INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
CSS Changing Attribute of Specific Button I have a button with the button class **button.ttfm2** but I want to change **button[type="submit"]:hover** this specific button: At the moment my current code is: .ttfm2 button[type="submit"]:hover { background-color: #28AE47 !important; } What am i missing?
The right code would be: button[type="submit"].ttfm2:hover { background-color: #28AE47; /* avoid using !important */ } You were trying to select the button of type submit inside ttfm2 element using descendant selector but you need to use the multiple selector i.e. the button that has a class `ttfm2` **Sample Output:** button[type="submit"].ttfm2 { transition: all ease 2s; } button[type="submit"].ttfm2:hover { background-color: #28AE47; } <button type="submit" class="ttfm2">Test</button> <button class="ttfm2">This will not work</button>
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "css, button" }
C++ operator overloading return pointer I'm fairly new to programming in C++ and I was wondering something: whenever I see operator overloading in C++ it's done like this: #ifndef STONE_H #define STONE_H class Stone { private: int weight; public: ....... Stone operator+(const Stone& s) { Stone stone; stone.weight = this->weight + s.weight; return stone; } ....... } #endif But when the "+" operator is called, it creates an object "stone", and returns a copy of this. This can't be good for performance when dealing with huge objects? Wouldn't it be better to use dynamic memory for this as in the example below: Stone * operator+(const Stone& s) { Stone * stone = new Stone; stone->weight = this->weight + s.weight; return stone; } Or am I seeing this wrong? Thanks in advance
Trying to reason things out is not particularly accurate way of estimating performance: you need to actually write a program to _measure_ whether or not one implementation is better than another. There are a number of ways in which no copy will happen at all; the named return value optimization (NRVO) and move assignment are relevant ideas here. Even if you decide that you want to do something like your suggestion, you shouldn't implement it as you have, since it has the wrong semantics: you've had `operator+` return a pointer-to-thing rather than a thing. Also, working with pointers (especially bare pointers) is risky, since it gives you a lot more opportunities to make mistakes. If you want to implement something along those lines, you need to wrap the pointer semantics in a class that provides value semantics.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c++, operator overloading, dynamic memory allocation" }
Javascript - if statement error Wondering if someone can steer me into the right direction, I'm trying to use Javascript to make a little game to help me learn. Essentially I declare all my variables which I want to change outside of my function so they act global, which works in the code but the if statement seems to be not proving successful, I cant seem to correct this as tutorials point to my code as correct, please see code below; var Refresh; Refresh = "InActive"; var Counter; Counter = 0; var StartTime; function StartGame() { var StartDate; StartDate = new Date(); StartTime = d.getTime(); Refresh = "Active"; } function FunctionB1() { if (Refresh == "Active"){ document.getElementById("Bean1").style.display = "None"; Counter ++; document.getElementById("BeanCount").innerHTML = Counter + " Out of 150"; } }
You need to change `d.getTime();` to `StartDate.getTime();` to reflect the change in variable name. function StartGame() { StartTime = new Date().getTime(); Refresh = "Active"; } JSFiddle: Solution Edited to include Xufox's improvement.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript" }
Is there anything wrong with assigning dynamically created objects to pointers that are private members of a class? For exemple, say that I have a Game class: class Game{ public: Game(); ~Game(); void CreateWindowClass(HINSTANCE); void CreateRessources(HINSTANCE); void ShowMainScreen(); Winsock* CreateWinsock(); MessageLog* CreateMessageLog(); D2DResources* CreateD2DResources(HWND); HWND Getm_hWnd(); public: D2DResources* pD2DResources; Winsock* pWinsock; MessageLog* pMessageLog; private: HWND m_hWnd; }; and the 3 pointers inside Game are assigned like this: Winsock* Game::CreateWinsock() { pWinsock = new Winsock; return pWinsock; } Will this cause any problem? Also, will I delete the dynamically created object like this: delete pWinsock;?
`pWinsock` is a public member, but either way there is nothing wrong with this. Both `pWinsock` and the pointer return value of the function are pointing at the dynamically allocated `Winsock` object. As long as you `delete` the object at some point, you don't have a memory leak. The only issue here is that the client of this function may `delete` the pointer themselves, while your `Game` object might rely on the `pWinsock` pointer being valid for a particular duration (perhaps for its entire lifetime). You can best express your intent by using a smart pointer. A `std::shared_ptr<Winsock>` would be a good choice here, as your `Game` object creates the `Winsock` and then shares ownership with the client.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "c++, pointers, memory management, dynamic, memory leaks" }
doctrine 2 query builder and join tables I'm trying to get all comments for each post in my home page return $this->createQueryBuilder('c') ->select('c') ->from('Sdz\BlogBundle\Entity\Commentaire' ,'c') ->leftJoin('a.comments' ,'c')->getQuery()->getResult() ; but I'm getting this error [Semantical Error] line 0, col 58 near '.comments c,': Error: Identification Variable a used in join path expression but was not defined before. PS : The mapping is correct because I can see the page article with its comments.
In case this is still giving you problems, here is your query using the syntax found in the examples in the Doctrine 2.1 documentation. I'm assuming your query resides in a custom repository method, and that 'a' is an abbreviation for 'Article'. $em = $this->getEntityManager(); $qb = $em->createQueryBuilder(); $qb->select(array('a', 'c')) ->from('Sdz\BlogBundle\Entity\Article', 'a') ->leftJoin('a.comments', 'c'); $query = $qb->getQuery(); $results = $query->getResult(); return $results;
stackexchange-stackoverflow
{ "answer_score": 38, "question_score": 19, "tags": "doctrine orm, left join, query builder" }
How to show hidden text on hover using CSS I would like to show text when the mouse hovers over a button or `<a>` tag. For example, I have this button with some text: ![Original button]( I have managed to make it larger when the mouse hovers over the button: ![Larger button on hover]( What I would like to do instead is keep the text and image on top and display some text beneath the button. Can anyone suggest how I might do this?
Not sure if thats what you are looking for since you didn't include your code... div { display: none; margin-left: 10px; } a:hover+div { display: block; } <a><img src=' <div>Display Whatever</div>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "html, css, button, hover" }
Is there anyway to create a Spring Aspect advice that triggers on any method that is NOT annotated by certain annotation? Basically I am trying to create a log system that will log most of the controller methods (their parameters, bodies, status codes and so on), however, there are few controller methods I do not want to log for some specific reasons. I do not want to create an annotation that indicates this method will be logged (because there are gonna be plenty), instead, I want to create an annotation that indicates this method should NOT be logged. Obviously, I cannot negate an annotation in a Spring Aspect advice, so is there any workaround for it? (such as getting a method's all annotations from `ProceedingJoinPoint`, then check if they contain that `NoLog` annotation)
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = joinPoint.getTarget().getClass() .getMethod(methodSignature.getMethod().getName(), methodSignature.getMethod().getParameterTypes()); CustomAnnotation annotation = method.getAnnotation(CustomAnnotation.class); Well, looks like you can use the above codes to attempt to get the `CustomAnnotation` on your methods, if your methods are NOT annotated by this `CustomAnnotation`, a `null` will be returned, otherwise a `Proxy` object will be returned
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, spring boot, java annotations, spring aspects" }
Mobile version of website: adjust to screen size I realize that creating a mobile version of a site is a complex matter. However, I've noticed specifically that most large websites when you surf to them in mobile browser ie safari on iphone fill up whole page instantly. In contrast, my site displays small including font size, has white space at borders, and you need to adjust it by hand to fill up iphone screen. I gather part of solution is to replace pixel specifications with percentages. Is there anything else needed to make site instantly fill up pane, perhaps something about html doctype at beginning or other metadata?
add viewport meta tag <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "mobile, web, screen, resolution" }
Writing an AI: screen capture and input I'm considering a pet project to write an AI for a simple game on Windows (C++/python preferred). Can you instruct me on what is the way to go for grabbing simple screen captures, so that I can do some very simple object recognition/find out what is such and such pixel color basically. And also I'd need to manage input (moving mouse, click etc)? I'm mostly a linux guy, so I bet here I'd need to use some DirectX API to inject events? Thanks
I once did that for breaking the record for Bejeweled Blitz. Turns out computers are much faster than _all_ humans who don't use cheats. Since the game I created a robot for was a flash game running inside a browser a few years ago, I only needed to use ordinary Win32 API calls to grab the screen content and to send mouse events. You can start reading here a little bit about grabbing screen content, and here about simulating mouse input. I think you'd be better off using .NET instead of C++. If you're really fond of Python, try IronPython, since it's .NET based, it'll make interfacing with the Windows APIs a lot easier.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "c++, python, windows, directx, artificial intelligence" }
Same width for all cols Boostrap4 I am using Bootstrap since a while, but I am stuck with the problem. After the Bootstrap 4 npm installation, I have **col-xs-1** and **col-xs-12** same **width:100%** I inspected library files I installed and I have same width for all elements (xs, md, lg etc.). **What should I do?** Bootstrap v.4.5.3 Bootstrap.min.css image here frontend inspection here
Thanks to Ahmed Tag Amer, the solution is: `col-xs-12` must be in `row` class
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 0, "tags": "bootstrap 4" }
Retrieve a record from table with particular datetime I need to retrieve a record with specific DateTime in SQL Server. Tried with many options like select * from test where convert(datetime ,imported_date) = convert(datetime,'2020-06-16 22:00:07') imported_date is of datetime2 datatype. Less than and Greater than is working but equals condition is failing. Please help
Possibly, your datetime has fractional seconds. If so, I would recommend phrasing this as: where imported_date >= '2020-06-16 22:00:07' and imported_date < '2020-06-16 22:00:08' This is much more efficient than using conversion functions on the datetime column, since it allows the database to make use of an index on that column, if any. If you are working with a parameter: where imported_date >= @param_date and imported_date < dateadd(second, 1, @param_date)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql server, date, jpa, select, where clause" }
How to stop the thread in android activity I am developing an android application which works on threads How to stop or destroy the thread in android while i was passing to the next activity can any one tell me please i am new to this
In onStop() method, call interrupt as follows: yourThreadObject.interrupt() and in the run() method of the thread, have a condition that checks for Thread's interrupt status. Depending on your implementation, you might want to enclose this check within a while loop as, public void run() { while (!Thread.interrupted()) { //do something ... } } or you might check at certain points in the run() method as, public void run() { //do something ... if (Thread.interrupted()) { return; } //do something ... }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -6, "tags": "android, multithreading" }
IPython error executing system commands If I execute any system commend in ipython2/3 on my Ubuntu 16.04 machine, I get permission denied error as follows: In [1]: ls -------------------------------------------------------------------------- PermissionError Traceback (most recent call last) <ipython-input-1-5b21b94dda0e> in <module>() ----> 1 get_ipython().magic('ls ') I did not need to do anything special in Ubuntu 14.04. I have installed ipython2 and ipython3 with pip2 install ipython --user pip3 install ipython --user I also tried installing it system-wide with `sudo` as sudo pip2 install ipython sudo pip3 install ipython But the problem still persists. I do not get this problem in jupyter notebook. How can I use system commands in IPython?
When I was setting up my machine, I created a dummy rootUser as the first _admin_ user. Later on, I created another user with the same _name_ , _uid_ and _gid_ as my workplace and added it to _sudo_. This some how causes permission problems which is really strange. Though I do not know the actual cause of the problem but I did reproduce it with the above steps. I solved this problem by creating the first user with the name same as my workplace. Later i changed the _uid_ and _gid_ and file/directly permissions accordingly. This solved the problem and I can now use ipython2/3 normally.
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 1, "tags": "ipython" }
How to set Content-Disposition header using Django Rest Framework I am serving an image using the Django REST framework. Unfortunately it downloads instead of displays. I guess I have to set the header `Content-Disposition = 'inline'`. How do I do this in the `View` or the `Renderer`? class ImageRenderer(renderers.BaseRenderer): media_type = 'image/*' format = '*' charset = None render_style = 'binary' def render(self, data, media_type=None, renderer_context=None): return data class ImageView(APIView): renderer_classes = (ImageRenderer, ) def get(self, request, format=None): image=MyImage.objects.get(id=1) image_file = image.thumbnail_png.file return Response(image)
According to this page in the Django docs, you can set the `Content-Disposition` header in this way: response = Response(my_data, content_type='image/jpeg') response['Content-Disposition'] = 'attachment; filename="foo.jpeg"'
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 9, "tags": "django, django rest framework" }
How can block azure aks get-credentials --admin and allow azure aks get-credentials only on azure? Use `azure aks get-credentials --admin` can get kubernetes admin config file and `azure aks get-credentials` can get only user config file on azure. How to set something to deny user run `azure aks get-credentials --admin`?
well, be default they cant run it, unless they have specific azure permissions. so by default you dont have to do anything. they shouldnt have this specific permission: Microsoft.ContainerService/managedClusters/listClusterAdminCredential/action which they would get if they are contributor for the AKS resource or resource group. They need this permission to get user credentials: Microsoft.ContainerService/managedClusters/listClusterUserCredential/action
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "azure, kubernetes, config, admin" }
in vb.net I want to loop charts I want listbox1 item = aa ab ac ba bb bc ca cb cc And this my code Dim text As String = "abc" Dim i As Integer = 0 Do ListBox1.Items.Add(text.Chars(i)) i += 1 Loop Until (i = text.Length)
Use this, you need 2 loops: For i as Integer = 0 to 2 For j as Integer = 0 to 2 ListBox1.Items.Add(text.Chars(i) & text.Chars(j)) Next Next
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "vb.net" }
How to run cron on same time in different time zones? I have one cron which I want to run around 6:00 am in IST and same cron should also run same time 6:00 am EAT. I am using synced-cron for running cron jobs on my meteor server. If I have only few timezones to support I would have ran this cron 2 times a day and it would have worked but I have multiple timezones to support in future. How can I automate same thing with little effort.
You will need to set the cron job to run every half an hour, and then look for work based on the timezone that the user is in. So for example you need to send a daily email digest at 6am in each timezone. Let's assume that you have the events for each user in a collection of some kind. Each user record needs to include a timezone that the user is in. When the cron job runs, you do a query to find the users that need to receive a digest that are in the timezone where it is currently 6am. Then you send the email and clear out the queued events.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "node.js, meteor, cron, timezone" }
Node.js HTTP Get URL Length limitation Is there a limit to the size when making HTTP GET requests in Node.js? And if so, how can I change this? var url = "..." // very long, ~50'000 chars http.get(url, function (res) { res.pipe(fs.createWriteStream("file.txt")); }); Gives me this: <html><body><h1>400 Bad request</h1> Your browser sent an invalid request. </body></html> Same thing using wget in PowerShell or Bash works perfectly fine. $url = "..." wget -outf file.txt $url
There is a built-in request size limit enforced by Node. Requested headers + URI should not be more than 80 kb. As it is defined in http_parser.h#L55: /* Maximium header size allowed */ #define HTTP_MAX_HEADER_SIZE (80*1024) Asuming that UTF-8 character can be between 1 and 4 bytes, the size of a string with 50 000 characters would be from 50 000 to 200 000 bytes, or from ~48kb to 195kb.
stackexchange-stackoverflow
{ "answer_score": 31, "question_score": 24, "tags": "javascript, node.js, http" }
Auto completion in xcode In XCode 3.2.2 completion works whenever it chooses to. One time it will, one time it won't. Is there some flag or add-on to increase the auto-completion success rate ??? Is there maybe a better code editor that can link to xcode in a good manner which has better coding capabilities then XCode ? Thanks
I don't know. Maybe it depends on the way you code but it works for me most of the time. There is some case that it will not work, for example, too much complicated like `[[self.a doB] doC];` Can you post me some code that it doesn't work for you?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "iphone, xcode" }
JasperServer: how to change "Jaspersoft: Login" page name to our "Organization: Login" page How to change "Jaspersoft: Login" page name to our "Organization: Login" page, when we login on `JasperServer` default page name is Jaspersoft: Login? You can see in browser after login.
You can find in `WEB-INF\jsp\decoratos\decorators.jsp` Here you will find Japsersoft default message you can edit that tile or you can edit in `pro_nav_messages.properties` found in bundles and print their and reflect this in your `decorator.jsp` E.g. <!--default> <title>Jaspersoft: <decorator:title /></title> <!--customized message where we edited pro_nav_messages.properties with NAV_020_FULL_TITLE code > <title><spring:message code='NAV_020_FULL_TITLE'/></title>
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "jasper reports, jasperserver" }
Android : restart the service My application have a Service that every X minutes do same action on the database than it stopSelf() and into onDestroy method I have palced this code for restart the service after same time: @Override public void onDestroy() { super.onDestroy(); Intent intent_service = new Intent(context,vampireService.class); PendingIntent pintent = PendingIntent.getService(context, 0, intent_service,0); AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarm.set(AlarmManager.ELAPSED_REALTIME,SystemClock.elapsedRealtime()+ 4500000, pintent); } But I don't understand why if my phone go in sleep mode the service not restart ! Appears that the count time of AlarmManager to start when I power back up the display....it's possibile ? If yes, how can I resolve this problem ? Thanks
From the documentation for ELAPSED_REALTIME... > **This alarm does not wake the device up** ; if it goes off while the device is asleep, it will not be delivered until the next time the device wakes up. Try using ELAPSED_REALTIME_WAKEUP to see if that helps (not sure if it will work for a service however).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, service, alarmmanager" }
How to inherit controls created at runtime? I have two forms,one is main and other is inherited form main.Lets say I have a function on the main form: procedure FormMain.CreateButton; begin with TsButton.Create(Self) do begin Width := 31; Height := 31; Left := 31; Top := 31; Visible := true; Parent := Self; end; end; Usually everything on the main form should be on the inherited form,but this is what I do: I call CreateButton from mainForm ,but the button is only on the main form. Is it possible to inherit that button too?
There's a difference between design-time and runtime. The form designer creates a definition for your form, which it instantiates at runtime. If you inherit one form from another, then it takes the base template and adds to it. But form-designer forms are only templates, like class definitions. Now, at runtime, you instantiate a base form and a derived form, and it creates them from the templates stored in the resource section of your app. If you add something to the instance of the base form, you're modifying an individual instance, not the definition, so of course it's not going to show up on another instance. If you want to add a button dynamically to a form, you have to create it on that instance (in this case, the derived form) individually.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "delphi, inheritance" }
RxAndroidBle "LOCATION_PERMISSION_MISSING" Доброго времени суток :D Подскажите пожалуйста из-за чего может возникать ошибка " **LOCATION_PERMISSION_MISSING** ", при вызове метода `scanBleDevices`? Уже час ломаю голову не чего не могу придумать. Фрагмент кода : import com.polidea.rxandroidble.RxBleClient; import com.polidea.rxandroidble.RxBleScanResult; import rx.Observable; /** * Created by johny on 02.01.2017. */ public class bluetooth_controler { public void rxScan(RxBleClient client){ Observable<RxBleScanResult> scanSubscription = client.scanBleDevices(); } } P.S. В гугле тщательно поискал, пусто. P.S.S. Пробовал добавить в манифест `<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />`
Дело в том, что сканирование окружающих устройств может дать информацию о местоположении устройства. Поэтому начиная с Android 6.0 (API level 23) для этого необходимо запросить `android.permission.ACCESS_FINE_LOCATION` или `android.permission.ACCESS_COARSE_LOCATION`. Это касается как списка bluetooth устройств, так и MAC адресов и SSID WiFi сетей. Одновременно с этим в 6.0 появились runtime permissions: пермишены, попавшие в группу опасных (dangerous), нужно не только указать в `AndroidManifest.xml`, но и запросить у пользователя явно. Доступ к местоположению входит в их число. Подробнее об этом написано в документации. Для эксперементов на этапе разработки можете в Settings в списке приложений найти ваше, зайти в раздел Permissions, и там руками дать разрешение.
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, bluetooth, permissions, android bluetooth" }
How is an Airbus A380 fuselage joined and fastened together? An Airbus A380 fuselage is manufactured in three different parts and then assembled together: ![enter image description here]( ![enter image description here]( (Images courtesy of Airbus S.A.S 1994) The fuselage functions under extreme conditions: low pressure outside and normal pressure on the inside (normal for humans, that is), and wind drag at near Mach 1 speeds. How are the three parts joined together to complete an airtight unit? Does one fit into the other in a male-female configuration and how are they held together? Is it nuts and bolts, rivets, screws, airtight glue or a combination of them all? Pictures would be greatly appreciated.
With approximately 19,000 rivets. This picture is of the wing attachments, but the fuselage joints use the same attachment method. ![enter image description here](
stackexchange-aviation
{ "answer_score": 5, "question_score": 5, "tags": "airbus a380, fuselage" }
CSS: Hide Scrollbar. I know how to hide scroll bar. But **without a scroll bar** , I would like to scroll whatever there is to scroll. This is what I did, it hides initially, and as mouse hovers, vertical scroll bar shows. div#LogoStrip{ height:600px; overflow:hidden; } div#LogoStrip:hover{ overflow-y:scroll; overflow-x:hidden; } But **on hover** , I **don't want to see scrollbar but still would like to scroll the text/images that are present there** , using wheel or two small buttons, 1 at top and 1 at bottom. div#LogoStrip{ height:600px; overflow:hidden; } \+ `javascript` can you help with Javascript/jQuery ?
If you really want to code this yourself (and I would again caution against it), you can look through the jScrollPane code. The basic idea is that you have a div within a div, one will hid the contents of the other when set to an offset. You have to capture the scroll wheel event and change that offset.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, jquery, css" }
Why is output of adb devices inconsistent? I'm running android emulator on Mac, the output of `adb devices` is different every time I run it, [PWD: ~/Library/Android] %> adb devices List of devices attached emulator-5564 offline emulator-5562 offline emulator-5560 offline emulator-5554 offline emulator-5556 device [PWD: ~/Library/Android] %> adb devices List of devices attached emulator-5560 offline emulator-5556 device What could the problem be? I already killed the server and restarted it.
Totally sad story! I have programs listening on local ports `5551, 5553, 5554, 5555, 5561` etc. And adb is connecting to these ports which receives unexpected response, resulting in inconsistent output.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "android" }
Difficulty with translation for "We like; they like" My son is doing online assignments for class which consist of turning very simple English snippets into French. I'm trying to help out but, since I haven't done French myself for forty-odd years, I'm struggling. The online assignment is asking for the translation of "we like; they like" which is tripping me up, despite `aimer` being a regular verb, which is supposed to be easy :-) It appears that this is either 1st or 3rd person plural, which would be `nous aimons` or `ils/elles aiment`, based on the French guide we have. Yet the test is insisting it's `on aime`. Why is this so? Google Translate state that both `on` and `nous` translate to "we" and I don't understand the distinction. And, if they _do_ both mean "we", why is it `on aime` (1st/3rd singular) rather than `on aimons`?
Using 'on' as the first person plural has become very common in spoken French, so common that you would be hard pressed to find anyone actually using 'nous' in conversation. 'Nous' is still however very present in written French, for example in story telling or official documents. In summary: there is no distinction in meaning, just in formality.
stackexchange-french
{ "answer_score": 3, "question_score": 2, "tags": "verbes, conjugaison" }
Why does moment not recognize the .add method? moment=require('moment'); const now= moment(); const dateFormat1 = 'MMDDYYYY'; this.todaysdate = () => (`${now.format(dateFormat1)}`); this.futuredate= () => (`${now.format(dateFormat1).add('days', 5)}`); When I run this, I get that add is not a recognizable function. numerical Begindate works fine.
A `string`, which is returned from `format`, doesn't have `add` on it's prototype. Try to add on the moment instead now.add('days', 5).format(dateFormat1)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, momentjs" }
Perl: Return anonymous array from a subroutine I'm trying to return an anonymous array from a subroutine, however, when dumping the returned variable I only see one value (I'm expecting two). Here is my code: #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $fruits_ref = generate_fruits(); print "Fruits: " . Dumper($fruits_ref) . "\n"; sub generate_fruits { return ("Apple", "Orange"); } This outputs: Fruits: $VAR1 = 'Orange'; How do I get the subroutine to return that array ref?
You're not returning an array (or a reference to array), you're returning a list. A reference to anonymous array is `["Apple", "Orange"]` List becomes its last element when you pass it to scalar context. To pass to list context, you could do my @fruits = generate_fruits(); But that is likely not what you need - you seem to need a reference. For that, just use square brackets. Oh, another alternative is my $fruits_ref = [generate_fruits()];
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "perl" }
Install updates for a Device-Owner App Does anyone know what is the behavior in production of a device-owner App, distributed thru Google Play, when updates occur? As we know, installing a device-owner App involves some motivation and is not easy: reset to factory default then NFC-provision the device with a second device etc… So even if we consider this step done, would any further update involve so much pain, each time? This question occurs because on my development device, I cannot re-launch the device-owner App with changes if it was previously installed… unless I reset the device to factory settings! Thanks for reading…
Once your Device Owner app is set, a new file is created under _/data/system/device_owner.xml_ that references the Device/Profile owner apps. The Android system is then reading this file to check which application is considered as _Device Owner_ or _Profile Owner App_. This file contains refers to the applications by using their package name. Updating these apps won't infer on this file since the package name stays the same. When you're updating your app, just make sure you're always using the same certificate as the one you previously used when first setting you device owner for the first time (which is a standard rule of security for every application update in Android anyway). Permissions can also be updated the same way, without the need to reprovision it through NFC, nor `dpm` tool.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 5, "tags": "android, android 5.0 lollipop, device owner" }
find open balls $B_1,B_2,B_3,\ldots$ so: $U=\bigcup _{n\in \Bbb N} B_n$ , where $U=\{(x,y)\in \Bbb R^2 : y\gt x\}$ > In the metric space $(\Bbb R^2,d_{\Bbb R^2})$: How can I find open balls $B_1,B_2,B_3,\ldots$ so: > > $U=\bigcup _{n\in \Bbb N} B_n$, where: > > $U=\\{(x,y)\in \Bbb R^2 : y\gt x\\}$. > > and why it is not possible to do this for: $U'=\\{(x,y)\in \Bbb R^2 : y\ge x\\}$.
Consider $$ U = \bigcup_{x\in U\cap \mathbb Q} B(x;r_x) $$ where $$ r_x~=~ d(x,\partial U) $$ is the distance between point $x$ and the line $\\{(x,x):~x\in\mathbb R\\}$. If you want uniformly bounded balls you may consider $r_x'=\min\\{r_x,1\\}$ as radiuses. In both cases the union is countable and entirely covers $U$. Since $B(x,r_x)\subseteq U$ for every $x\in U\cap \mathbb Q$, then the union is contained in $U$ and therefore the equality above holds. The second set ($\overline U$) is closed, while unions of open balls is still open. The only sets which are both open and closed are $\mathbb R^2$ and $\emptyset$, so $\overline U$ cannot be expressed in such way. You may find a _covering_ , but it will never coincide with $\overline U$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "metric spaces" }
Logout using session in asp.net I'm trying to clear session in 'logout' link using`Session.Abandon();`. After Logout I redirected back to login page.But even after logout I could visit previous pages using browser's back button. How can I solve it?
Based on your comments, your session HAS been abandoned. What you're seeing is a "snapshot" of the page saved in the cache by the browser. As long as in your code behind you make sure that you have a valid session before allowing the user to perform any tasks on your pages, you should be fine. There are various answers on how to try and disable the cache, so that pressing the back button won't show the previous page - but as far as it goes to your question - you HAVE logged out and your session IS gone...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "asp.net" }
Generic way to convert a string into a numerical type? I have this class: template<typename T> class Parser { public: Parser() : count(0) {} virtual void parse(const string&); void get_token(void); private: T result; char token; string expression; int count; }; now had the class not been generic, had the `result` been say, a `double`, I would have used this method to detect numbers. while((strchr("1234567890.",token)) { /* add token to a "temp" string */ /* etc. etc. */ } result = atof(temp.c_str()); But since `result` is generic, I can't use any method like `atof` and `atoi` etc. What do I do?
Boost has this functionality built-in: #include <boost/lexical_cast.hpp> void Parser<T>::get_token() { std::string token = ...; result = boost::lexical_cast<T>(token); } Add exception handling as required. * * * Or, perhaps you don't want to use Boost for some reason: void Parser<T>::get_token() { std::string token = ...; std::stringstream ss; ss << token; ss >> result; } Check the error state of `ss` as required. * * * More expansive answers may be found on this related question, though it discusses only `int` specifically.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "c++, string, generics, types, casting" }
Child elements break out of parent, even though parent has no height set? This is probably pretty hard to explain, so for good measure, I've placed a mock-up on JsFiddle: < I have `#box-cont` with no set height, which usually (at least from my experience anyway), means that it takes the sum heights of all of it's nested elements + any padding. However, `.valid` and `.invalid` (which as far as I can tell are contained within `#box-cont`)seem to be running off the bottom, not only of `#box-cont` but of `.box-bottom` too. On to the question, can anyone point out why this is happening? I've gone back and forth in attempt to diagnose what the problem is to no avail :(. Any help would be greatly appreciated ;)!!
So long as the `height` is not set explicitly on the div with an `id` of `box-cont`, you can simply set: `overflow: hidden;` JS Fiddle demo.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "html, css" }
Why the original element got changed when I modify the copy created by .dup method? Ruby and REXML I just tested the following steps in irb and got something odd: require 'rubygems' require 'rexml/document' include REXML e1=Element.new("E1") e2=Element.new("E2") e1.add_element(e2) e1Dup=e1.dup puts e1 puts e1Dup e1.delete_element(e1.elements[1]) puts e1 puts e1Dup I only want changes on e1, however, the result shows both element got changed. How could this happen? The result is below: <E1><E2/></E1> <E1><E2/></E1> <E1/> <E1/>
Ruby's `dup` function only makes a shallow duplicate of the object. Its internal data, such as that stored in attributes (which is what the `elements` method is accessing) does not get duplicated. So you have two totally distinct objects `e1` and `e1Dup`, but their _children_ are the same. In C++, you would say that the two pointers are accessing the same memory location. To fully duplicate the tree of elements, you would have to recursively call `.dup` on each child node and replace them on the duplicated `e1Dup`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby, rexml" }
My webpage won't let me scroll? I'm making a webpage where I have a div ("container") that is a parent to the div "rounded". For some odd reason, the webpage doesn't let me scroll down even though both of the divs' height are larger than the screen. Here's a jFiddle with the components that aren't working out: < Any ideas as to why this isn't working?
You need to take the `position:fixed` off the `.container` so that it allows the page to be scrollable **EDIT** Check this out here < I think this is what you are looking for. I took out the non relevant css so don't just copy and paste to yours. I eliminated your background rounded image in place of using `border-radius` because by using a background image you can't really shrink or expand depending on content. This won't work on older browsers unless you use webkits and so on. If you want to use an image I would suggest slicing the image between a top, bottom, and middle. The top would contain the top section with the radii. The middle would be 1px tall that repeats vertical as needed. The bottom would contain the bottom section with the radii.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "html, css" }
Haskell string manipulation. Non-exhaustive patterns in function error I am trying to solve a simple problem on HackerRank and am receiving the error in the title. The problem asks to take in a string and reduce it by removing adjacent pairs of letters. So "aabcdd" => "bc" for example. Here's my code: main :: IO() main = do line <- getLine putStrLn (reduce' line) reduce' :: String -> String reduce' [] = [] reduce' (x0:x1:xs) | x1:xs == [] = [x0] | x0 == x1 = reduce' xs | otherwise = x0 : x1 : reduce' xs I am confused because I think I have the edge cases covered. I don't want an answer to the problem, I just want to know why I am getting the error. Thanks!
You are not matching the case where you have only one element in the list reduce' :: String -> String reduce' [] = [] reduce' [x] = [x] reduce' (x0:x1:xs) | x0 == x1 = reduce' xs | otherwise = x0 : x1 : reduce' xs This `| x1:xs == [] = [x0]` is the pattern matching added, so there is no need to check in the guards.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "string, parsing, haskell" }
Add an exception to Joomla's .htaccess rewrite rules to allow an Owncloud subdirectory i'm actually use Joomla in our website and i would like to add Owncloud. The .htaccess in the root let Joomla side works without trouble: RewriteEngine On RewriteCond %{REQUEST_URI} !^/Joomla3 RewriteRule ^(.*)$ Joomla3/$1 [L] But if want to access the owncloud service, i get this error: > The requested URL /Joomla3/owncloud/ was not found on this server. It seems the original rewrite works with the owncloud directory too. my host is composed by 1 root directory and the 2 subdirectory: * -root * \--Joomla * \--Owncloud How can I set .htaccess to 1. rewrite URL from my website (example.com) into `www.example.com/Joomla` 2. access owncloud (without rewrite) in the directory `www.example.com/owncloud`
> > RewriteCond %{REQUEST_URI} !^/Joomla3 > RewriteRule ^(.*)$ Joomla3/$1 [L] > What these directives do is... if the requested URL does not start "/Joomla3" then internally rewrite the request to the "Joomla3" folder. What you need to do is add another condition to state that... if the requested URL does not start "/Joomla3" **and it does not start "/owncloud"** then internally rewrite the request to the "Joomla3" folder. For example, this could be achieved by adding a second `RewriteCond` (condition) directive: RewriteCond %{REQUEST_URI} !^/Joomla3 RewriteCond %{REQUEST_URI} !^/owncloud RewriteRule ^(.*)$ Joomla3/$1 [L] `RewriteCond` directives are implicitly AND'd.
stackexchange-webmasters
{ "answer_score": 2, "question_score": 3, "tags": "htaccess, apache, joomla" }
To find a DOM element using jQuery and replace its string I have a very complex DOM structure, A small for example or say demo of code, <div> <div class="test_data"> <span>sample 1</span> <span>sample 1</span> <span>sample 3</span> <span>sample 1</span> <span>sample 2</span> </div> </div> Now on above example, I have to find all the ****tag having **sample 1** and want to replace it by another string say as **example** , I want to do this stuff using jQuery.
$('.test_data span:contains(sample 1)').html('sample'); # crazy demo but I think you want more than this. Well maybe this will help someone. $('.test_data span:contains(sample 1)').html(function(i,html){ return html.replace('sample 1','sample'); }); this will replace the particular text. # crazy demo
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, html" }
Is there any DatePicker control for Qt 5? I'm writing my first QML/Javascript app for QtQuick 2.0. I need to place a **DatePicker** control, but I haven't found any control like that under _QtQuick.Controls_ -and nowhere, in fact-. I'm starting to believe there is no way to call a 'native' DatePicker in QML. Do I have to implement one or there is exist one?
Well, I had to make my own control. It is called **Datepicker**. !Datepicker example It is intented to used in this way: import QtQuick.Controls 1.1 ApplicationWindow { id: main Datepicker { id: myDate activeWindow: main width: 200 } } It asumes you are using it from a `Window` object, and needs the parent reference to show the datepicker in the correct position (it shows a calendar in a new window). You can download the source code from: < This is the first version and need a lot of polish to be ready, but is a start point.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 13, "tags": "datepicker, qml, qtquick2" }
When should a type be a struct containing another type and when should it just "extend"(?) that type? I'm currently learning Go by doing the rosalind problems (basically a bunch of bioinformatics related code katas). I'm currently representing a DNA strand with a type: type DNAStrand struct { dna byte[] } My initial reason was to encapsulate the byte slice so I would know it only contained bytes representing the nucleotides: `'A', 'C', 'G', 'T'`. I realized that this was obviously not guarateed since I could simply do: DNAStrand{[]byte("foo bar")} And there is no longer any guarantee that my dna strand contains a byte array with only elements from those four bytes. Since my struct only contains a byte array is it better/more ideomatic to do: type DNAStrand []byte Or is it better to let the type contain the dna strand? Are there any rules of thumb for when to use either of the two approaches?
Struct with zero fields are handy. Structs with many fields are handy even more. Structs with exactly one field are a bit special and I can't think of a reasonably "good" case where to use them - even though they are seen regularly "in the wild". I, for one, don't use them. Anyway, if you really really need tighter/bulletproof safety about the `DNAStrand` slice content - then it is possible to to use the single field struct and define an argument checking setter method for this/such named type. In that case, if the definition is later used from some other package, there's no way, modulo using package unsafe, to circumvent the checks and get a result equivalent to your `DNAStrand{[]byte("foo bar")}` example.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "types, struct, go" }
I have a question about Python the numerical computation of letters df = pd.DataFrame({'num':['9','','3','7','11']}) col_nm = 'num' print(df) num 0 9 1 2 3 3 7 4 11 If the num is greater than 5, I will convert it to 5. But after the number 10, there is no conversion. string ="np.where(num == '',num,np.where(num >= '5', '5', num))" string = string.replace(col_nm,"df['"+col_nm+"']") df[col_nm] = eval(string) print(df) num 0 5 1 2 3 3 5 4 11 Is there any way to solve the logics using data and string while keeping them intact?
We need first convert `to_numeric` then use condition assign df['num'] = pd.to_numeric(df['num'],errors='coerce') df.loc[df['num'].between(5,10),'num'] = 5 df Out[97]: num 0 5.0 1 NaN 2 3.0 3 5.0 4 11.0
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, pandas, numpy, dataframe, eval" }
array extract with php I have a problem with extract value on array multidimensional, print_r array: Array ( [0] => Array ( [0] => Array ( [referent] => vespucci ) [1] => Array ( [referent] => colombo ) ) [1] => eb38f736ef826180218c8c0c804f7bebe6d995c1 ) I'd like extract 'referent' values but if I get this error of nested foreach: Warning: Invalid argument supplied for foreach() in exactly in line of second foreach: foreach($posts as $post) { foreach($post as $po) { $change[] = $po; } } where am I doing wrong?
It is because of the second element of your array that is not an array; You could do this by: foreach($posts[0] as $post) $change[] = $post; And if you only want the referent value you could use: foreach($posts[0] as $post) $change[] = $post['referent']; And here is general: foreach($posts as $post){ if( is_array($post)){ foreach($post as $po){ if(isset($po['referent'])) $change[] = $po['referent']; } } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, arrays, multidimensional array" }
Get my private key I've just recieved a certificate from Commodo. The ZIP file contains a xxx.crt and xxx.pb7b I need to convert the xxx.pb7b file in to a xxx.pfx so that I can import it in IIS. I'm using OpenSSL for the conversion, but I need a private.KEY file. Is there away to get\extract this file??
Export the current certificate (PFX) that is about to expire. This file contains your certificate and public key. Then use OpenSSL to extract the private key from the PFX file. **openssl pkcs12 -in myfile.pfx -nocerts -out private_key.pem -nodes**
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "private key, pfx, crt" }
Meaning of "shot" cloth > "A truly beautiful shade! A cloth of smoked grey, shot with flame colour!" —Gogol, trans. by D. J. Hogarth 'Shot' is what is confusing me. In my mind I imagine it refers to a repeated pattern. My best guess as to what it would look like is this, on the right: !Image of silk scarves
Shot in ODO > **1** (of coloured cloth) woven with a warp and weft of different colours, giving a contrasting effect when looked at from different angles: > _a dress of shot silk_ > \- interspersed with a different colour: _dark hair shot with silver_ > \- (shot through with) suffused with (a particular feature or quality): _the mist was shot through with orange spokes of light_ It's not a repeated pattern; it's a highlight of some sort, either the odd thread, or the entire warp or weft. In the quote, it could be either, but since a different warp and weft would give rise to "a truly beautiful shade," it's probably that: woven throughout with two different colours. I couldn't find an example of grey and red, but here's blue and red from the blog Snoring Scholar: !Shot silk
stackexchange-english
{ "answer_score": 10, "question_score": 4, "tags": "meaning, literature" }
Alternatives to finish() to remove an Activity from view. At present I have a main Activity which has a number of buttons leading to other screens which will allow the user to build up a number of search criteria. The search criteria are passed back to the main activity via extras on the intent. the sub activities are started with StartActivityForResult and then when the user has made a selection I call finish() to return to the main screen. However I'm now wanting to keep the sub activities in memory so that the user can go back, see what they have entered and adjust the search criteria rather than re-entering it from scratch. How do I swap back to my main activity without losing the state of the sub activity? Thanks, m
From your description it looks like main activity receives data from all sub-activities. It also sounds like this data is enough to restore the state of each subactvity. You could start sub-actvities with already known search criteria in the `Intent`. So each sub-actvitiy could restore its state from intent on `onCreate()`. Here is a sequence of events: 1. Application starts, Main Activity starts. 2. User presses button: Main Activity -> Intent ( **empty** ) - > Sub-Activity 3. User completed search criteria: Sub-Activity returns -> Intent ( **search criteria** ) -> Main Activity 4. User presses button: Main Activity -> Intent ( **search criteria** ) -> Sub-Activity So on step 4 Main Activity would pass the state received on step 3.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, android activity" }
minimum-maximum entries matrix Let $M(n)$ be an $n\times n$ matrix in the variables $x_1,\dots,x_n$ with entries $$M_{i,j}(n)=\frac{x_{\max(i,j)}}{x_{\min(i,j)}}, \qquad 1\leq i,j\leq n.$$ I'm interested in the following: > **Questions.** > > (1) Is there a neat or "closed form" evaluation for the determinant $\det M(n)$? > > (2) Is there an explicit formula for the inverse of $M(n)$? Thank you.
Let us write $$a_r=\frac{x_{r+1}}{x_r}$$ for $r=1\cdots n$. We can then write the matrix $M(n)$ in the form $$\begin{pmatrix} 1 & a_1 & a_1a_2& \cdots & a_1a_2\cdots a_{n-1} \\\ a_1 & 1 & a_2& \cdots & a_2\cdots a_{n-1}\\\ \vdots & \vdots & \vdots &\ddots & \vdots\\\ a_1a_2\cdots a_{n-1}& a_2\cdots a_{n-1} &\cdots & a_{n-1} & 1\end{pmatrix} $$ We do now Gauss elimination, and reduce $a_{n-1}$ times the $(n-1)$-th row from the $n$-th row. We then get in the last row $0, 0, \ldots (1-a_{n-1}^2)$. But this means that $det(M(n))=det(M(n-1))(1-a_{n-1}^2)$ and by induction $$det(M(n)) = \prod_{r=1}^{n-1} (1-a_r^2)=\prod_{r=1}^{n-1}(1-\frac{x_{r+1}^2}{x_r^2}).$$ By using inductively the Gauss elimination mentioned above, one can also get the inverse of $M(n)$.
stackexchange-mathoverflow_net_7z
{ "answer_score": 10, "question_score": 5, "tags": "co.combinatorics, linear algebra, matrices, determinants, matrix inverse" }
Regexp to match words two by two (or n by n) I'm looking for a regexp which is able to match words n by n. Let's say `n := 2`, it would yield: `Lorem ipsum dolor sit amet, consectetur adipiscing elit` `Lorem ipsum`, `ipsum dolor`, `dolor sit`, `sit amet` (notice the comma here), `consectetur adipiscing`, `adipiscing elit`. I have tried using `\b` for word boundaries to no avail. I am really lost trying to find a regex capable of giving me `n` words... `/\b(\w+)\b(\w+)\b/i` can't cut it, and even tried multiple combinations.
Regular expressions are not really what you need here, other than to split the input into words. The problem is that this problem involves matching **overlapping** substrings, which regexp is not very good at, especially the JavaScript flavor. Instead, simply break the input into words, and a quick piece of JavaScript will generate the "n-grams" (which is the correct term for your n-word groups). const input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit"; // From an array of words, generate n-grams. function ngrams(words, n) { const results = []; for (let i = 0; i < words.length - n + 1; i++) results.push(words.slice(i, i + n)); return results; } console.log(ngrams(input.match(/\w+./g), 2));
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, regex, node.js, text, nlp" }
DICOM Deflated Explicit VR Little Endian (1.2.840.10008.1.2.1.99) How is the data in this transfer syntax organized? A description from the standard: > This Transfer Syntax applies to the encoding of the entire DICOM Data Set. The entire Data Set is first encoded according to the rules specified in Section A.2. The entire byte stream is then compressed using the "Deflate" algorithm defined in Internet RFC 1951. Initially I took this to mean the entire DICOM file itself was gzipped. But if the entire file is gzipped, including the header which contains the identifying transfer syntax, how would a parser/viewer be able to read the transfer syntax to know it is gzipped? From the perspective of a viewer which is given a file of this type, how can it know it is of this transfer syntax? Look for a GZIP header? Are there any publicly available sample images which use this transfer syntax?
For the examples pointed to by @Springfield762, each of the `_dfl` files had a valid deflate stream from 300-some-odd bytes to eight bytes from end. They each decompressed to something about the length of the corresponding file in the archive without the `_dfl` suffix, but the data was not the same. There is additional decoding needed to get from the decompressed data to the original. `image_dfl` has a deflate stream that starts at offset 334, `report_dfl` at 348, and wave_dfl at 314. They decompress to 262682, 6178, and 62408 bytes respectively. The last eight bytes after each deflate stream are the same as a gzip trailer, i.e. the CRC-32 of the decompressed data (four bytes) followed by the uncompressed length in little endian order. Those both match with the data that results from decompressing the deflate stream. The bytes that precede the deflate data are _not_ a gzip header.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 7, "tags": "image processing, dicom, deflate" }
Can't call Python entry_points from command line I just installed a python tool for line profiling that should ship with itself a command line entry point named kernprof $pip install line_profiler a quick search returns: $find /opt/local/Library/Frameworks/Python.framework/ -name 'kernprof.py' opt/local/Library/Frameworks/Python.framework//Versions/2.7/lib/python2.7/site-packages/kernprof.py and the module is callable from the Python's interactive console, but $which kernprof does not return anything. I suppose that this behaviour could be related to the fact that I'm using `python-2.7` from Macports on OSX OS with wrong or incomplete path settings.
The problem is that with Macports's Python the scripts are installed in `/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/` that is not in the `PATH`. The lighter solution could be to symlink the script to `/usr/local/bin` sudo ln -s /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/kernprof /usr/local/bin
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, macos, macports" }
XFCE suspend system command When I click on the exit icon there is a suspend option. When I click this the computer suspends, which works really well. I want to create a custom key mapping on the suspend command `XK86Sleep` (ThinkPad sleep button) which I can create using the keyboard settings. I have seen `pm-suspend` from numerous sources, but this requires root and so does not work. What command does XFCE use when pressing the Suspend option through the UI as described above? XFCE 4.8, Ubuntu 12.04, ThinkPad T60
Try using this for the command xfce4-session-logout -s man xfce4-session-logout > The xfce4-session-logout command allows you to programmatically logout from your Xfce session. It requests the session manager to display the logout confirmation screen, or, if given one of the command-line options below, causes the session manager to take the requested action immediately. > > \--suspend Suspend without displaying the logout dialog
stackexchange-askubuntu
{ "answer_score": 9, "question_score": 4, "tags": "command line, suspend, xfce" }
gcloud SQL postgres - FATAL: remaining connection slots are reserved for non-replication superuser connections I am seing those errors in cloud sql Postgres logs. Its a small 1 cpu, 4Gb of ram instance yet this is a bit troublesome. I do not see any `max_connections` in the customizable flags that could allow me to bypass this error. The app is a simple Django service with very little queries and load not even exposed to the public. The immediate solution is for me to start using db connection pooling with pgbouncer or a Django app but that adds up a bit of complexity. max_connections ----------------- 100 Do we have a way to increase this number? PS: After digging a bit it seems to come from the use of gevent workers with gunicorn. It was stable < 20 connections before that. Nevertheless, in case of traffic surge it would be good to know if `max_connections` can be controlled.
Use `CONN_MAX_AGE: 0` when using gevent.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 8, "tags": "google cloud sql" }
What is the use case for the constructor constraint in Delphi? The title is pretty much it... Why would you ever want to use the `constructor` constraint? It's clearly implied by the `class` constraint. If you use it alone, you can't do anything with the thing you've created. Why does it even exist? **Additional info:** Just as a note, the following code doesn't compile until you add the "constructor" constraint: program Project3; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils; type TSomeClass<T: class> = class function GetType: T; end; { TSomeClass<T> } function TSomeClass<T>.GetType: T; begin Result := T.Create; end; begin try { TODO -oUser -cConsole Main : Insert code here } except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.
> Why would you ever want to use the constructor constraint? > > It's clearly implied by the class constraint. No it's not. The constructor constraint requires that the type has a public, parameterless constructor - and then allows that constructor to be called. Not all classes have a public parameterless constructor.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 4, "tags": "delphi, generics, parameterized types" }
Etiquette for using StackOverflow answers > **Possible Duplicate:** > Attribution etiquette in code -- do you cite helpful question URLS in code? If someone answers a question with some code, what's the etiquette for including it (and its technique) in closed source software? Do you add a comment with a link to the SO question or do you just take the advice and implement the code without any attribution? Boaz Yaniv really helped me out of a jam with this answer: Python: override __str__ in an exception instance ...and I want to make sure that my team doesn't think I'm the smart one based on Boaz's inspiration. Any advice?
It's partly etiquette, and partly good programming, but I'd definitely add the comment with a link to the SO question. Not only is it polite, but it will add context to the code on the off chance that your documentation doesn't answer all questions. See also this question which addresses the legality: Using code posted on StackOverflow
stackexchange-meta
{ "answer_score": 10, "question_score": 9, "tags": "discussion, etiquette" }
ContactsContract returning phone number with a space that can't be trimmed I've a weird problem here. When you use this: ContactsContract.CommonDataKinds.Phone.NUMBER It returns 0123 4567890 (or something like that). Now the SPACE in between these numbers is causing issues in a webservice so I was asked to trim it. I can't. I've tried the .trim() function but it doesn't seem to work. The only reason I can think of is that this isn't exactly a space. But how can I check? If I copy paste this from the logcat to a text file, it says its a SPACE (ASCII 32). But if it is, why isn't .trim() removing it?
trim() function doesn't work like that..it only removes spaces from the start and at the end..you can always replace them with empty string
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, trim, contactscontract" }
Generate a list of dictionaries representing all combinations of the values for each key Having the following dictionary: d = { 'a': [1, 2, 3], 'b': [True, False] } How can I generate a list of dictionaries representing all combinations of the values for each key? The output should be like this: combinations = [ {'a': 1, 'b': True}, {'a': 2, 'b': True}, {'a': 3, 'b': True}, {'a': 1, 'b': False}, {'a': 2, 'b': False}, {'a': 3, 'b': False} ] This should work with an arbitrary number of keys and an arbitrary length of values in the dictionary. We can assume that the values are always a list.
This can be solved using `itertools`: [dict(zip(d, values)) for values in itertools.product(*d.values())]
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "python" }
Netbeans 6.7 freezes on launch after crash. Any hints? My wonderful corporate Dell crashed when "hibernating", and now NetBeans freezes when launching. (It displays the full interface, and starts "Scanning Projects", but doesn't get past there and I can't click on anything.) I imagine there's some cache somewhere to clear out or something. Anyone know where?
I kinda had that type of problem before. What I end up doing to resolve that problem is to remove all the project entries that were loaded but not closed when I closed the problem. They are in: .netbeans/6.X/config/Preferences/org/netbeans/modules/projectui.properties In the entries: openProjectsDisplayNames.0=PROJECTNAME openProjectsURLs.0=file:/PATH/TO/PROJECT
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "netbeans, netbeans6.7" }
Comparing the DateTime Objects in Ruby on Rails I'm trying to compare the DateTime value accessed from the Active Record object with the current time. But not able to find any built in method to do this. I tried Using DateTime.now > @model_name.schedule_time But this is not giving expected result ( may be this does string comparison). Is there any accurate way to perform comparison with the current time.
Answering this question is a bit tricky without knowing the type of `@model_name.schedule_time`. However in rails `ActiveSupport` provides the methods `#past?` and `#future?` to `Date`, `DateTime` and `Time` instances, so that should take care of your problem: Date.yesterday.past? => true Time.now.end_of_day.future? => true DateTime.now.beginning_of_day.past? => true If `@model_name.schedule_time` does not respond to these methods, then it is not one of those types, which explains that the comparison you tried did not work.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby on rails, ruby" }
Why is this do while loop infinitely executing? Why is this do while loop infinitely executing? #include "stdafx.h" #include <iostream> using namespace std; int main() { unsigned int base; cout << "Base: "; cin >> base; for (int i = 1; i <= base; i++) { int j = 0; do { cout << "#"; j++; } while (j = i); cout << endl; }; system("pause"); // keep on building up until you reach 'base' return 0; } I am really confused about this. This program is supposed to create a triangle like this # ## ### (user inputs bottom number, so in this example the base = 3) Anybody help fix my rookie mistake?
You might wanna try `while (j == i);`. `j = i` is a variable declaration/assignment which will always be true as long as it succeeds. It seems like you want to compare the two, so use the _equal to operator:_ `==`. **Edit:** Made a typo and therefore the same mistake as your question shows. Fixed that.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++, loops, infinite loop, do while" }
get report of all open explorer windows I want to get a report of all open explorer windows titles and current paths. The current paths part of this is problem is answered here with C#, but I want this for powershell and am not sure how to adapt it. I am not sure how to bring out the window titles part of it. Could someone please assist.
Sounds to me like you're looking for something like this: $app = New-Object -COM 'Shell.Application' $app.Windows() | Select-Object LocationURL AFAICS the window objects don't have a title property, but you can get that information from `Get-Process` via the window handle ID: function Get-WindowTitle($handle) { Get-Process | Where-Object { $_.MainWindowHandle -eq $handle } | Select-Object -Expand MainWindowTitle } $app = New-Object -COM 'Shell.Application' $app.Windows() | Select-Object LocationURL, @{n='Title';e={Get-WindowTitle $_.HWND}}
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 8, "tags": "powershell, windows 8, windows 7, explorer" }
How to deal with mysql server downtime? Is there a way to make a file that is hosted on my site (for ex `site.com/db.sql`) that my website will pull from when my `mysql` server is down? I recently signed up for `Fatcow` to realize that their `MYSQL` server is down more than half the time, and I have a simple database that I need pulling from. I do plan on leaving Fatcow but I need a temporary solution until I can switch hosting.
Just use SQLLite until you leave FatCow. It's very easy and simple to setup. Here's a tutorial on how to read from and write to a SQLLite db file using PHP. <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, mysql, sql, database" }
What is the use of a tunnel interface on a cisco router? What is a tunnel interface used for on a cisco router? What is the difference between setting up a VPN connection and a tunnel interface; or does this serve the same purpose?
Tunnel interfaces have many uses, including participating in a larger VPN configuration. A VPN setup usually has many parts, including encryption, authentication, routing, and finally, the tunneling. Tunneling is also used for IPv4/IPv6 coexistence setups, such as encapsulating IPv6 packets in IPv4 packets payloads, creating GRE tunnels, and multicast tunneling. The point is that while tunnels may be part of a VPN setup, they do not necessarily represent the entire VPN configuration, but only the traffic encapsulation between endpoints.
stackexchange-networkengineering
{ "answer_score": 11, "question_score": 9, "tags": "cisco, vpn, router, tunnel" }
What is the story behind Monument Valley? Monument Valley is a minimalistic puzzle game featuring MC Escher - like structures. However, the story has a few fragments of a storyline, given to you by the Ghost, an adviser that you meet in some levels during your journey. The lines are short and few, but is there some kind of story behind this game that the Ghost and various structures throughout the game hint at? For example, > In _Labyrinth_ , drawings of Ida-like beings are seen worshipping the shape that eventually restores the _Observatory_ monument. _The Descent_ is also rich with clues, giving us > a resurrected Totem, drawings of Ida-like beings weeping, and a crow queen that is eventually revealed to be Ida. So is there any confirmed story concerning this game? Any stories at all?
The fragments of the story were written to help create an atmosphere for the game and are not narrative. In other words, there is no fully-worked out story that completely explains Ida, the crows, the monuments and the other aspects alluded to. Ken Wong, Lead developer at UsTWo games is reported as saying > Wong called the game's themes more impressionistic and symbolic than narrative. > > "The storytelling in the game is more akin to a song than a book or movie," Wong said. "The player can enjoy the game on whatever level they choose, and come away with their own meaning."
stackexchange-gaming
{ "answer_score": 10, "question_score": 15, "tags": "monument valley" }
What does f.input in a rails form do? I started to program with Rails after i finished some lessons in Ruby. When i looked at someone's code I got confused. It looked like he makes some form using Rails but I just can't understand how it works. Well just take a look on the code... Hopefully you can help me to understand this: =f.inputs do =f.input :type, :as => :transmission, :label => false =create_submit_link('Do something',:id=>'transmit') Now the f.input row will print me 3 rows of following stuff: (row 1): radio_button | labeltext | text_field; (row 2): 1x radio_button |labeltext| number_field; (row 3): radio_button |labeltext| How is that possible? :O
`f.inputs` is not defined in rails. You may be using "simple-form" gem. Simple Form has various views helpers to generates html contents. It has various method such as: `text`, `radio`, `email` however `:as => :transmission` options seems to be user defined as its not defined in "simple form" also. You can take look at < `f.input` work same as `f.textbox` or similar to rails but it has much more options than bare rails html helpers.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "ruby on rails, ruby, forms" }
Unable to compile python with pyglet in Ubuntu In Ubuntu 15.10,Running python3.4 sound.py leads to this error: Traceback (most recent call last): File "sound.py", line 2, in <module> import pyglet ImportError: No module named 'pyglet' I already installed pyglet with running this command: sudo easy_install -U pyglet resulting Searching for pyglet Reading Best match: pyglet 1.2.4 Processing pyglet-1.2.4-py2.7.egg pyglet 1.2.4 is already the active version in easy-install.pth Using /usr/local/lib/python2.7/dist-packages/pyglet-1.2.4-py2.7.egg Processing dependencies for pyglet Finished processing dependencies for pyglet I am confused about what is missing. I guess there are some confusion about different verions of python, pyglet or Ubuntu.
From the install output it seems that the installed version of pyglet goes to **python 2.7 packages**. From your command you are explicitly calling **python 3.4** There might be a problem there. python 3.4 will not go to 2.7's packages to check for the module. I suggest that you call the script using **python 2.7**. running just python is enough (the default env python) You can take a look at this question on the installation of python 2 and 3 packages too
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, ubuntu, pyglet" }
Displaying SVG as an ImageLayer - OpenLayers As flagged in the following GitHub issues, OpenLayers do not display SVG images properly when referenced in an ImageLayer: < There was a solution to this implemented a few months ago, using the "render" property in the Layer class: < But i cannot figure out how to implement this correctly. What is the frame state, and how can this be referenced correctly to the render property?
The devs behind OpenLayers have created an example to show how an SVG image can be rendered: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "svg, rendering, openlayers" }
Javascript: IIfe called before class constructor So I was just playing around with javascript, I have an iife defined withing a class which is being called before the class constructor. class SomeClass { constructor() { console.log('Constructor Called.'); }; someIife = (() => { console.log('iife called'); return () => { } })() }; const someClass = new SomeClass(); The output is - > iife called > > Constructor Called. Is this by design? I am not sure what is happening. Seems really interesting, could someone please explain why is this happening. Thanks.
The constructor function that's generated from your class declaration is effectively this: function SomeClass() { this.someIife = (() => { console.log('iife called'); return () => { } })(); console.log("constructor called"); } Instance variable declarations in the `class` body are transformed into `this.something` initializations in the constructor function body. Those initializations happen before the actual constructor body, so that the instance values can be used by the constructor code.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "javascript, iife" }
How come there are two accusative objects here "das geht dich einen Dreck an"? (so it seems) I failed with the object analysis of the following sentence: > Das Subjekt geht Verb dich Akk-Objekt(!?) einen Dreck Akk-Objekt(!?) an. I know there are instances, in which one finds, on top of the accusative object, some other noun in accusative, like in: > Diesen Monat werde ich den Arzt drei Mal besuchen. There, one has _Arzt_ and _Monat_ in accusative, but one is a time complement. In the first sentence one has an instance of other nature, I guess. If there are indeed two direct objects, why? If not, which is the right analysis?
Es handelt sich hierbei um das Objektsprädikativ, dessen Funktion es ist, das Akkusativobjekt genauer zu bestimmen. Es ist somit ein Prädikativum, genau wie das Prädikatsnomen, welches bekanntlich das Subjekt genauer bestimmt. Es ist folglich das Komplement zu einem sonst unvollständigen Satz. Vergleiche: * Vollständiger Satz, braucht keint Komplement > Ich lese. > Er schimpft. * Unvollständiger Satz, braucht ein Komplement > *Ich bin. > *Er schimpft ihn. * Mit Subjektsprädikativ (Prädikatsnomen) bzw. Objektsprädikativ > Ich bin Em1. > Er schimpft ihn einen Esel.
stackexchange-german
{ "answer_score": 4, "question_score": 9, "tags": "accusative" }
FileMode is not a member of IO I for the first time is trying a code in VB.This code is handed over to me from my old team who codes in VB.While seeing the code i am getting an error as `FileMode is not a member of io`.Rest of the codes are fine . Here is the line of code in which i am getting error.. stamper = New iTextSharp.text.pdf.PdfStamper(pReader, New System.IO.FileStream(DestinationFile, IO.FileMode.Create)) And i have imported `Imports System.IO` in start of the program also. Please help me.
If you imported `System.IO` all you need is: stamper = New iTextSharp.text.pdf.PdfStamper(pReader, New FileStream(DestinationFile, FileMode.Create))
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "vb.net" }
How to set specific Hadoop version for Spark, Python I need help with setting a specific hadoop version in my spark config. I read somewhere that you can use the hadoop.version property. It doesn't say where to find it. < I need to set it from current/default to 2.8.0. Im coding in PyCharm. Please help, preferebly with a step-by-step guide. Thanks!
You can build like that, for Apache Hadoop 2.7.X **and later** , so the above answer is correct. [ ./build/mvn -Pyarn -Phadoop-2.7 -Dhadoop.version=2.7.0 -DskipTests clean package ] Or you could modify this in the pom.xml of your spark downloaded distribution before performing the maven build, so that the building gets done with the version you want. <profile> <id>hadoop2.8</id> <properties> <hadoop.version>2.8</hadoop.version> ... </properties> </profile> Take a look at this post for a step-by-step guidance.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, hadoop, apache spark, pyspark, pycharm" }
How to draw a view over a GLkit view on iOS5/Ipad I´m creating a GLK view on iOS5. First, i create the context. GLKView *view = (GLKView *)self.view; view.context = self.context; view.drawableDepthFormat = GLKViewDrawableDepthFormat24; [self setupGL]; Second, i draw a triangle moving. This works. Now, i want to create a view over the GLKview. So, i used the Storyboard, to draw a View (HUDView) with background red, and i put it over the main view. When i run the app, only openGL appear, i assume that red background view is drawing behind GLKView. Why? I have tried to use on Hudview -> viewDidLoad [self bringSubviewToFront:self]; But the problem nothing happen. Any idea how could i solve this problem???? Thanks in advance.
I have found a sample that solve the problem. Glfun is a sample where a openGL layer is drawn, and you can add a hud view over it. Hopes help people :D
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ios5, opengl es, uistoryboard" }
Connect neighbor vertices into a polygons? Geometry nodes 3.x Is there a way to connect vertices (separate points) into a mesh grid inside the geometry nodes? What I basically need is to get this: ![enter image description here]( from this: ![enter image description here](
Maybe this example will help you _(Blender 3.1.2)_ : ![Connect neighbor vertices into a polygons - Screen 1]( ![Connect neighbor vertices into a polygons - Screen 2]( * Here I simply instantiate mesh lines at the points, extrude them minimally in height so that I get edges from them. * I merge these with the node `Mesh Boolean` with the underlying grid (you can also do this with a convex hull). * The resulting mesh is then simply triangulated and the outer hull is removed again. * To make the positions exactly match the points, I get them directly back from the points and merge identical vertices. * In the last step I extrude the mesh again, and separate the edges. You can omit this step if you don't need the edges individually. ![](
stackexchange-blender
{ "answer_score": 2, "question_score": 2, "tags": "geometry nodes" }
OpenVPN UDP and TCP Traffic Fowarding It's been a while since I've used OpenVPN, but using the TUN configuration, how would one go about sending all TCP and UDP traffic over the VPN? Would I need two VPN Clients and Servers running? Here's my current client config: client dev tun proto tcp remote myvpnhost.com 8080 resolv-retry infinite nobind persist-key persist-tun ca "C:\\Program Files (x86)\\OpenVPN\\easy-rsa\\ca.crt" cert "C:\\Program Files (x86)\\OpenVPN\\easy-rsa\\laptop.crt" key "C:\\Program Files (x86)\\OpenVPN\\easy-rsa\\laptop.key" ns-cert-type server comp-lzo verb 3 #explicit-exit-notify 2 #ping 10 #ping-restart 60 route-method exe route-delay 2 #last updated June 04, 2011
This line: `proto tcp` means that your client will communicate with your OpenVPN server through TCP. Your traffic (UDP & TCP) is already going through your OpenVPN TCP-based tunnel.
stackexchange-serverfault
{ "answer_score": 2, "question_score": 2, "tags": "openvpn" }
Cannot send data over UDP in UWP I am trying to send the data over UDP in UWP Application. However, I cannot see the data being sent on Wireshark. Just to check if firewall is causing any issue, I disabled it and tried sending the data again. However, I still don't see the data on Wireshark. Here's my code: UdpClient client = new UdpClient(); client.EnableBroadcast = true; client.Connect(IPAddress.Broadcast, 9520); Byte[] senddata = Encoding.ASCII.GetBytes("Hello!"); client.Send(senddata, senddata.Length); client.Close(); Am I missing something obvious here? I am using Visual Studio 2017 to build this UWP Application.
This page explains why the above code will not work if the App capabilities were not configured. I didn't configure the capabilities before asking this question. However, I came across the page and enabled some capabilities (Internet(Client & Server), Internet(Client), Private Networks(Client & Server)). After configuring them, my earlier code is working fine. If you're facing the same problem, please configure the capabilities by going to Package.appxmanifest -> Capabilities and then rebuild the solution. After correctly enabling the capabilities, your app shall send the data. :) :)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, uwp, udp" }
jQuery can't get top parent? I have a simple html code like this: <section class="main"> <div class="container"> <div class="row"> <header class="verticalCenter"> ... </header> </div> </div> </section> Plus, I have this jQuery: function verticalCenter(el) { el.each(function() { var elHeight = $(this).outerHeight(true), parentHeight = $(this).parent('section').outerHeight(true), marginTop = (parentHeight - elHeight)/2; $(this).css('margin-top',marginTop); }) } verticalCenter($('.verticalCenter')) Problem is - jQuery doesn't see `section.main`. What did I do wrong?
You want `.closest()`, not `.parent()` parentHeight = $(this).closest('section').outerHeight(true), The `.parent()` function checks _only_ the immediate parent. Passing it a selector effectively means, "get me the parent, but only if the parent matches this selector; otherwise, give me an empty list."
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, jquery" }
Python- re.search() // Match start and end but do not include either in match result My intention is to get all inbetween 'start' and 'end' variables. Currently struggling to understand how to apply the filters to get group excluding the start and end criteria. start = 'melons' end = 'strawberry' s = 'banana apples melons+cucumber+strawberry grapes' r = re.search('', s) print(r.group(1)) #print = +cucumber+
Can be achieved with below approach: import re start = 'melons' end = 'strawberry' s = 'banana apples melons+cucumber+strawberry grapes' r = re.search(rf'{start}(.*?){end}', s) print(r.group(1)) Output: +cucumber+
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, python 3.x, python re" }
Clarification of proof on the completion of a metric space using Cauchy sequences This is in reference to the proof of the completion theorem of metric spaces. (To protect against link rot, here is a copy of the document being referenced: page 1, page 2, page 3) A proof is given at the bottom of page 2 to "every Cauchy sequence in $\psi[X]$ converges to a point in $X^*$. I don't understand what $\lceil\\{z_1,z_2,z_3,\dots\\}\rceil$ means. Is it the $\sup$? How is the $\sup$ of a Cauchy sequence of Cauchy sequences defined, especially when there is no ordering in the space?
It is the equivalence class of the Cauchy sequence $(z_1,z_2,\ldots)$ in $X^*$. Look at the very beginning of the proof, where this notation is introduced... > !enter image description here Closeup of the notation you're asking about: > !enter image description here
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "sequences and series, metric spaces" }
undefined property on iterator_to_array (date object) With this snippet: $dt = new DateTime(); $periods = new DatePeriod($dt, new DateInterval('P1D'), 6); $days = iterator_to_array($periods); foreach($days as $day){ echo 'current date: '.$day->date.'<br />'; } I see this error: > Notice: Undefined property: DateTime::$date Anyway, If I add a "print_r" before echo: $dt = new DateTime(); $periods = new DatePeriod($dt, new DateInterval('P1D'), 6); $days = iterator_to_array($periods); foreach($days as $day){ print_r($day); echo 'current date: '.$day->date.'<br />'; } I see on my page both the print_r result and the result of echo. Why?
I'm not sure, it might be a bug. But you'll need to use your `$day` object like this only: foreach($days as $day){ echo $day->format('Y-m-d')."\n"; } I'm guessing printing the `$day` object initializes it somehow, and you're able to use its member variables then. PS. you don't really need to iterator_to_array to iterate through the `DatePeriod` object. You can simply do something like `foreach ($periods as $day)`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, date, iterator" }
User unable to search contents in site even though he is site owner I create a new site collection called site1 through user1 who is also farm admin. When I search something in site1, it brings all results i.e. not only from this site but other site collections also (because I am using custom search scope "All Sites") I created another AD user called user2 I gave READ permissions to user2 in site1 by adding it into VISITORS group. Then I logged into site1 as user2 and searched something but it is only showing results from other site collections and not this current site1. I then added user2 in site1 SITE OWNER group but still same problem. It is not showing results from current site collection. Why is that? That user2 is the owner of site1 but still no results!? While in case of user1 it works who is also farm admin.
Ok I fixed it. I did a full crawl again and now user2 can also search.
stackexchange-sharepoint
{ "answer_score": 0, "question_score": 0, "tags": "sharepoint enterprise, search, search results" }
Solve for subset of group knowing only whole group First time on this exchange, apologies if I don't select the right tags. It seems like this should be really easy, but it's been a long time since I've been out of high school math and there's no excel formula I can find for this... I have the following set of data: users: 20,000 process time average: 500 seconds The users are made up of new, and existing staff and I know that 30% of the users are new. New staff take, on average, 100 seconds longer to process the task than existing staff. knowing the total users, and total process time, I need to solve for the process time for existing users. Can you help? or point me in the right direction? I can't even come up with a coherent google search for this. Done some google searching, but haven't been able to come up with a way to frame the question. I expect to have a process time for new users that's lower than the overall process time.
It's not entirely clear what you are asking, but let's try this: You have $.3\times 20000=6000$ new users, and therefore $14000$ seasoned users. Let's say the seasoned users require $N$ seconds to process the task. Then the new users require $N+100$ seconds to process the task. It follows that the average processing time is $$500=\frac {6000\times (N+100)+14000\times N}{20000}$$ Which we solve to get $N=470$. I am puzzled by your comment that "I expect to have a process time for new users that's lower than the overall process time." Surely you expect new users to take longer than the average time. My computation shows that new users need $470+100=570$ seconds, which indeed is longer than the average.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "algebra precalculus, word problem" }
Is there a way that i can pass a string uninterpreted in a url? I have a zabbix server that sends me a mail whenever there is an issue. It uses a template like this, to generate the mail Issue: {TRIGGER.ISSUE} Description: "Node: {TRIGGER.NODE}, {TRIGGER.DESCRIPTION}" And the mail would look like: Issue: "memory usage" Description: "Node: abc.def.com, high memory usage (>90%)" I need to pass this information on to a web server after which appropriate action will be taken. The way I thought is by putting the url inside that template something like this But this sometimes generates a string that will not be properly encoded into a URI and I often run into Bad URI issues on my browser. Is there a way that I can pass on the strings such that it goes through as a raw string and does not get interpreted by the browser?
Some characters (white space, &, ...) in `{TRIGGER.DESCRIPTION}` or `{TRIGGER.NODE}` macros are your problem. Unfortunately, Zabbix doesn't provide any _urlencode_ function in the template. Fortunately, you can write your own alertscript which will solve your problem. Just pick up your favorite language, which support _urlencode_ function (or write your own) and use _urlencode_ function for any macro, which you use in the URL. Your script must be able to send also email. Doc: * < * <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "url, browser, webserver, zabbix" }
Jmeter two response code assertion I already made Response Code 422 as a success http request in jmeter with Response Assertion, and it works. But jmeter assign Response Code 200 as a failed http request. I add 422 and 200 in Pattern to test but jmeter only assert Response Code 200 as a success http request. How assign Response Code 200 OR 422 as a success http request? regards, Stefio
`200|422` The pipe character `|` is the OR operator In general, you can use perl5 regular expressions in JMeter
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "jmeter, http response codes" }
How can I improve this nested loop? I am trying to do a fuzzy match of records in two Account table using .NET Entity Framework. I wrote some code like this but it has bad performance like 1 min a record. ARSalesforceEntities arsf = new ARSalesforceEntities(); //dbcontext Salesforce_FFEntities ffsf = new Salesforce_FFEntities(); //dbcontext var araccounts = arsf.Accounts; //dbset contains 400000 records var ffaccounts = ffsf.Accounts; //dbset contains 6000 records IDCONV byName = new IDCONV(); IDCONV byAddress = new IDCONV(); foreach (var ffaccount in ffaccounts) { Console.WriteLine(++count); foreach (var araccount in araccounts)//this line goes every slow like 1 min { Basically, I am comparing the records in two tables with complicated logic. How can I greatly improve the performance of the code? Thank you
This line: var ffaccounts = ffsf.Accounts; is what's hitting you hard. You're basically assigning the `IQueryable` to a variable which, when accessed in your inner loop, re-queries the database everytime. I imagine simply adding `ToList()` on the end will drastically improve your performance: var ffaccounts = ffsf.Accounts.ToList(); That's assuming of course that it's acceptable to materialise the 6000 rows into memory. If not, then you might want to consider writing the logic in SQL and doing all the work in the DB instead...
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": -1, "tags": "c#, .net, linq, entity framework" }
How do I remove an element from an array and insert into another position in PHP? For example suppose I have $input = array(0, 1, 2, 3, 4, 5, 6, 7); How would I remove element 5 and insert at position 2 leaving me with 0, 1, 5, 2, 3, 4, 6, 7
$input = array(0, 1, 2, 3, 4, 5, 6, 7); array_splice($input, 2, 0, array($input[5])); //Place the a new array in the 3rd place of array unset($input[6]); //remove the fifth element array_splice($input, 0, 0); //to update the indexes echo "<pre>".print_r($input,1)."</pre>"; //to view the array Method without the need to unset and rearrange the index $input = array(0, 1, 2, 3, 4, 5, 6, 7); array_splice($input, 2, 0, array_splice($input,5,1)); **Output** Array ( [0] => 0 [1] => 1 [2] => 5 [3] => 2 [4] => 4 [5] => 5 [6] => 6 [7] => 7 )
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "php, arrays" }
Trouble looping a multidimensional array in PHP I have the following array. It contains nicknames and names: $nickAndNames = array( array( "Johnie", "John Larson" ), array ("Maggie", "Margaret London" ), array("Nic","Nicholas Carradine") ); Can you please help me to print just the first elements? I mean Johnie, Maggie, Nic.
Each element of the array is another array. Each element of this inner array in turn contains 2 elements: element 0 (a string, the nickname) and element 1 (another string, the name). Therefore, you'd first need to loop through the `$nicksAndNames` array, and then display the inner array's first element (which is element 0): // loop through $nickAndNames and assign, in turn, each inner array // to a variable named $nickAndName foreach ($nickAndNames as $nickAndName) { // this $nickAndName variable now contains the inner array, something like: // array("Johnie", "John Larson"), so "Johnie" is the first element, // element 0 echo $nickAndName[0]; }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "php, arrays, multidimensional array" }
Google maps wont to show height 100% I use twitter bootstrap 3 and google maps but this code wont to show map height in %. When I use PX everything is ok. <body onload="findMyCurrentLocation()"> <div class="col-xs-3 col-md-3 col-lg-3"></div> <div class="col-xs-9 col-md-9 col-lg-9"> <div id="map_canvas"></div> </div> and css: #map_canvas { height:100%; }
<body> <div class="container"> <div class="col-xs-9 col-md-9 col-lg-9"> <div id="map_canvas"></div> </div> </div> </body> The problem comes from the fact that you didn't add a container.
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": -1, "tags": "html, css, twitter bootstrap, google maps" }
newDateTime and new DateTime difference, if any In India, the common date format is `dd/MM/yyyy`. So I input into the `TextBox` in Indian format and with the code posted in one of Stack Overflow sites, I am converting `textBox1.Text` to the format of `yyyy/MM/dd` format to further management of the string to find difference between two dates. Though this code taken from Stack Overflow works fine with my needs, I am at a loss to understand the difference between `new DateTime` and `newDateTime`. Would anyone of you please explain? I appreciate the help. DateTime d1; if (DateTime.TryParse(textBox1.Text, out d1)) { string newDateTime = d1.ToString("yyyy/MM/dd hh:mmtt"); MessageBox.Show(newDateTime.ToString()); }
The `DateTime`.aspx) is a constructor that (in this case) attempts to create a specified date format from a string. In it's simplest structure, it is declared like this: DateTime d1 = new DateTime (int, int, int); You then have a `string` which is a variable, with the name `newDateTime`. This is simply a string, which holds a collection of characters. You can _format_ a string, as you have done in your example, which would rely on the data being passed in to have some form of structure. However, once the information has been passed in, it is just a string.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "c#, datetime" }
Summing array on Javascript Hi I am trying to sum an array on Javascript with the following codes. var data[]: var total=0; data.push[x]; // x is numbers which are produced dynamically. for(var i=0, n=data.length; i < n; i++) { total=total+data[i]; } alert(total) for example if x values are are respectively 5,11,16,7. It shows the total value as 511167 not sum the values 5+11+16+7=39 Do you have any idea why it results like that? Thanks.
Use `parseInt()` function javascript total=parseInt(total)+parseInt(data[i]);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, html, arrays" }
Can we install safari and edge webDriver on the docker? I could install chrome and firefox webDriver on Docker, but I don't know if it is possible to do the same with safari and edge too. So any one has an idea? if yes how to do?
Docker containerisation is limited to Linux OS containers only. This means no OS X nor Windows. So you can't run Safari nor Edge. But you can add a vagrant vm browser (running Windows or OS X), and then connect them to your Selenium hub.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "selenium, docker, webdriver" }
Enabling "Hardened Runtime" from outside of XCode This question is prompted by the new Notarization requirements that Apple will enforce for Mac Apps distributed outside of the Mac App Store targeting Mojave (in the near future.) I maintain a suite of self-hosted, Developer ID Application certificate-signed apps, using a custom runtime (Excelsior JET for Mac Java JIT Compiler / Runtime); custom bash scripts (are used as part of the apps in the installation process) and automate the builds. Therefore, there are no XCod` projects per-se involved in this process. After consulting the developer docs, I wasn't able to find a way to activate and customize this "hardened mode" (described here) by using any kind utilities from XCode, but from the CLI (instead of the IDE GUI). Is there any way to accomplish this?
I have several executables in my app. Hardening takes place when all of them are signed with the `--options runtime`. In the end, of course, I sign the app bundle itself the same way (see the links I provided in my last comment above).
stackexchange-apple
{ "answer_score": 1, "question_score": 5, "tags": "mojave, java, notarization" }
Doesn't boot after fresh install After fresh install of oneiric 11.10 nothing displayed during boot process, but I still can switch to tty's. I made apt-get update/upgrade from tty and tried to reboot. Nothing changed. 'service lightdm restart' and 'startx' also doesn't help. **UPD(24.10.2011):** Just reported bug with apport-bug to launchpad. You can see there logs and others collected reports.
Try `sudo apt-get purge nvidia` replace nvidia by the driver you are using. It will use the free driver Nouveau. That worked for me.
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 3, "tags": "11.10, boot, xorg, startup" }
Class not found when mysqlconnector is put as classpath Here's my problem, I'm trying to connect a Java program to MySQL database. I'm using no IDE here. What happen is when i add the `mysql-connector-java-bin.jar` as CLASSPATH it produce error, but without CLASSPATH, my program runs but is not connected to the database because of the missing `com.mysql.jdbc.driver`. Any fix here? Thank you! Also even the basic HELLO WORLD program doesnt work when mysql connector is classpathed. Here is the screenshot when I execute the program for clarifications. !enter image description here
Your problem is because you didn't put a ';' after then name of your connector jar file, Because the -classpath parameter value should be in ';' seperated format. The correct way is to use it in this way: java -cp mysql-connector-java-5.1.23-bin.jar; Dbcon Another problem you may encounter is when your class placed in a package. When using `java` command you must in the root of [bin] directory (root directory where your compiled classes exists) and make sure you are using the fully qualified name (full package name + class name) of your main class. Good Luck.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, mysql" }
How to Write in csv or Excel file using CSV module or Pandas by combining two lists into one In Python? I've got two lists. list1 = ['abc', 'bcd', 'efg', 'ijk', 'lpo'] list2 = [111, 222, 333] **Sometimes list1 is more values than list2, and other times list2 is more values than list1.** How am I able to write on a CSV File Like This. abc 111 bcd 222 efg 333 ijk lpo ![enter image description here](
You can try with `itertools` `zip_longest` then `to_csv` import itertools pd.DataFrame(itertools.zip_longest(list1,list2)).to_csv('Your.csv',header=None, index=None)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "python, excel, pandas, list, csv" }
how to set a view's background color using a precise hex via interfacebuilder? In IB, when I go to the attributes inspector and click the "background" drop down -> other, I get a color pallet with several tabs (wheel, slider, apllets) but there is no place to set a precise such as #ff5911 for example. Is there a way to do that without using code?
Add a hex color picker to your system. I use <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 6, "tags": "ios, interface builder" }
Exibir uma sequência de divs em duas linhas Boa noite, tenho a seguinte estrutura de divs: 1 | 2 | 3 | 4 | 5 | 6 O que eu preciso fazer é que essa estrutura fique da seguinte forma: 1 | 3 | 5 2 | 4 | 6 Um único detalhe, é que preciso fazer isso somente usando CSS, sem adicionar mais nenhuma div na estrutura. Meu código segue aqui: <
Uma solução é fixar o CSS assim: .teste{ width:100px; height:100px; background-color:red; float:left; margin-left:10px; position: absolute; } .teste:nth-child(even){ margin-top: 120px; } .teste:nth-child(4), .teste:nth-child(3){ left: 120px; } .teste:nth-child(6), .teste:nth-child(5){ left: 230px; } Repara que mudei os teus ID's duplicados para classes. Juntei `position: absolute` à classe, e depois dei regras mais ou menos a cada elemento. ### Exemplo: <
stackexchange-pt_stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "html, css" }
Do I still need to pay capital gains taxes when I profit from a stock in a foreign currency? Let's say I convert CAD 100 to USD 90. With the USD 90, I buy a stock that goes to USD 100, and then I sell it. If I don't convert the resulting USD 100 back to (say) the CAD 105 it might be worth at the time, do I still need to pay tax on my profit?
**Yes,** you still need to pay income tax on your capital gain regardless of whether you converted your USD proceeds back into CAD. When you calculate your gains for tax purposes, you'll need to convert all of your gains to Canadian dollars. Generally speaking, CRA will expect you to use a historical USD to CAD exchange rate published by the Bank of Canada. At that page, notice the remark at right: > **Are the Exchange Rates Shown Here Accepted by _Canada Revenue Agency?_** > > Yes. The Agency accepts Bank of Canada exchange rates as the basis for calculations involving income and expenses that are denominated in foreign currencies.
stackexchange-money
{ "answer_score": 5, "question_score": 1, "tags": "stocks, income tax, canada, foreign exchange, capital gain" }
Запретить чужому сайту вставлять картинки с моего сайта Добрый день! Встал вопрос, как запретить чужому сайту использовать графику <img src="Мой сайт" /> с моего сайта. Чужим сайтом, в данном случае будет любой сайт, в чьём названии нет слова _test_. test.ru - Можно ad.test.ru - Можно test.adawd.dwad.ru - Можно и т.п... Помогите пожалуйста, искал в интернете, но решение не подходит, так как в данном случае нужно отклонять сайты, где нет слова _test_.
RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^.*test.* [NC] RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L] Как-то так наверно.
stackexchange-ru_stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": ".htaccess, php" }
jquery get only all html elements with ids I have a div with many many html elements like other divs, trs, tds, tables etc Is it possible to get all the elements which have an id? I know asking `$("#test")` will give me the specific element with this id but is it possible to get `find("#")` or something like this?!
`$('[id]')` returns all elements that have id set
stackexchange-stackoverflow
{ "answer_score": 54, "question_score": 18, "tags": "jquery, validation" }
Checking if package is older than 24 hours with bash I would like to check if my last file is older than 24 hours or not. (project in django) I have many zip packages in directory so I have to 'filter' the last one with this part of code: `ls -1 | sort -n | tail -n1`. My code in .sh file: #!/bin/bash file="$HOME/path_directory ls -1 | sort -n | tail -n1" current=`date +%s`; last_modified=`stat -c "%Y" $file`; if [ $(($current-$last_modified)) -gt 86400 ]; then echo "File is older that 24 hours" | mailx noreply@address -s "Older than 24 hours" [email protected] else echo "File is up to date."; fi; Here is an error, that I got: stat: invalid option -- '1' Try 'stat --help' for more information. /path_directory/imported_file.sh: line 9: 1538734802-: syntax error: operand expected (error token is "-") If somebody made something similar, please some hint.
I'd advise you to try this: if test "`find file -mtime +1`" but if you insist you can fix it by changing it to this: #!/bin/bash file="$HOME/path_directory ls -1 | sort -n | tail -n1" current=$(date +%s); last_modified=$(stat -c "%Y" $file); if [ $((current - last_modified)) -gt 86400 ]; then echo "File is older that 24 hours" | mailx noreply@address -s "Older than 24 hours" [email protected] else echo "File is up to date."; fi;
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "bash, shell" }
Removing text inside parens, but not the parens in Perl OK, I got a weird one that I've been jamming on for awhile (fri afternoon mind does not work I guess). Does anyone know of a away to parse a string and remove all of the text inside parens without removing the parens themselves...but with deleting parens found inside. ie. myString = "this is my string (though (I) need (help) fixing it)" after running it through what I want it would look like: myString = "this is my string ()" very important to keep those two parens there.
If you want to use Regular Expressions without using Regexp::Common. Look at the "Look Around" Feature. It was introduced with Perl 5. You can read more about "Look Ahead" and "Look Behind" at regular-expressions.info. There is also a section on "Look Around" in the "Mastering Regular Expressions" book. Look on page 59. #!/usr/bin/env perl use Modern::Perl; my $string = 'this is my (string (that)) I (need help fixing)'; $string =~ s/(?<=\()[^)]+[^(]+(?=\))//g; say $string;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 6, "tags": "perl, string" }