qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
12,378,154
Are there any aspects to the C++ programming language where the code is known to be slower than the equivalent C language? Obviously this would be excluding the OO features like virtual functions and vtable features etc. I am wondering whether, when you are programming in a latency-critical area (and you aren't worried about OO features) whether you could stick with basic C++ or would C be better?
2012/09/11
[ "https://Stackoverflow.com/questions/12378154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/997112/" ]
Nothing in the C or C++ language standards specifies the speed of any construct (C++ does specify the time complexity of some operations applied to containers, but that's outside the scope of your question). The speed of the code generated for a given construct depends on the compiler used to compile it, and on the system it runs on. For a given code construct that's valid C and valid C++ with the same semantics, there's no *fundamental* reason why either should be faster than the other. But it's likely that one will be faster than the other if the developers of the compiler were a little more clever.
714,344
Yesterday, I noticed that <https://hkps.pool.sks-keyservers.net/> showed a different page on my laptop than it did on my desktop PC. This URL redirects to one of the many servers listed here: <https://sks-keyservers.net/status/> Unlike a normal URL redirection, the URL does not change, while the contents of the page do. How exactly does this work? How can it be set up? Does it have anything to do with a [round-robin DNS system](https://en.wikipedia.org/wiki/Round_robin_dns)? It also seems that it always shows the same "server" on a given PC once it has been accessed once from there. How does it do that? <http://www.pool.ntp.org/en/> appears to be a similar system.
2014/02/09
[ "https://superuser.com/questions/714344", "https://superuser.com", "https://superuser.com/users/41232/" ]
Yes, all the pools of sks-keyservers.net are set up using a DNS round-robin. In terms of reverse proxies, it require all servers to have one enabled, and if you look at the rprox column at <https://sks-keyservers.net/status/> some blue flags are specifying servers with multiple servers in the backend in a clustered setup. The actual data for the round-robin is based on (i) hourly update run of the full pool (ii) authorative DNS server update the list of DNS records every 15 minutes. For the non-geographical pools a random selection is used in (ii), for the geographical pools (EU, NA, ... ) it is ranked by SRV record based on the description in <http://kfwebs.com/sks-keyservers-SRV.pdf>
3,632,331
I am working through "Thinking Mathematically" by Mason, Burton and Stacey. One of the questions goes as follows: *Three slices of bread are to be toasted under a grill. The grill can hold two slices at once but only one side is toasted at a time. It takes 30 seconds to toast one side of a piece of bread, 5 seconds to put a piece in or take a piece out and 3 seconds to turn a piece over. What is the shortest time in which the three slices can be toasted?* I am wondering if I am overlooking something in my solution method, so I have come here. Some sources online say 130 seconds and others say 139. My solution, if non-fallacious, should be able to get it done in 118 seconds. The process goes as follows. Allow $T\_n$ to represent the first side of the $n$th piece of toast and $T\_n'$ to represent the opposite side of the $n$th piece of toast. Then, assuming a piece of toast is cooking as soon as it is placed, then the suggested sequence of events [![enter image description here](https://i.stack.imgur.com/CL5aO.jpg)](https://i.stack.imgur.com/CL5aO.jpg) Sorry for the convoluted timeline in the picture, but essentially I place the first piece of toast and then the second. $T\_1$ and $T\_2$'s cooking time will overlap, but there is necessarily a five-second window where they do not. You flip $T\_1 \to T\_1'$ where $T\_1'$ officially begins toasting at 38 seconds. This gives another thirty-second window (until $t = 68$) to get a lot of the time-wasting flipping and removing done. For example, $T\_2$ finished at $t=40$ and the most original part of this solution is to **remove** $T\_2$ rather than flip it over and begin cooking the other side immediately. As soon as we are done removing $T\_2$ the running total will be $t=45$ at which point we immediately begin placing $T\_3$ bringing us to a running total of $t=50$. Note, that $T\_3$ will be done at $t = 80$. At this point, we wait until $t=68$ to remove $T\_1'$ which brings us to a running total of $t = 73$, at which point we immediately begin placing $T\_2'$ which we put aside before. When we are done placing $T\_2'$ we will be at $t = 78$ and at $t = 80$ it will be time to flip $T\_3$, which brings us to $t = 83$ and which point $T\_3'$ will begin toasting. $T\_3'$ will thus be done at $t = 113$ and in that time we will have to remove $T\_2'$ which began cooking at $t = 78$. Finally, we remove $T\_3'$ at $t = 113$ and ending at $t = 118$. Are there any problems with this solution that I am not detecting? I think it works well, indeed if it works at all, because it uses the long 30-second windows of cooking to do all the time-consuming activities of flipping etc.
2020/04/18
[ "https://math.stackexchange.com/questions/3632331", "https://math.stackexchange.com", "https://math.stackexchange.com/users/698855/" ]
Assuming that (a) flipping a slice does not require removing and replacing it (so that flipping is a total of 3 seconds and not 13 seconds) and (b) messing with one slice does not interrupt the cooking of the other slice, I see no flaw in your solution.
325,075
I am using a RichTextBox in WPF, and am trying to set the default paragraph spacing to 0 (so that there is no paragraph spacing). While I could do this in XAML, I would like to achieve it programmatically if possible. Any ideas?
2008/11/28
[ "https://Stackoverflow.com/questions/325075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/691/" ]
I did it **with style** (pun indented) ``` <RichTextBox Margin="0,51,0,0" Name="mainTextBox" > <RichTextBox.Resources> <Style TargetType="{x:Type Paragraph}"> <Setter Property="Margin" Value="0"/> </Style> </RichTextBox.Resources> </RichTextBox> ```
5,195
I have just purchased a new CF card for my DSLR. I tested it using Xbench (Mac OS X) and it performs as expected. However, I'd like to do a "surface scan" (moving platter term) to check for "bad sectors" (moving platter term). I could bash script a processes using dd, but I get the feeling that there is a better way out there. My goal is to conclusively know that a memory card (CF, SD, etc.) is safe to use on a photo shoot, and that is doesn't need to be returned before the 30 day vendor policy window expires. I definitely want Mac solutions given here. I would also like to get a few Linux suggestions. Let's even throw a bone to the windows users just so that this one question can meet everyone's needs.
2010/11/27
[ "https://photo.stackexchange.com/questions/5195", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/2363/" ]
As the controller can move the blocks wherever it wants (see wear leveling), the only chance for a whole read/write-test ist to fill the disk up and then compare. Several times with different patterns of course to be sure. And still you won't catch faulty regions, as they are hidden too by the controller as long as he has spares.
7,802,159
I have the same exact problem that's in this [question](https://stackoverflow.com/questions/5070237/problemas-com-parse-xml-iphone), but it didn't get any good answers. I'm trying to parse an XML file with an `ISO-8859-1` encoding, but everytime there's an accentuated word, it gets truncated and doesn't show properly. ``` Example: Original Word: Interés Word Shown: és ```
2011/10/18
[ "https://Stackoverflow.com/questions/7802159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000331/" ]
* Using MySQL replication. * using active-pasive with [rdbd](http://www.drbd.org/) + [heartbeat](http://linux-ha.org/wiki/Heartbeat) In any case you would need use DNS to automatically update the IP or VIP
6,258,361
I've googled about this all over the Internet and still haven't found a solution. As an ultimate try, I hope someone can give me an exact answer. I get that error when I try to copy a file from a directory to another in an File Explorer I'm trying to do on my own. It has a treeview control to browse for directories and a listview control to display the contents of the directory. This is how the code would look like, partially: ``` private void copyToolStripMenuItem_Click(object sender, EventArgs e) { sourceDir = treeView1.SelectedNode.FullPath; for (int i = 0; i < listView1.SelectedItems.Count; ++i) { ListViewItem l = listView1.SelectedItems[i]; toBeCopied[i] = l.Text; // string[] toBeCopied, the place where I save the file names I want to save } } private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { targetDir = treeView1.SelectedNode.FullPath; try { for (int i = 0; i < toBeCopied.Length; ++i) { File.Copy(sourceDir + "\\" + toBeCopied[i], targetDir + "\\" + toBeCopied[i], true); refreshToolStripMenuItem_Click(sender, e); } } catch (Exception ex) { MessageBox.Show(ex.Message + Environment.NewLine + ex.TargetSite); } } ``` The place where I got the error is at `File.Copy(sourceDir + "\\" + toBeCopied[i] ...`. I've read that it could be something that has to do with the mapping of devices, but I don't really know what that is.
2011/06/06
[ "https://Stackoverflow.com/questions/6258361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/786559/" ]
Can you take a look at the [Path.Combine](http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx) method on MSDN? This will help make sure all your entire path doesn't have extra \'s where they shouldn't be. i.e. `Path.Combine(sourceDir, toBeCopied[i])` If you are still getting an error, let me know what the value if the above.
64,026,699
I have one program sending data with 10Hz frequency. ``` import socket import time if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('127.0.0.1', 19080)) while True: data = time.time() sock.sendto(str(data).encode(), ('127.0.0.1', 9090)) time.sleep(0.1) ``` And second program recieving data, with delay (1Hz): ``` import socket import time if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('127.0.0.1', 9090)) while True: data = time.time() print(time.time(), sock.recv(100)) time.sleep(1) ``` After a while, output is: ``` 1600859111.7595737 b'1600858988.4863389' 1600859112.760249 b'1600858988.5863452' 1600859113.760647 b'1600858988.6864707' 1600859114.761207 b'1600858988.7871313' 1600859115.761991 b'1600858988.8875835' ``` You can see big diffrence in times when data is received(right) and when is send(left). Why it's so much data buffered, and how can I get rid of this? I want possible newest frames, not the buffered ones.
2020/09/23
[ "https://Stackoverflow.com/questions/64026699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12250028/" ]
I found the anserw. I had to set socket option for the size of the input buffer. ``` sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0) ``` Set it to `0`, for max effinency.
38,827,783
All of a sudden, my Visual Studio has begun to popup a message every time I want to break my ASP.net project. [!["Debugging is being stopped but is not yet complete" dialog message.](https://i.stack.imgur.com/VEzra.png)](https://i.stack.imgur.com/VEzra.png) How can I get rid of this dialog? There is nothing to complete, only a debug session to get rid of. Clicking the "Stop Now" button will not immediately stop the execution, but wait some seconds. From what I know, I have not changed any configuration to get this dialog.
2016/08/08
[ "https://Stackoverflow.com/questions/38827783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1427758/" ]
Deleting all breakpoints **(Menu > Debug > Delete All Breakpoints)** and running in Debug mode fixed it. Unfortunately, nothing else did it for me. I had to again set the breakpoints that I wanted. Alternatively, you can choose to work around this problem by choosing the **Menu > Debug > Terminate All** option instead of clicking the **Stop Debugging (Shift + F5)** button. Microsoft announced that they have fixed it in the new release of VS 2017, per this [link](https://developercommunity.visualstudio.com/content/problem/33482/asp-net-core-debugging-closing-browser-window-does.html):
26,374,112
I basically want to create a timer. I have a textview where I need to show a timer like "Updating your location in 2min 29 secs" and I want the timer to decreament For eg 2min 28secs followed by 2min 27 secs. And I want to update it even when the user is not using my app (I dont want it to update in real sense what I mean is when user opens my app after say 1 min then the timer should show 1min 27 secs). Can some one please help me out in pointing out the correct and efficient way of doing this ? Thanks :)
2014/10/15
[ "https://Stackoverflow.com/questions/26374112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3064175/" ]
The most efficient way in my opinion is using [scheduleAtFixedRate](http://developer.android.com/reference/java/util/Timer.html#scheduleAtFixedRate%28java.util.TimerTask,%20long,%20long%29) when your activity is in foreground and when it is going to background you do not need any services you can just save the current time and the remaining time in a sharedpreferances and when again your activity comes to foreground read those values plus current time and then update the `textview` in a proper way.
3,694,597
> > Show that, if $P$ and $Q$ are constants and $$y = P\cos(\ln(t)) + Q\sin(\ln(t))$$ > then > $$t^2\frac{d^2y}{dt^2}+t\frac{dy}{dt}+y=0$$ > > >
2020/05/27
[ "https://math.stackexchange.com/questions/3694597", "https://math.stackexchange.com", "https://math.stackexchange.com/users/791189/" ]
Actually this is true only if $n\mid m$. Indeed $$n\cdot\mathbf Z/m\mathbf Z=(n\mathbf Z+m\mathbf Z)/m\mathbf Z=\gcd(m,n)\mathbf Z/m\mathbf Z.$$
66,334,998
In Numpy, say I have a matrix A of dimensions i x j x k, and a matrix B of dimensions k x i. How do I get back a product with dimensions k x i without using a loop? For example: ``` Let A = [[[1 2], [3 4]], [[5 6], [7 8]]] B = [[a b], [c d]] ``` I would like to get: ``` C = [[a+2c 5b+6d], [3a+4c 7b+8d]] ``` My current solution is ``` np.diagonal(np.dot(A, B), axis1=0, axis2=2) ``` However, the problem is I'm working with a large data set (`A` and `B` have huge dimensions) so `np.dot(A, B)` would lead to `MemoryError`. Therefore I want to figure out a better way to solve this without computing the dot product. I have looked into functions like `einsum` and `tensordot` but I didn't find what I need (or maybe I missed something). I would appreciate if someone could help me out. Thank you!
2021/02/23
[ "https://Stackoverflow.com/questions/66334998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11485718/" ]
You can do this by analyzing the input and output dimensions. ``` A.shape -> i, j, k B.shape -> k, i ``` Your example is not very good, but if you look carefully at what you're asking the output to be, the shape of `B` must match the first and last dimensions of `A`. The sum reduction is happening along the last axis of `A` and the first axis of `B`: ``` np.einsum('ijk,ki->ji', A, B) ``` `einsum` can be intimidating, but doing this sort of analysis can save you a lot of the frustration caused by trial and error.
10,070,701
The code below is in C# and I'm using Visual Studio 2010. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; namespace FrontEnd { class Flow { long i; private int x,y; public int X { get;set; } public int Y { get;set; } private void Flow() { X = x; Y = y; } public void NaturalNumbers(int x, int y) { for (i = 0; i < 9999; i++) { Console.WriteLine(i); } MessageBox.Show("done"); } } } ``` When I compile the above code I get this error: > > Error: 'Flow': member names cannot be the same as their enclosing type > > > Why? How can I resolve this?
2012/04/09
[ "https://Stackoverflow.com/questions/10070701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/961016/" ]
Method names which are same as the class name are called *constructors*. Constructors do not have a return type. So correct as: ``` private Flow() { X = x; Y = y; } ``` Or rename the function as: ``` private void DoFlow() { X = x; Y = y; } ``` Though the whole code does not make any sense to me.
88,886
I have a portrait with a blurred background. I'd like to use this to create a mask or for alpha channel or to erase the background. So after editing I want to have an image with perfect white or transparency where was the background and keep the face unchanged. Is it possible? What I tried yet: * made the image copy * converted this copy B/W * made the copy of this B/W layer * blured this copy * subtracted these copies: [![enter image description here](https://i.stack.imgur.com/3FfUp.png)](https://i.stack.imgur.com/3FfUp.png) So I hoped that *blurred blur* will be almost the same as *blur* and *blurred sharp* will differ from *sharp* parts of the picture. And the difference will be as an indication of the blureness. But I see that my idea did not worked for some reasons. Any other thoughts?
2017/04/23
[ "https://photo.stackexchange.com/questions/88886", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/25684/" ]
A little confused about your question: are you attempting to keep the face and remove the existing background? Are you having difficulty making a decent selection? If the above is correct, you'll want to make a selection of the face.There are a multitude of ways to do that in Photoshop. In this case,you'll want to make a selection of the background. If the background is solid, you could use color range. Otherwise you could make a selection of the face and then use inverse. I have found the select and mask option invaluable in refining my selections so that I don't have a halo or that pesky little color around the edges. There is a definite learning curve but well worth it. Once you have made the selection hit "delete" on your keyboard and there you have it! You can then make a new document and do what you want with that background - make it white or transparent. Hope this helps.
7,456,993
I have a twist on a common question I've seen in here, and I'm puzzled. What I need is simply a dialog box for each sub item of a list item. I have seen a dialog for a list item, but I need it down to the list item's item. Currently I've tried doing that within the adapter when inside the getView() method. For example: ``` @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater li = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = li.inflate(_resourceId, null); } string description = "howdy Test"; TextView description = (TextView) v.findViewById(R.id.description); description.setText(description ); description.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { AlertDialog.Builder dia = new AlertDialog.Builder(view.getContext()); dia.setTitle(view.getContext().getResources().getString(R.string.DESCRIPTION_TITLE)); dia.create(); } }); } ``` With that example above, it does go into the onClick() method, but nothing happens with the AlertDialog. Has anyone else tried this? is there a better way? Even better what am I doing wrong? Thanks, Kelly
2011/09/17
[ "https://Stackoverflow.com/questions/7456993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/703210/" ]
You have to call the `show()` method on your **dia** object.[Link here to the android docs!](http://developer.android.com/reference/android/app/AlertDialog.Builder.html#show%28%29)
5,670,745
Works fine in firefox but does nothing in ie. ``` <script type="text/javascript"> $(document).ready(function(){ var links = $('.bound'); var west = $('.west'); var west2 = $('.west2'); var west3 = $('.west3'); var west4 = $('.west4'); west2.hide(); west3.hide(); west4.hide(); links.click(function(event){ west.hide(); west2.hide(); west3.hide(); west4.hide(); west.filter('.' + event.target.id).show(); west2.filter('.' + event.target.id).show(); west3.filter('.' + event.target.id).show(); west4.filter('.' + event.target.id).show(); }); }); </script> ``` html ``` <div class="tabset"> <div id="tab1" class="tab-box"> <div class="form-holder"> <form action="#"> <fieldset> <label for="lb02"><strong>Choose District:</strong></label> <select id="lb02"> <option class="bound" id="west">WEST</option> <option class="bound" id="west2">WEST2</option> <option class="bound" id="west3">WEST3</option> <option class="bound" id="west4">WEST4</option> </select> </fieldset> </form> </div> <div class="report-box"> <table> <thead> <tr> <td class="name">Name</td> <td class="department">Department</td> <td class="title">Title</td> <td class="district">District</td> <td class="profile">&nbsp;</td> </tr> </thead> <tbody> <tr class="west"> <td>Name1</td> <td>Dept2</td> <td>Title2</td> <td>West</td> <td><a class="btn-profile" href="#">PROFILE</a></td> </tr> <tr class="west2"> <td>Name2</td> <td>Dept2</td> <td>Title2</td> <td>West2</td> <td><a class="btn-profile" href="#">PROFILE</a></td> </tr> </tbody> </table> </div> </div> ```
2011/04/14
[ "https://Stackoverflow.com/questions/5670745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/708908/" ]
Instead of a `click` event on the `option` elements, use a `change` event on the `select` element. ``` var links = $('#lb02'), wests = $('.west,.west2,.west3,.west4'); wests.not('.west').hide(); links.change(function(event) { wests.hide().filter('.' + this.options[this.selectedIndex].id).show(); }); ```
25,912,947
I'm trying to retrieve de int value of this reg dword: SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate I'm able to retrieve a strings' value, but i cant get the int value of the dword... At the end, i would like to have the install date of windows. I searched an found some solutions, but none worked. I'm starting with this: ``` public void setWindowsInstallDate() { RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\NT\CurrentVersion"); if (key != null) { object value = key.GetValue("InstallDate"); // some extra code ??? ... WindowsInstallDate = value; } } ``` Any suggestions?
2014/09/18
[ "https://Stackoverflow.com/questions/25912947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1663157/" ]
The issue you have is an issue between the 32 bit registry view and the 64 bit registry view as described on MSDN [here](http://msdn.microsoft.com/en-us/library/aa384129.aspx). To solve it you can do the following. Note that the returned value is a Unix timestamp (i.e. the number of seconds from 1 Jan 1970) so you need to manipulate the result to get the correct date: ``` //get the 64-bit view first RegistryKey key = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64); key = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); if (key == null) { //we couldn't find the value in the 64-bit view so grab the 32-bit view key = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32); key = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); } if (key != null) { Int64 value = Convert.ToInt64(key.GetValue("InstallDate").ToString()); DateTime epoch = new DateTime(1970, 1, 1); DateTime installDate = epoch.AddSeconds(value); } ``` The return from `GetValue` is an `Object` but `AddSeconds` requires a numeric value so we need to cast the result. I could have used `uint` above as that's big enough to store the [DWORD](http://msdn.microsoft.com/en-us/library/aa383751%28VS.85%29.aspx#dword) which is (32 bits) but I went with `Int64`. If you prefer it more terse you could rewrite the part inside the null check in one big line: ``` DateTime installDate = new DateTime(1970, 1, 1) .AddSeconds(Convert.ToUInt32(key.GetValue("InstallDate"))); ```
11,079,337
I am doing a transform work from windows to wince. For using iostream I choose `STLport5.2.1`. I get the compile error on *vs2008*: > > am files (x86)\windows ce tools\wce500\athenapbws\mfc\include\wcealt.h(248) : error C2084: function 'void \*operator new(size\_t,void \*)' already has a body > > > 2> D:\Program Files (x86)\Windows CE Tools\wce500\AthenaPBWS\include\ARMV4I../Armv4i/new(71) : see previous definition of 'new' > > > 2>d:\program files (x86)\windows ce tools\wce500\athenapbws\mfc\include\wcealt.h(254) : error C2084: function 'void operator delete(void \*,void \*)' already has a body > > > 2> D:\Program Files (x86)\Windows CE Tools\wce500\AthenaPBWS\include\ARMV4I../Armv4i/new(73) : see previous definition of 'delete' > > > 2>Util1.cpp > 2>D:\Program Files (x86)\Windows CE Tools\wce500\AthenaPBWS\include\ARMV4I../Armv4i/new(72) : error C2084: function 'void \*operator new(size\_t,void \*)' already has a body > > > 2> d:\program files (x86)\windows ce tools\wce500\athenapbws\mfc\include\wcealt.h(247) : see previous definition of 'new' > > > 2>D:\Program Files (x86)\Windows CE Tools\wce500\AthenaPBWS\include\ARMV4I../Armv4i/new(74) : error C2084: function 'void operator delete(void \*,void \*)' already has a body > > > 2> d:\program files (x86)\windows ce tools\wce500\athenapbws\mfc\include\wcealt.h(253) : see previous definition of 'delete' > > > How can you solve the error?
2012/06/18
[ "https://Stackoverflow.com/questions/11079337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1452611/" ]
Put prefer external into your Manifest ``` <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="preferExternal" ... > ```
54,645,489
I have a folder named "Models" located at app/models in my laravel project directory. I want to use all models by a single line of code in controller, instead of using each one like: ``` use App/Models/User; use App/Models/Roles; ```
2019/02/12
[ "https://Stackoverflow.com/questions/54645489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8511942/" ]
If i get the question correctly, you need to get the initial text from a tag just before the child tag. A tag’s children are available in a list called [.contents](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#contents-and-children) . You can use `.contents[0]` ``` from bs4 import BeautifulSoup html=""" <span class="t-small summary-count"> Showing 1-25 of 131 ads for <span>"Samsung Galaxy A5"</span>.</span> """ soup=BeautifulSoup(html,'html.parser') pgn = soup.find("span", {"class": "t-small summary-count"}) print(pgn.contents) print(pgn.contents[0]) ``` Output ``` [' Showing 1-25 of 131 ads for ', <span>"Samsung Galaxy A5"</span>, '.'] Showing 1-25 of 131 ads for ```
19,444,188
I want to save `numpy.array` data into XML file, then read it again. following is my code: **array to string** ``` arr=numpy.zeros((20)) s = str(arr) ``` But This way would generate **enter key and '[',']'** characters in the string. **string to array** I should remove the enter key and '[',']' first. And then use `numpy.fromstring` But I don't think that's a good way to do that. **And that can't work on 2-D array**
2013/10/18
[ "https://Stackoverflow.com/questions/19444188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/936332/" ]
You are mixing two different ways of doing "to string": ``` a = numpy.zeros((20)) ``` you can, after stripping newlines and `[]` from it, put `str(a)` in a new `numpy.matrix()` constructor and initialize `numpy.array()` with the returned value: ``` b = numpy.array(numpy.matrix(" ".join(str(a).split()).strip('[]'))) ``` or you can combine `numpy.array.tostring()` with `numpy.fromstring()`: ``` c = numpy.fromstring(a.tostring()) ``` but mixing and matching like you tried to do does not work.
10,850
I am publishing everything in the broker database and able to fetch entire component value with the help of ComponentPresentation class and ComponentFactory class. I am using ComponentPresentation.getContent(true) method to fetch the entire content. But my requirement is to retrieve some specific field value from one of the component. but i am unable to do so. Can anybody tell me with an example how I can do that?
2015/01/20
[ "https://tridion.stackexchange.com/questions/10850", "https://tridion.stackexchange.com", "https://tridion.stackexchange.com/users/1390/" ]
In broker final content (xml or html as per your architecture) is published. individual field values (as key values) are not published, so You can not directly fetch any component value. you have to parse your Xml/Html to get that field value. one of the possible way could be to use metadata, to directly fetch the value from broker.
50,161,290
I need assistance in creating a query. I have Client table that has unique client info - identified by their unique ClientID. I also have a Client\_UserDefinedFields table that contains values of custom data for clients. They are linked via the ClientID and there may be many records for a ClientID in this Client\_UserDefinedFields table. My situation is that there are 3 custom data fields that I need to know the values for a given client (as shown by my CASE statement). My current query is bringing back the client 3 times (a row for each value) and I want to only see the client once (one row) and have these values shown as columns. Not sure if this is possible or how to that. Furthermore, when I tried using a CASE statement in my select, I cannot use AS 'fieldname' to identify it - since it's giving me an error on the AS keyword. An example of my current SQL SELECT statement ``` SELECT c.ClientID , c.LastName , c.FirstName , c.MiddleName , CASE WHEN cudf.UserDefinedFieldFormatULink = '93fb3820-38aa-4655-8aad-a8dce8aede' THEN cudf.UDF_ReportValue --AS 'DA Status' WHEN cudf.UserDefinedFieldFormatULink = '2144a742-08c5-4c96-b9e4-d6f1f56c76' THEN cudf.UDF_ReportValue --AS 'FHAP Status' WHEN cudf.UserDefinedFieldFormatULink = 'c3d29be9-af58-4241-a02d-9ae9b43ffa' THEN cudf.UDF_ReportValue --AS 'HCRA Status' END FROM Client_Program cp INNER JOIN client c ON c.ulink = cp.clientulink INNER JOIN code_program p ON p.ulink = cp.programulink INNER JOIN Code_System_State css ON c.ContactMailingStateUlink = css.ulink INNER JOIN Code_ClientStatus ccs ON c.ClientStatusULink = ccs.ULink INNER JOIN Client_UserDefinedField cudf ON c.ULink = cudf.ClientULink AND cp.ProgramStatusULink = '1' -- Open (active) program AND c.ClientStatusULink = '10000000' --Active client AND cp.programulink in ('7280f4a7-cd94-49be-86ad-a74421ff6f', '0a9b94a3-edd7-4918-b79c-bf2b20f9da', '54f6c691-2eba-49e5-8380-85f5349bca', 'ed8c497d-d4fe-41d7-a218-4235fd0734', '5be826f0-b3c3-4ebe-871d-4d20b56da5') AND cudf.UserDefinedFieldFormatULink IN ('93fb3820-38aa-4655-8aad-a8dce8aede', -- DA Status '2144a742-08c5-4c96-b9e4-d6f1f56c76', --FHAP Status 'c3d29be9-af58-4241-a02d-9ae9b43ffa') --HCRA Status ``` Again, my issue is that I don't want to bring back the same client multiple times if they had more than one entry in the Client\_UserDefinedFields table. I'd like to bring this in one row with each "Status" field correctly populated as a columns. How do I do this? Here's a sample of my current output: ``` ClientID LastName FirstName MiddleName PCHP/HCH Status DA Status FHAP Status HCRA Status XXXXXXXXXXXX River Mike Allan Active (null) - None Selected - (null) XXXXXXXXXXXX River Mike Allan Active Active (null) (null) XXXXXXXXXXXX River Mike Allan Active (null) (null) - None Selected - ``` Ultimately would like to see just the one record with all the values ``` ClientID LastName FirstName MiddleName PCHP/HCH Status DA Status FHAP Status HCRA Status XXXXXXXXXXXX River Mike Allan Active Active - None Selected - - None Selected - ``` Examples are very helpful as I'm not a SQL guru. Thank you!
2018/05/03
[ "https://Stackoverflow.com/questions/50161290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1218207/" ]
Finally i manage to come up with the query in linq, dont know how to do it in lambda, but it works fine. ``` var obj = (from emisor in _context.DbSetEmisores where emisor.EmisorCuenta == cuenta select new EmisorDto { Segmento = ((from itemConf in _context.ItemsDeConfiguracion where itemConf.ConfigID == "SEGM" && itemConf.ConfigItemID == emisor.SegmentoId select new { itemConf.ConfigItemDescripcion }).FirstOrDefault().ConfigItemDescripcion), Marca = ((from itemConf in _context.ItemsDeConfiguracion where itemConf.ConfigID == "MRCA" && itemConf.ConfigItemID == emisor.MarcaId select new { itemConf.ConfigItemDescripcion }).FirstOrDefault().ConfigItemDescripcion), Producto = emisor.Producto, Familia = emisor.Familia, SegmentoId = emisor.SegmentoId, MarcaId = emisor.MarcaId, }).FirstOrDefault(); ```
9,963,367
I am trying to make a thing, but I have hit a problem. I have tried all I know, but I am new to [MySQL](http://en.wikipedia.org/wiki/MySQL), so I have hit a dead end. This code: ``` <?php require('cfg.php'); mysql_connect($server, $user, $pass) or die(mysql_error()); mysql_select_db($database) or die(mysql_error()); if (isset($_GET['name'])){ $name = $_GET['name']; } else if (isset($_POST['submit'])){ $name = $_POST['name']; $name1 = $_POST['name1']; $name2 = $_POST['name2']; $name3 = $_POST['name3']; mysql_query("INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 ) ") or die(mysql_error()); echo ("Data entered successfully!"); } ?> <html> <head> <title>Random giffgaff simmer</title> </head> <body> <form action="" method="post"> <p>Your Username: <input type="text" name="name"></p> <p>Username 1: <input type="text" name="name1"></p> <p>Username 2: <input type="text" name="name2"></p> <p>Username 3: <input type="text" name="name3"></p> <p>Username 4: <input type="text" name="name4"></p> <p>Username 5: <input type="text" name="name5"></p> <p>Username 6: <input type="text" name="name6"></p> <p><input type="submit" name="submit" value="Submit"></p> </form> </body> </html> ``` Brings this error: > > You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' )' at line 1 > > > Now, that would tell me that this SQL code has a syntax error: ``` INSERT INTO data (name, name1, name2, name3) VALUES($name, $name1, $name2, $name3 ) ``` But I don't think I can see one?
2012/04/01
[ "https://Stackoverflow.com/questions/9963367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1124470/" ]
You haven't quoted your query. You should quote every field like this ``` INSERT INTO data (name, name1, name2, name3) VALUES('$name', '$name1', '$name2', '$name3' ) ``` As an tribute to TheCommonSense, I am providing a mysqli version using correct prepared statement for data safety ``` $db = new mysqli(...); $stmt = $db -> prepare("INSERT INTO data (name, name1, name2, name3) VALUES(?, ?, ?, ?)"); $stmt -> bind_param("ssss", $name, $name1, $name2, $name3); $stmt -> execute(); $db -> close() ```
17,293,922
I am using a program that pastes what is in the clipboard in a modified format according to what I specify. I would like for it to paste paths (i.e. "C:\folder\My File") without the pair of double quotes. This, which isn't using RegEx works: Find " (I simply enter than in one line) and replace with nothing. I enter nothing in the second field. I leave it blank. Now, though that works, it will remove double quotes in this scenario: Bob said "What are you doing?" I would like the program to remove the quotes only if the the words enclosed in the double quotes have a backslash. So, once again, just to make sure I am clear, I need the following: 1) RegEx Expression to find strings that have both double quotes and a backslash within those set of quotes. 2) A RegEx Expression that says: replace the backslashes with backslashes (i.e. leave them there). Thank you for the fast response. This program has two fields. One for what to find and the other for what to replace. So, what would go in the 2nd field? ![enter image description here](https://i.stack.imgur.com/k9fvH.jpg) The program came with the Remove HTML entry, which has <[^>]\*> in the match pattern and nothing (it's blank) in the Replacement field.
2013/06/25
[ "https://Stackoverflow.com/questions/17293922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2519402/" ]
You didn't say which language you use, here's an example in Javascript: ``` > s = 'say "hello" and replace "C:\\folder\\My File" thanks' "say "hello" and replace "C:\folder\My File" thanks" > s.replace(/"([^"\\]*\\[^"]*)"/g, "$1") "say "hello" and replace C:\folder\My File thanks" ```
20,038,409
First thing I am not an expert in writing VBScripts. I have a requirement of deleting files & folders of remote systems with just 1 click. I was trying to build below VBScript but somehow it’s not working. I request any of your help to correct the same or with a new script that help me to fulfill the requirement. Any help in this regard is greatly appreciated, Thanks in Advance. With the below: C:\Test - is the directory from where I would like to delete the files & subfolders C:\computerList.txt – is the text file contains all remote systems IP Address. ``` Const strPath = "C:\Test" Set computerList = objfso.OpenTextFile ("C:\computerList.txt", 1) Dim objFSO Set objFSO = CreateObject("Scripting.FileSystemObject") Call Search (strPath) WScript.Echo"Done." Sub Search(str) Do While Not computerList.AtEndOfStream strComputer = computerList.ReadLine Dim objFolder, objSubFolder, objFile Set objFolder = objFSO.GetFolder("\\" & strComputer & "\" & str) For Each objFile In objFolder.Files If objFile.DateLastModified < (Now() - 0) Then objFile.Delete(True) End If Next For Each objSubFolder In objFolder.SubFolders Search(objSubFolder.Path) ' Files have been deleted, now see if ' the folder is empty. If (objSubFolder.Files.Count = 0) Then objSubFolder.Delete True End If Next loop End Sub ``` Regards, Balaram Reddy
2013/11/18
[ "https://Stackoverflow.com/questions/20038409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3002951/" ]
Your first problem is that you have the line order incorrect: ``` Set computerList = objfso.OpenTextFile ("C:\computerList.txt", 1) Dim objFSO Set objFSO = CreateObject("Scripting.FileSystemObject") ``` Should be ``` Dim objFSO Set objFSO = CreateObject("Scripting.FileSystemObject") Set computerList = objfso.OpenTextFile ("C:\computerList.txt", 1) ``` You are using objfso before declaring it
31,751,705
I'm trying to redirect to the previous page after a user logs in. I am using a bootstrap modal for login/register forms but if someone doesn't have JS enabled on their browser and are taken to the '/login' page, I want to make sure they are redirected to the root url. I know current\_page? does not work with POST requests. I've tried tons of things so the following code is redirecting correctly from the '/login' page to the root url but I am not being redirected to ':back' when logging in using the bootstrap modal. This is from SessionsController: (PS- I have sessions#new/sessions#create as /login in routes) ``` def create user = User.find_by(email: params[:email]) if user && user.authenticate(params[:password]) session[:user_id] = user.id if request.path === '/login' redirect_to '/' else redirect_to :back end flash[:success] = "Logged in." else flash.now[:danger] = "Email and password did not match. Please try again." render :new end end def destroy session[:user_id] = nil flash[:success] = "Logged out." redirect_to '/' end ``` Routes.rb: ``` Rails.application.routes.draw do root to: 'home#home' resources :users get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' get '/logout', to: 'sessions#destroy' end ```
2015/07/31
[ "https://Stackoverflow.com/questions/31751705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5057766/" ]
I figured it out. I basically create an order variable, name that variable the animal names, and then use that ordered variable to create the chart rather than the animals themselves. Below is the quick process: Create an order variable ``` data test1; set test; temp=_n_; char_animal=put(temp,3.); run; ``` Put your sequence of animals in a list ``` proc sql; select distinct quote(animal) into: animallist separated by " " from test1 order by temp; quit; %put &animallist.; ``` In the `axis3` statement, use the macro list in the value statement to "name" the order variable the animal names ``` axis1 label=(f=arial h=1.5 'Time to Death (Hours Post-Exposure)') value=(f=arial h=1) order=(0 to 840 by 120) minor=(n=5) offset=(1,1); axis2 label=(f=arial h=1.2 j=r 'Group') value=(f=arial h=1); axis3 label=(f=arial h=1.2 j=c 'Animal') value=(f=arial h=1 &animallist.); PATTERN1 C=BLACK; proc gchart data=test1; hbar char_animal /group=group nozero nostats sumvar=ttd type=sum width=0.4 space=1 raxis=axis1 gaxis=axis2 maxis=axis3; run; quit; ``` Notice the correct order in the graphic now: [![enter image description here](https://i.stack.imgur.com/nulm2.png)](https://i.stack.imgur.com/nulm2.png)
6,405,614
In my XAML, I am trying to implement the folowing: ``` <DataTrigger Binding="{Binding Path=Word}" Value="\n"> ``` but this does not work, even though Word is \n. I suspect that \n is not the right way to express newline in XAML, but what would be?
2011/06/19
[ "https://Stackoverflow.com/questions/6405614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339843/" ]
Yes, setting a distant expiry header and the asset will not be downloaded again until that expiry. > > If you remove the Last-Modified and ETag header, you will totally eliminate If-Modified-Since and If-None-Match requests and their 304 Not Modified Responses, so a file will stay cached without checking for updates until the Expires header indicates new content is available! > > > [Source](http://www.askapache.com/htaccess/apache-speed-last-modified.html).
43,587,165
To get row information of currently selected row we can do this ``` var current = e.sender.dataItem(e.sender.select()); ``` But how to get the same when i click on Edit button? I tried `$("#grid").data("kendoGrid").dataItem($(e.sender).closest("tr"));` it didnt work. **EDIT** I tried ways as suggested on the answers below, but its still giving me null. in the screenshot the commented code doesn't work either [![enter image description here](https://i.stack.imgur.com/IQUt1.jpg)](https://i.stack.imgur.com/IQUt1.jpg) **COMPLETE CODE** ```html <script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Kendo UI Snippet</title> <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.common.min.css" /> <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.rtl.min.css" /> <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.silver.min.css" /> <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.mobile.all.min.css" /> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <!--<script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>--> <!--<script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>--> <script src="Scripts/KendoUI.js" type="text/javascript"> </head> <body> <div id="grid"> </div> <script> $("#grid").kendoGrid({ columns: [ { field: "id" }, { field: "name" }, { field: "age" }, { command: "edit" }, { command: "list" } ], dataSource: { data: [ { id: 1, name: "Jane Doe", age: 30 }, { id: 2, name: "John Doe", age: 33 } ], schema: { model: { id: "id", fields: { "id": { type: "number" } } } } }, editable: "popup", toolbar: ["create"], dataBound: function (e) { //<input name="age" class="k-input k-textbox" type="text" data-bind="value:age"> }, edit: function (e) { //This currentItem is null :( var currentItem = $("#grid").data("kendoGrid").dataItem($(e.sender).closest("tr")); if (!e.model.isNew()) { $('.k-window-title').text("Newton Sheikh"); } } }); </script> </body> </html> ```
2017/04/24
[ "https://Stackoverflow.com/questions/43587165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2110531/" ]
You should use `e.container` instead of `e.sender`, like this: ``` $("#grid").data("kendoGrid").dataItem($(e.container).closest("tr")) ``` **Update to make it work with a popup** If you are using a popup editor, then the container will be the popup itself and the above will not work. In that case, you can use the uid of the row to locate it within the table: ``` var row = $("#grid").data("kendoGrid").tbody.find("tr[data-uid='" + e.model.uid + "']"); ``` If you do not need a reference to the actual row, but only the data item, then you can simply use `e.model`. I have created a dojo with your code and if you check the console after you click "edit", you will see that there is no difference: <http://dojo.telerik.com/iqAPO>
57,101,872
I fixed a bug recently. In the following code, one of the overloaded function was const and the other one was not. The issue will be fixed by making both functions const. My question is why compiler only complained about it when the parameter was 0. ``` #include <iostream> #include <string> class CppSyntaxA { public: void f(int i = 0) const { i++; } void f(const std::string&){} }; int main() { CppSyntaxA a; a.f(1); // OK //a.f(0); //error C2666: 'CppSyntaxA::f': 2 overloads have similar conversions return 0; } ```
2019/07/18
[ "https://Stackoverflow.com/questions/57101872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4005852/" ]
`0` is special in C++. A null pointer has the value of `0` so C++ will allow the conversion of `0` to a pointer type. That means when you call ``` a.f(0); ``` You could be calling `void f(int i = 0) const` with an `int` with the value of `0`, or you could call `void f(const std::string&)` with a `char*` initialized to null. Normally the `int` version would be better since it is an exact match but in this case the `int` version is `const`, so it requires "converting" `a` to a `const CppSyntaxA`, where the `std::string` version does not require such a conversion but does require a conversion to `char*` and then to `std::string`. This is considered enough of a change in both cases to be considered an equal conversion and thus ambiguous. Making both functions `const` or non `const` will fix the issue and the `int` overload will be chosen since it is better.
12,201,541
can anyone give me pointers to a library/way of getting country specific calendars. THis is because I am looking to implement Quartz and would like to use different calendars for different countries. THank you
2012/08/30
[ "https://Stackoverflow.com/questions/12201541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1479589/" ]
I would suggest trying Joda Time <http://joda-time.sourceforge.net/> , which has different Chronologies.
10,456,215
I am trying to use activeX to start a windows form application written in C# from my ASP.net website. When I click a button I would like a new page to open up and activeX on that page would call my windows application. I am using Visual Studio 2010. I have followed this tutorial: <http://dotnetslackers.com/articles/csharp/WritingAnActiveXControlInCSharp.aspx> However, that tutorial is only for 1 C# file which you compile via console. My questions are the following: 1.How would I compile the entire windows form project to use the /t:library and regasm? 2.I have followed this question answer to modify my windows form application: [How do I create an ActiveX control (COM) in C#?](https://stackoverflow.com/questions/3360160/how-do-i-create-an-activex-com-in-c). However, like in both examples, they do not have a Main method. When I tried to modify the code of my windows form app, I get the error saying the program does not have a Main method for entry if I take it out and replace it with a Launch() method. I am sure I am missing something? 3.Would I just write the java script on the new .aspx page to access the application? P.S. I am trying to open this open source windows form application: <http://www.codeproject.com/Articles/239849/Multiple-face-detection-and-recognition-in-real-ti> Thank you kindly
2012/05/04
[ "https://Stackoverflow.com/questions/10456215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/849509/" ]
*The question to ask yourself is, how long do you need to persist the data?* If you only need to save the data to pass it to the next action you can use **POST** or **GET**, the **GET** would pass through the url and the **POST** would not(*typically*). The example you presented would suggest that you need to persist the data just long enough to validate, filter and process the data. So you would likely be very satisfied passing the few pieces of data around as parameters(**POST** or **GET**). This would provide the temporary persistence you need and also provide the added benefit of the data expiring as soon as a request was made that did not pass the variables. A quick example (assume your form passes data with the **POST** method): ``` if ($this->getRequest()->isPost()) { if ($form->isValid($this->getRequest()->getPost()){ $data = $form->getValues();//filtered values from form $model = new Appliction_Model_DbTable_MyTable(); $model->save($data); //but you need to pass the users name from the form to another action //there are many tools in ZF to do this with, this is just one example return $this->getHelper('Redirector')->gotoSimple( 'action' => 'newaction', array('name' => $data['name'])//passed data ); } } ``` if you need to persist data for a longer period of time then the **$\_SESSION** may come in handy. In ZF you will typically use `Zend_Session_Namespace()` to manipulate session data. It's easy to use `Zend_Session_Namespace`, here is an example of how I often use it. ``` class IndexController extends Zend_Controller_Action { protected $_session; public function init() { //assign the session to the property and give the namespace a name. $this->_session = new Zend_Session_Namespace('User'); } public function indexAction() { //using the previous example $form = new Application_Form_MyForm(); if ($this->getRequest()->isPost()) { if ($form->isValid($this->getRequest()->getPost()){ $data = $form->getValues();//filtered values from form //this time we'll add the data to the session $this->_session->userName = $data['user'];//assign a string to the session //we can also assign all of the form data to one session variable as an array or object $this->_session->formData = $data; return $this->getHelper('Redirector')->gotoSimple('action'=>'next'); } } $this->view->form = $form; } public function nextAction() { //retrieve session variables and assign them to the view for demonstration $this->view->userData = $this->_session->formData;//an array of values from previous actions form $this->view->userName = $this->_session->userName;//a string value } } } ``` any data you need to persist in your application can sent to any action, controller or module. Just remember that if you resubmit that form the information saved to those particular session variables will be over written. There is one more option in ZF that kind of falls between passing parameters around and storing data in sessions, `Zend_Registry`. It's use is very similar to `Zend_Session_Namespace` and is often used to save configuration data in the bootstrap (but can store almost anything you need to store) and is also used by a number of internal Zend classes most notably the [flashmessenger action helper](http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.flashmessenger). ``` //Bootstrap.php protected function _initRegistry() { //make application.ini configuration available in registry $config = new Zend_Config($this->getOptions()); //set data in registry Zend_Registry::set('config', $config); } protected function _initView() { //Initialize view $view = new Zend_View(); //get data from registry $view->doctype(Zend_Registry::get('config')->resources->view->doctype); //...truncated... //Return it, so that it can be stored by the bootstrap return $view; } ``` I hope this helps. Pleas check out these links if you have more questions: [The ZF Request Object](http://framework.zend.com/manual/en/zend.controller.request.html) [Zend\_Session\_Namespace](http://framework.zend.com/manual/en/zend.session.basic_usage.html) [Zend\_Registry](http://framework.zend.com/manual/en/zend.registry.using.html)
50,364
I've wandered into some dungeon and encountered some necromancers or bandits. I killed some with sneak attack by bow and some turned hostile and they rush to me and I killed them directly. When I sleep, there are no Dark Brotherhood members approaching me. Why?
2012/02/10
[ "https://gaming.stackexchange.com/questions/50364", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/7993/" ]
According to the [Elder Scrolls wiki](http://www.uesp.net/wiki/Oblivion:A_Knife_in_the_Dark), > > you must murder someone in cold blood. In other words, you must murder an innocent without provocation (note that Bandits and the like do not count as the required murder). Once the deed is done, regardless of who is there, the cryptic message "Your killing has been observed by forces unknown..." will appear in the corner of your screen, indicating you will be visited the next time you sleep. > > > Basically any non-essential NPC will do. (Note that unlike in Morrowind, Oblivion's predecessor, you cannot kill an essential NPC, so you don't have to worry about killing the "wrong" person. If an NPC is involved in a quest you haven't completed, you won't be able to kill them.) If you are looking for a specific set of targets, the wiki has a [list of them](http://www.uesp.net/wiki/Oblivion:Dark_Brotherhood#Targets). I've listed a few of the best targets below: > > -- The Skooma Den in Bravil has 4 residents, 3 with 0 responsibility, so your crime will likely go unreported. > > -- Camonna Tong Thug: Killing one of the two Camonna Tong thugs at Walker camp will give you no bounty, as they both have low responsibility. If you attack one of them before he attacked you, killing him is counted as a murder, and will allow you to join the Dark Brotherhood. They both respawn in a few days, as well. > > -- Alval Uvani has a rather low responsibility, and since he does a lot of traveling (see the Dark Brotherhood mission A Matter of Honor for details) it's rather easy to dispose of him on the road without witnesses. The benefit of killing Alval is that you will have already completed one of the later Brotherhood missions. > > >
3,175,607
Im trying to define an array of arrays as a Constant in one of my classes, the code looks like this: ``` Constant = [[1,2,3,4], [5,6,7,8]] ``` When I load up the class in irb I get: ``` NoMethodError: undefined method `[]' for nil:NilClass ``` I tried using %w and all that did was turn each one into a string so i got "[1,2,3,4]" instead of [1,2,3,4] how do I define an array of arrays as a constant? Im using ruby 1.8.7. When I define the constant in IRB its fine, but when I load up the class with it in i get an error. ``` require 'file_with_class.rb' NoMethodError: undefined method `[]' for nil:NilClass from ./trainbbcode/tags.rb:2 from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require' from (irb):1 ``` That file looks like this: ``` class TBBC Tags = [[/\[b\](.*?)\[\/b\]/,'<strong>\1</strong>',@config[:strong_enabled]], ... [/\[th\](.*?)\[\/th\]/,'<th>\1</th>',@config[:table_enabled]]] ```
2010/07/04
[ "https://Stackoverflow.com/questions/3175607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222018/" ]
The code you showed works just fine. You're definitely not getting that error message for that particular line. The error is caused elsewhere. And yes, `%w` creates an array of strings. To create normal arrays use `[]` like you did. Edit now that you've shown the real code: `@config` is `nil` in the scope where you use it, so you get an exception when you do `@config[:strong_enabled]`. Note that inside of a class definition but outside of any method definition `@foo` refers to the instance variable of the class object, not that of any particular instance (because which one would it refer to? There aren't even any instances yet, when the constant is initialized).
2,417
``` cleos --url http://127.0.0.1:8888 --wallet-url http://127.0.0.1:8899 push action eosio.token create '["eosio", "2000000000.0000 KBS"]' --permission eosio.token@active cleos --url http://127.0.0.1:8888 --wallet-url http://127.0.0.1:8899 push action eosio.token issue '["eosio", "100000000.0000 KBS", ""]' --permission eosio@active cleos --url http://127.0.0.1:8888 --wallet-url http://127.0.0.1:8899 system newaccount eosio intblue11112 EOS6w5oLk1NcLvvnfW4YVqeohoX3GV3t79LT8CJEZczBTEJVKYzeC EOS6w5oLk1NcLvvnfW4YVqeohoX3GV3t79LT8CJEZczBTEJVKYzeC --stake-net "10000.0000 KBS" --stake-cpu "10000.0000 KBS" --buy-ram-kbytes 8192 assertion failure with message: symbol precision mismatch ``` why ?
2018/09/21
[ "https://eosio.stackexchange.com/questions/2417", "https://eosio.stackexchange.com", "https://eosio.stackexchange.com/users/2283/" ]
When you build from source, you can specify what the core symbol token will be by adding the flag `-s`: `./eosio_build.sh -s "KBS"` ``` printf "Usage: %s \\n[Build Option -o <Debug|Release|RelWithDebInfo|MinSizeRel>] \\n[CodeCoverage -c] \\n[Doxygen -d] \\n[CoreSymbolName -s <1-7 characters>] \\n[Avoid Compiling -a]\\n[Noninteractive -y]\\n\\n" "$0" 1>&2 # ... \\n[CoreSymbolName -s <1-7 characters>] ``` <https://github.com/EOSIO/eos/blob/master/scripts/eosio_build.sh#L104> ``` # CORE_SYMBOL_NAME="SYS" CORE_SYMBOL_NAME="KBS" ``` <https://github.com/EOSIO/eos/blob/master/scripts/eosio_build.sh#L38>
42,853,292
Is there a way to add buttons from a specific wrappanel to an array or list in code? I tried the code below, but it doesn't work: ``` foreach(Button b in nameOfWrappanel) { list.Add(b); } ```
2017/03/17
[ "https://Stackoverflow.com/questions/42853292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790802/" ]
You have to specify wrappanel.children to access its child. ``` foreach (Button b in nameOfWrappanel.Children) { list.Add(b); } ```
37,907,105
this is my spring-security.xml: ``` <security:http pattern="/eklienci/**" authentication-manager-ref="authenticationManager" entry-point-ref="restAuthenticationEntryPoint" create-session="stateless"> <security:intercept-url pattern="/eklienci/**" access="hasAnyAuthority('ADMIN','USER','VIEWER')" /> <form-login authentication-success-handler-ref="mySuccessHandler" authentication-failure-handler-ref="myFailureHandler" /> <security:custom-filter ref="restServicesFilter" before="PRE_AUTH_FILTER" /> </security:http> <!-- other stuff --!> <beans:bean id="restAuthenticationEntryPoint" class="pl.aemon.smom.config.RestAuthenticationEntryPoint" /> <!-- Filter for REST services. --> <beans:bean id="restServicesFilter" class="pl.aemon.smom.config.RestUsernamePasswordAuthenticationFilter"> <beans:property name="postOnly" value="true" /> <beans:property name="authenticationManager" ref="authenticationManager" /> <beans:property name="authenticationSuccessHandler" ref="mySuccessHandler" /> </beans:bean> ``` This is my RestUsernamePasswordAuthenticationFilter: ``` public class RestUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { @Autowired private CustomAuthenticationProvider authenticationProvider; @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { Enumeration<String> names = request.getHeaderNames(); while(names.hasMoreElements()) { System.out.println(names.nextElement()); } String username = obtainUsername(request); String password = obtainPassword(request); System.out.println("Username " + username + " password: " + password); if(username!=null) { username = username.trim(); } UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); // Allow subclasses to set the "details" property setDetails(request, authRequest); return authenticationProvider.authenticateRest(authRequest); // System.out.println(auth.toString()); // return auth; } @Override protected String obtainPassword(HttpServletRequest request) { return request.getHeader("password"); } @Override protected String obtainUsername(HttpServletRequest request) { return request.getHeader("username"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; Authentication auth = attemptAuthentication(httpRequest, httpResponse); SecurityContextHolder.getContext().setAuthentication(auth); chain.doFilter(request, response); } } ``` And this is my RestController methods ``` @RestController @RequestMapping("/eklienci") public class EklientRestController { @RequestMapping(value="/get/{eklientid}") public Eklient get(@PathVariable String eklientid) { return userService.findById(eklientid); } @RequestMapping(value = "/add", method = RequestMethod.POST, produces="application/json", consumes="application/json") @ResponseBody public String add(@RequestBody String json) { System.out.println(json); Eklient pj = new Eklient(); ObjectMapper mapper = new ObjectMapper(); try { pj = mapper.readValue(json, Eklient.class); return mapper.writeValueAsString(pj); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "Error"; } } ``` When i try to call /get/{eklientid}, it always works fine. All GET calls always returns at least infomration about UNARTHORIZED access (401) and i see logs from RestUsernamePasswordAuthenticationFilter. But when i try any POST call (for example /eklienci /add} my application always returns 403 code and doesn't producde any log. What is the reason? How to fix it ?
2016/06/19
[ "https://Stackoverflow.com/questions/37907105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2420030/" ]
[CSRF](http://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html) is activated by default for the common non-GET methods like POST, PUT, DELETE causing 403s if you haven't placed the CSRF headers in your REST calls. You can (temporarily!) shut off CSRF in your security.xml to confirm that's the issue. Mainly you'll need to add the [CSRF headers](https://github.com/gmazza/tightblog/blob/b32c215e5c904070d02d6a837496819e05b953f4/app/src/main/webapp/tb-ui/scripts/commonjquery.js#L9-10) into your REST calls and [`<sec:csrfInput/>`](https://github.com/gmazza/tightblog/blob/b32c215e5c904070d02d6a837496819e05b953f4/app/src/main/webapp/WEB-INF/jsps/editor/EntryEdit.jsp#L78) JSPs tags for any client-server calls. FYI, additional classes I needed to implement in my open-source project, perhaps useful for you: 1. [CsrfSecurityRequestMatcher](https://github.com/gmazza/tightblog/blob/master/app/src/main/java/org/apache/roller/weblogger/ui/core/security/CsrfSecurityRequestMatcher.java) to turn off CSRF for certain POSTs/PUTs, etc., that don't require authorization. As configured [here](https://github.com/gmazza/tightblog/blob/b32c215e5c904070d02d6a837496819e05b953f4/app/src/main/webapp/WEB-INF/security.xml#L50) in my security.xml. 2. [CustomAccessDeniedHandlerImpl](https://github.com/gmazza/tightblog/blob/master/app/src/main/java/org/apache/roller/weblogger/ui/core/security/CustomAccessDeniedHandlerImpl.java) to route CSRF 403's resulting from session timeouts to a login page instead.
18,488,096
Here's my table A ``` orderID groupID nameID 1 grade A foo 2 grade A bar 3 grade A rain 1 grade B rain 2 grade B foo 3 grade B bar 1 grade C rain 2 grade C bar 3 grade C foo ``` Desired result: ``` rain bar foo ``` I need `nameID` of `max(orderID)` from each grade. I can get right `orderID` from each grade, but `nameID` always stays as the first. Thanks a Lot! --- Praveen gave the right query! Extra question under his answer
2013/08/28
[ "https://Stackoverflow.com/questions/18488096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2689375/" ]
**edit:** I just fixed a mistake in my answer. You are looking for something quite like: ``` select orderID, groupID, nameID from A where concat(orderID,'-',groupId) in (select concat(max(orderID),'-',groupId) from A group by groupID) ``` **edit:** in regards to the extra question: To put the list in order of nameId, just add to the query: ``` order by nameID ```
2,454,550
I have the following problem. My client program monitor for availability of server in the local network (using Bonjour, but it does not rally mater). As soon as a server is "noticed" by the client application, the client tries to create a socket: `Socket(serverIP,serverPort);`. At some point the client can loose the server (Bonjour says that server is not visible in the network anymore). So, the client decide to `close` the socket, because it is not valid anymore. At some moment the server appears again. So, the client tries to create a new socket associated with this server. But! The server can refuse to create this socket since it (server) has already a socket associated with the client IP and client port. It happens because the socket was closed by the client, not by the server. Can it happen? And if it is the case, how this problem can be solved? Well, I understand that it is unlikely that the client will try to connect to the server from the same port (client port), since client selects its ports randomly. But it still can happen (just by chance). Right?
2010/03/16
[ "https://Stackoverflow.com/questions/2454550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245549/" ]
Yes, close the socket, as soon as you detect a failure. The socket will be "stuck" in "close\_wait" if not closed properly. Even if the socket is closed, it's state will be in time\_wait for a short period. However, if You design the application to use a different local port for each new connection, there is no need to wait for the old socket to be closed. (As you are then creating a completly different socket, since a socket is identified by the remote-ip, remote port, local ip and local port.)
69,727,847
So I'm making a voice assistant in Python and I want it to do math that I input. This code checks if it ends with an integer: ``` elif text[-1].isdigit() == True: basicmath() ``` Then the function basicmath(): ``` def basicmath(): split = text.split(" ") in1 = split[0] in2 = split[5] op = split[3] print(op) if op == "+": m = in1+in2 worked = "y" mathout = str(m) print(mathout) elif op == "-": m = in1-in2 worked = "y" mathout = str(m) print(mathout) elif op == "*": m = in1*in2 worked = "y" mathout = str(m) print(mathout) elif op == "/": m = in1/in2 worked = "y" mathout = str(m) print(mathout) ``` My terminal doesn't return any errors, it just doesn't run the lines where you assign the variables in1, in2, and op. I really just need to know how to pull lines from the list made by split(). Please keep in mind that I'm still learning Python. Thank you!
2021/10/26
[ "https://Stackoverflow.com/questions/69727847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17245368/" ]
Use `perl=TRUE` with [lookaround](https://www.regular-expressions.info/lookaround.html): ```r vec <- c("2 - 5-< 2", "6 - 10-< 2", "6 - 10-2 - 5", "> 15-2 - 5") strsplit(vec, "(?<! )-(?!= )", perl=TRUE) # [[1]] # [1] "2 - 5" "< 2" # [[2]] # [1] "6 - 10" "< 2" # [[3]] # [1] "6 - 10" "2 - 5" # [[4]] # [1] "> 15" "2 - 5" ```
29,043,922
I have an image in an HTML email template where the height is being cutoff. I'm using the Zurb Ink email framework. The setup is two images that are supposed to stack on top of each other. From what I can tell the image is being cutoff at 19px in height, while it's actual height is 47px; I'm using Email on Acid to preview the email. The CSS is being inlined before the email is sent using `premailer`. The 2nd image displays fine. Here's the relevant code and screenshots. **HTML** ``` <table class="row banner"> <tr> <td class="wrapper last"> <table class="four columns"> <tr> <td> <img class="hide-for-small" src="url-to-image.jpg" width="179" height="47" style="width:179px; height:47px; line-height:47px;" /> <br/> <img src="url-to-image.jpg" width="179" height="63" style="width:179px; height:63px; line-height:63px;" /> </td> <td class="expander"></td> </tr> </table> </td> </tr> </table> ``` **CSS** ``` img { outline:none; text-decoration:none; -ms-interpolation-mode: bicubic; width: auto; max-width: 100%; float: left; clear: both; display: block; } ``` **Inlined CSS** - after all the CSS is compiled and inlined. ``` td { word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; vertical-align: top; text-align: left; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 13px; margin: 0; padding: 0px 0px 10px; } img { width: 179px; height: 47px; line-height: 47px; outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; max-width: 100%; float: left; clear: both; display: block; ``` **Screenshots** Outlook 2007/2010 ![enter image description here](https://i.stack.imgur.com/VEIpp.jpg) Normal Email Clients ![enter image description here](https://i.stack.imgur.com/Yp8dq.png) I've tried adding `height`, `style="height"` and `line-height` attributes to force the height but to no luck so far.
2015/03/14
[ "https://Stackoverflow.com/questions/29043922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438581/" ]
Try setting `mso-line-height-rule: at-least` on the TD that the image sits in. I've found issues with MSO email clients where it would crop images to the line-height unless this option is set correctly.
5,988,673
iam developing WPF product. I want to protect my .net source code from reverse enginering Please advice me
2011/05/13
[ "https://Stackoverflow.com/questions/5988673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/714681/" ]
You would use an obfuscator. There are a lot of them on the market, just google. For example, Visual Studio used to ship with the [Dotfuscator Community Edition](http://www.preemptive.com/products/dotfuscator). I never used it, so I can't say anything about its quality. This blog post shows the possible ways to try to prevent reverse engineering: <http://blogs.msdn.com/b/ericgu/archive/2004/02/24/79236.aspx>
48,727,346
Due to some odd reason, I cannot go with JPA vendor like Hibernate, etc and **I must use MyBatis.** Is there any implementation where we can enrich similar facility of CRUD operation in Mybatis? (Like GenericDAO save, persist, merge, etc) I have managed to come up with single interface implementation of CRUD type of operations (like Generic DAO) but still each table has to write it's own query in XML file (as table name, column names are different). Will that make sense to come up with generic implementation? Where I can give any table object for any CRUD operation through only 4 XML queries. (insert, update, read, delete) passing arguments of table name, column names, column values..etc. Does it look like re-inventing the wheel in MyBatis or does MyBatis has some similar support?
2018/02/11
[ "https://Stackoverflow.com/questions/48727346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1640241/" ]
The idea is still the same. Just that you will be looking for a specific attribute in the class object. For your card class, you could do something like this: ``` hand = [ Card(10, 'H'), Card(2,'h'), Card(12,'h'), Card(13, 'h'), Card(14, 'h') ] ``` Then you could do ``` sorted_cards = sorted(hand, key=lambda x: x.rank) ``` The output looks something like this: ``` >>> [card.number for card in sorted_cards] [2, 10, 12, 13, 14] ```
411,810
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., ``` model = django.authx.models.User ``` Without Django returning the error: ``` "global name django is not defined." ```
2009/01/04
[ "https://Stackoverflow.com/questions/411810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44440/" ]
I think you're looking for this: ``` from django.db.models.loading import get_model model = get_model('app_name', 'model_name') ``` There are other methods, of course, but this is the way I'd handle it if you don't know what models file you need to import into your namespace. (Note there's really no way to safely get a model without first knowing what app it belongs to. Look at the source code to loading.py if you want to test your luck at iterating over all the apps' models.) **Update for Django 1.7+:** According to Django's [deprecation timeline](https://docs.djangoproject.com/en/dev/internals/deprecation/#deprecation-removed-in-1-9), `django.db.models.loading` has been deprecated in Django 1.7 and will be removed in Django 1.9. As pointed out in [Alasdair's answer](https://stackoverflow.com/a/28380435/996114), In Django 1.7+, there is an [applications registry](https://docs.djangoproject.com/en/1.8/ref/applications/#module-django.apps). You can use the [`apps.get_model`](https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.apps.get_model) method to dynamically get a model: ``` from django.apps import apps MyModel = apps.get_model('app_label', 'MyModel') ```
4,297,503
In continuation to my question asked [here](https://stackoverflow.com/questions/4212105/how-to-get-and-display-the-list-of-youtube-videos-using-javascript), i have created a test app to check the json parsing using jquery. It doesnt seem to work. I can append data in the click function. However getting data from that url and parsing seems to fail. Can someone provide some useful hints? ``` <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("body").append("<div id = 'data'><ul>jffnfjnkj</ul></div>"); $.getJSON("http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?callback=function&alt=jsonc&v=2", function(data) { var dataContainer = $("#data ul"); $.each(data.data.items, function(i, val) { $("body").append("<div id = 'data'><ul>jffnfjnkj</ul></div>"); if (typeof(val.player) !== 'undefined' && typeof(val.title) !== 'undefined') { dataContainer.append("<li><a href = "+val.player.default+" target = '_blank'>"+val.title+"</a></li>"); } }); }); }); }); </script> </head> <body> <h2>Header</h2> <p>Paragrapgh</p> <p>Paragraph.</p> <button>Click me</button> </body> </html> ``` TIA, Praveen S
2010/11/28
[ "https://Stackoverflow.com/questions/4297503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372026/" ]
The callback is provided so that you can bypass the same origin policy. Thus retrieved JSON data is enclosed within the function name and cannot be parsed directly. Details of doing this with jquery are given [here](http://api.jquery.com/jQuery.ajax/). Please refer the example given below ``` <script> $.ajax({ url:'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?alt=jsonc&v=2&callback=?', dataType: "jsonp", timeout: 5000, success: function(data){ alert(data.apiVersion); //add your JSON parsing code here } }); </script> ``` Please find the working example [here](http://tallymobile.com/test7.html).
43,066,698
I'm studying UWP by Windows 10 development for absolute beginners, and I meet some problems. Reflash my ObservableCollection<> data will cause the screen to flash. How do I fix it? The program details are in [UWP beginner](https://channel9.msdn.com/Series/Windows-10-development-for-absolute-beginners/UWP-044-Adeptly-Adaptive-Challenge) ``` //CS FILE CODE public sealed partial class FinancialPage : Page { ObservableCollection<NewsItem> NewsItems; public FinancialPage() { NewsItems = new ObservableCollection<NewsItem>(); this.InitializeComponent(); GetNewsItemManager.GetNewItemsByCategory(NewsItems, "Financial"); } } // XAML FILE CODE <GridView ItemsSource="{x:Bind NewsItems}" Background="LightGray"> <GridView.ItemTemplate> <DataTemplate x:DataType="data:NewsItem"> <local:NewsContentControl HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/> </DataTemplate> </GridView.ItemTemplate> </GridView> //MODELS NEWSITEMS CLASS FILE public static void GetNewItemsByCategory(ObservableCollection<NewsItem> NewsItems, string Category) { var allnewsitems = getNewsItems(); var filteredNewsItems = allnewsitems.Where(p => p.Category == Category && IsExist(NewsItems, p.Id)).ToList(); filteredNewsItems.ForEach(p => NewsItems.Add(p)); } private static Boolean IsExist(ObservableCollection<NewsItem> NewsItems, int Id) { return NewsItems.ToList().TrueForAll(p => Id == p.Id); } private static List<NewsItem> getNewsItems() { var items = new List<NewsItem>(); items.Add(new NewsItem() { Id = 1, Category = "Financial", Headline = "Lorem Ipsum", Subhead = "doro sit amet", DateLine = "Nunc tristique nec", Image = "Assets/Financial1.png" }); items.Add(new NewsItem() { Id = 2, Category = "Financial", Headline = "Etiam ac felis viverra", Subhead = "vulputate nisl ac, aliquet nisi", DateLine = "tortor porttitor, eu fermentum ante congue", Image = "Assets/Financial2.png" }); items.Add(new NewsItem() { Id = 3, Category = "Financial", Headline = "Integer sed turpis erat", Subhead = "Sed quis hendrerit lorem, quis interdum dolor", DateLine = "in viverra metus facilisis sed", Image = "Assets/Financial3.png" }); items.Add(new NewsItem() { Id = 4, Category = "Financial", Headline = "Proin sem neque", Subhead = "aliquet quis ipsum tincidunt", DateLine = "Integer eleifend", Image = "Assets/Financial4.png" }); items.Add(new NewsItem() { Id = 5, Category = "Financial", Headline = "Mauris bibendum non leo vitae tempor", Subhead = "In nisl tortor, eleifend sed ipsum eget", DateLine = "Curabitur dictum augue vitae elementum ultrices", Image = "Assets/Financial5.png" }); items.Add(new NewsItem() { Id = 6, Category = "Food", Headline = "Lorem ipsum", Subhead = "dolor sit amet", DateLine = "Nunc tristique nec", Image = "Assets/Food1.png" }); items.Add(new NewsItem() { Id = 7, Category = "Food", Headline = "Etiam ac felis viverra", Subhead = "vulputate nisl ac, aliquet nisi", DateLine = "tortor porttitor, eu fermentum ante congue", Image = "Assets/Food2.png" }); items.Add(new NewsItem() { Id = 8, Category = "Food", Headline = "Integer sed turpis erat", Subhead = "Sed quis hendrerit lorem, quis interdum dolor", DateLine = "in viverra metus facilisis sed", Image = "Assets/Food3.png" }); items.Add(new NewsItem() { Id = 9, Category = "Food", Headline = "Proin sem neque", Subhead = "aliquet quis ipsum tincidunt", DateLine = "Integer eleifend", Image = "Assets/Food4.png" }); items.Add(new NewsItem() { Id = 10, Category = "Food", Headline = "Mauris bibendum non leo vitae tempor", Subhead = "In nisl tortor, eleifend sed ipsum eget", DateLine = "Curabitur dictum augue vitae elementum ultrices", Image = "Assets/Food5.png" }); return items; } ```
2017/03/28
[ "https://Stackoverflow.com/questions/43066698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7439395/" ]
Assuming ``` NewsItem.Clear(); filteredNewsItems.ForEach(p => NewsItem.Add(p)); ``` should be ``` NewsItems.Clear(); filteredNewsItems.ForEach(p => NewsItems.Add(p)); ``` I assume the "flash" you are seeing (can't be certain as you haven't provided a full repro) is due to what you're doing to show the updated list. Yes, removing everything and then adding a new (mostly similar) list back can create what some people describe as a "flash". A better approach would be to remove the items you don't want displayed any more and then add in any extra ones you do. Something like this: ``` foreach (var newsItem in NewsItems.Reverse()) { if (newsItem.Category != Category) { NewsItems.Remove(newsItem); } } foreach (var fni in filteredNewsItems) { if (!NewsItems.Contains(fni)) { NewsItems.Add(fni); } } ```
128,817
I am new to Ubuntu, and I have just installed Ubuntu 12.04 on a computer. I am using an automatic proxy server. When I select a software package to install and input my password, the progress icon displays for a few seconds, and then it stops. I tried to install different programs, and I always had the same problem. I can browse the web with Firefox, so I know I have a network connection. I do not see any errors or anything. What should I do?
2012/04/30
[ "https://askubuntu.com/questions/128817", "https://askubuntu.com", "https://askubuntu.com/users/58882/" ]
Here is a work around. Once you find a game you want to install, you can search for it in the terminal with (for example \*\* Super Tux): ``` apt-cache search Super Tux ``` Then you can install one of the names it displays by for example: ``` sudo apt-get install supertux ``` If you want to install a game from *dotdeb.com* for instance, you can open the terminal and type: ``` sudo dpkg -i ``` Make sure to leave a `Space` **after** the `-i` and then drag-and-drop the deb file you downloaded onto the terminal and press `Enter`.
233,097
The Premise =========== * An earth-like world (gravity, 1 moon, distance from star) * Oceans do not touch the ground (ignoring the how for this premise, but for consistency we'll say it's floating atop **1 km** of air) * Oceans still in contact with shorelines (allowed to touch ground starting a maximum of 1km from shore) ### What the question is *NOT* * How ocean life would be affected * What destruction would be caused to the atmosphere * Feasibility of the premise The Question ------------ Given that an ocean didn't touch the ground outside of a 1km continental shelf allowance, how would natural ocean phenomena such as waves change? #### Clarifications I haven't been able to get on since posting the question, so I'll give some clarifications here: * The illustration below shows what I was trying to say: the water can only sit on top of land within 1 km of a continent, everywhere else has ~ 1 km of air between the water and ground [![MS Paint example](https://i.stack.imgur.com/nz9QZ.png)](https://i.stack.imgur.com/nz9QZ.png) * For the purposes of this premise, we can assume that the air being contained by the water bodies is air that is either more dense or less buoyant than the water atop it. * We can assume there is very little, if any, air flow getting below the water bodies from above them. * **I care less about the way the waves react upon reaching the shelf, and more about how they change (if they change at all) out on the open waters** **Disclaimer** If you notice anything wrong with my post, I'm still learning, and am always open to suggestions for improvement!
2022/07/22
[ "https://worldbuilding.stackexchange.com/questions/233097", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/97249/" ]
It wouldn't change much ======================= Your scenario is roughly equivalent to "There's a huge, 1 km deep, pocket of air at the bottom of the ocean, and all the ground below the continental shelf is dry" Waves on the ocean are mostly governed by surface effects, so what is happening deep below the surface will be largely unaffected. That isn't to say that if this change happened abruptly that there wouldn't be some big changes in the ocean, but after things settled down, the waves and the ocean would settle down and a new normal would be established.
1,415,973
I am trying to secure my PHP Image upload script and the last hurdle I have to jump is making it so that users cannot directly excecute the images, but the server can still serve them in web pages. I tried changing ownership and permissions of the folders to no avail, so I am trying to store the images above public\_html and display them in pages that are stored in public\_html. My File Structure: ``` - userimages image.jpg image2.jpg - public_html filetoserveimage.html ``` I tried linking to an image in the userimages folder like this: ``` <img src="../userimages/image.jpg"> ``` But it does not work. Is there something I am missing here? If you have any better suggestions please let me know. I am trying to keep public users from executing potentially dangerous files they may have uploaded. Just as an extra security measure. Thanks!
2009/09/12
[ "https://Stackoverflow.com/questions/1415973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84292/" ]
You want something that's basically impossible. The way a browser loads a page (in a very basic sense) is this: Step 1: Download the page. Step 2: Parse the page. Step 3: Download anything referenced in the content of the page (images, stylesheets, javascripts, etc) Each "Download" event is atomic. It seems like you want to only serve images to people who have just downloaded a page that references those images. As PHP Jedi illustrated, you can pass the files through PHP. You could expand on his code, and check the HTTP\_REFERER on the request to ensure that people aren't grabbing "just" the image. Now, serving every image through a PHP passthru script is not efficient, but it could work. The most common reason people want to do this is to avoid "hotlinking" -- when people create image tags on other sites that reference the image on your server. When they do that, you expend resources handling requests that get presented on someone else's page. If that's what you're really trying to avoid, you can use mod\_rewrite to check the referer. A decent-looking discussion of hotlinking/anti-hotlinking can be found [here](http://www.dagondesign.com/articles/hotlink-protection-with-htaccess/)
15,105,461
In my application, I want to open device default calendar using code/programatically. I am using this code : ``` private void viewAllCalender() { // TODO Auto-generated method stub Intent i = new Intent(); if(Build.VERSION.SDK_INT >= 8 && Build.VERSION.SDK_INT <= 14){ i.setClassName("com.android.calendar","com.android.calendar.LaunchActivity"); }else if(Build.VERSION.SDK_INT >= 15){ i.setClassName("com.google.android.calendar", "com.android.calendar.LaunchActivity"); }else{ i.setClassName("com.android.calendar","com.android.calendar.LaunchActivity"); } startActivity(i); } ``` **IT IS WORKING FOR ALL THE DEVICES BUT IT IS NOT WORKING IN SAMSUNG S3 - (BUILD SDK VERSION - 17)** Please help me to figure out what the problem is?? Thanks
2013/02/27
[ "https://Stackoverflow.com/questions/15105461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1114329/" ]
You gotta realise that you can't expect an Android device to have a certain application. Not even the play app can be expected to be installed. The correct way of doing this is simply not using .setClassName and then let the user decide what to do. There is a dozen different calendar apps and the phone manufactures each have their own... **Edit** If you want to add an event to calendar you could use my CalendarOrganizer which handles a lot of these issues: ``` public class CalendarOrganizer { private final static int ICE_CREAM_BUILD_ID = 14; /** * Creates a calendar intent going from startTime to endTime * @param startTime * @param endTime * @param context * @return true if the intent can be handled and was started, * false if the intent can't be handled */ public static boolean createEvent(long startTime, long endTime, String title, String description, String location, boolean isAllDay, Context context) { Intent intent = new Intent(Intent.ACTION_EDIT); int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < ICE_CREAM_BUILD_ID) { // all SDK below ice cream sandwich intent.setType("vnd.android.cursor.item/event"); intent.putExtra("beginTime", startTime); intent.putExtra("endTime", endTime); intent.putExtra("title", title); intent.putExtra("description", description); intent.putExtra("eventLocation", location); intent.putExtra("allDay", isAllDay); // intent.putExtra("rrule", "FREQ=YEARLY"); } else { // ice cream sandwich and above intent.setType("vnd.android.cursor.item/event"); intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime); intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime); intent.putExtra(Events.TITLE, title); intent.putExtra(Events.ACCESS_LEVEL, Events.ACCESS_PRIVATE); intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY , isAllDay); intent.putExtra(Events.DESCRIPTION, description); intent.putExtra(Events.EVENT_LOCATION, location); // intent.putExtra(Events.RRULE, "FREQ=DAILY;COUNT=10") } try { context.startActivity(intent); return true; } catch(Exception e) { return false; } } } ```
6,090,160
Let's say I started Linux process, in the background. It is not a daemon, just a utility. If it gets SIGHUP, it would be killed. I did not take the "nohup" precaution. It is taking already much longer time than I thought. After 4 hours of running, ssh session might get disconnected. But I don't want to lose the process. I want to prevent it being killed by SIGHUP. Is it possible to make the equivalent of ``` signal(SIGHUP, SIG_IGN); ``` to this process without restarting it ? Thanks
2011/05/22
[ "https://Stackoverflow.com/questions/6090160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/564524/" ]
Use `disown(1)` > > disown: disown [-h] [-ar] [jobspec > ...] > Remove jobs from current shell. > > > > ``` > Removes each JOBSPEC argument from the table of active jobs. Without > any JOBSPECs, the shell uses its notion of the current job. > > Options: > -a remove all jobs if JOBSPEC is not supplied > -h mark each JOBSPEC so that SIGHUP is not sent to the job if > the shell receives a SIGHUP > -r remove only running jobs > > ``` > > [Detaching a process from terminal, entirely](https://superuser.com/questions/178587/detaching-a-process-from-terminal-entirely/178592#178592) > > "disown" is a bash builtin that > removes a shell job from the shell's > job list. What this basically means is > that you can't use "fg", "bg" on it > anymore, but more importantly, when > you close your shell it won't hang or > send a SIGHUP to that child anymore. > Unlike "nohup", "disown" is used after > the process has been launched and > backgrounded. > > >
48,155,799
I am trying to calculate the average number participants scored correct on a memory task. I have a column called `RecallType` which tells me if participants were assessed through forward memory recall (called `forwards`) or through backwards memory recall (called `backwards`). I also have a column called `ProbeState` which identifies the type of memory task, of which there are two. In this column I have `positions` and `digits`. These are all my variables of interest. The memory task itself is split by two columns. `Recall.CRESP` is a column specifying the correct answers on a memory test selected through grid coordinates. `Recall.RESP` shows participants response. These columns look something like this: ``` |Recall.CRESP | Recall.RESP | |---------------------------------|---------------------------------| |grid35grid51grid12grid43grid54 | grid35grid51grid12grid43grid54 | |grid11gird42gird22grid51grid32 | grid11gird15gird55grid42grid32 | ``` So for example in row 1 of this table, the participant got 5/5 correct as the grid coordinates of `Recall.CRESP` matches with `Recall.RESP`. However in row 2, the participant only got 2/5 correct as only the first and the last grid coordinate are identical. The order of the coordinates must match to be correct. Ideally I would love to learn from any response. If you do reply please kindly put some comments. Thanks.
2018/01/08
[ "https://Stackoverflow.com/questions/48155799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8137074/" ]
THe problem is that you have a non virtual `foo()` so that `A::bar()` will call the only `foo()` it knows, being `A::foo()`, even if it's B that invokes it. Try: ``` class A { public: A() { foo(); } virtual ~A() { foo(); } // <<---------- recommendation virtual void foo() { cout << 3; } // <<<--------- solves it void bar() { foo(); } }; class B : public A { void foo() override { cout << 2; } // <<---------- recommendation }; ``` **Additional infos:** Making `foo()` [virtual](https://www.geeksforgeeks.org/virtual-function-cpp/) in the base class allows each class to override this function, and be sure that the `foo()` that is invoked is will be the `foo()` corresponding to the object's real class. It's a [good practice](https://stackoverflow.com/q/497630/3723423) then to use the keyword `override` in the derived classes: it's not mandatory, but in case you make a typo in the functions signature, you'll immediately notice with a compile-time error message. Another good practice is to make your base class destructor virtual if you have at least one virtual function in the class. A final remark: in B, `foo()`'s private. This is legal, but it's weird because the inheritance says that B is a kind of A, but you can't use B objects exactly as an A object.
32,739,725
I have a list of users and when I click on a list item I would like a sub section to slide down from beneath it. I'm fine with the animation and this isn't the area I need help on. My problem is that when I click on any list item, all drop-down sections appear underneath all list items. So my approach now is to use the `id` of each user to create a unique `ng-show`. Then when I click on a list item a function is called: ``` <ul id="users" ng-repeat="user in users"> <li ng-click="showUserDetail(user.id)"> {{user.name}} <div class="slide" ng-show="dropDownSection_{{user.id}}"> //Stuff will go here </div> </li> </ul> ``` The `showUserDetail` function is: ``` $scope.showUserDetail = function(id) { //not sure I can do this? var section = "dropDownSection" + "_" + id; $scope.section = true; //this would normally show the animation } ``` but this doesn't work - the dropdown doesn't appear. Is there a nice "Angular" way of achieving something like this?
2015/09/23
[ "https://Stackoverflow.com/questions/32739725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003632/" ]
what you can do is.. set the id to show on ng-click and check that id in ng-show `ng-click="idToDisplay = user.id"` and `ng-show="idToDisplay == user.id"`
16,864,635
How can I animate an MKMapView to certain lat and lng? I have a map that is displayed when the user opens the app. When a user clicks a certain button I want the map to move to a specificc lat/lng. Is there not an animateTo(CLLocation) method?
2013/05/31
[ "https://Stackoverflow.com/questions/16864635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/307428/" ]
This will animate to roughly the center of continental US: ``` MKCoordinateRegion region = mapView.region; region.center.latitude = 39.833333; region.center.longitude = -98.58333; region.span.latitudeDelta = 60; region.span.longitudeDelta = 60; [mapView setRegion:region animated:YES]; ``` set your "center" to your latitude/longitude coordinates, choose an appropriate span, and let setRegion to its thing.
15,259,830
I am attempting to write a method that will output the content (i.e. HTML) for any renderings that happen to exist within a specific placeholder. The goal is to pass in a `Sitecore.Data.Items.Item` and the placeholder key that i'm interested in, and the method should return the rendered content. The issue with this seems to be that there is no page context established, and therefore calling `RenderControl()` is throwing a null reference error in the `GetCacheKey()` method of the Sublayout. Is anyone aware of a way to render a Sublayout or XSLT rendering programmatically? Here's what I've got so far: ``` private string GetPlaceholderContent(Item item, string placeHolder) { StringWriter sw = new StringWriter(); using (HtmlTextWriter writer = new HtmlTextWriter(sw)) { foreach (RenderingReference renderingReference in item.Visualization.GetRenderings(Sitecore.Context.Device, false)) { if (renderingReference.Placeholder == placeHolder) { // This ensures we're only dealing with Sublayouts if (renderingReference.RenderingItem.InnerItem.IsOfType(Sitecore.TemplateIDs.Sublayout)) { var control = renderingReference.GetControl(); control.RenderControl(writer); // Throws null reference error in GetCacheKey() } } } } return sw.ToString(); } ```
2013/03/06
[ "https://Stackoverflow.com/questions/15259830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/185749/" ]
It is almost 8 years since the question was originally asked, and it turn to be [Uniform](https://uniform.dev/uniform-for-sitecore) - rendering any item/placeholder fragment! Yes, it cuts the item you supply into placeholders/renderings: [![enter image description here](https://i.stack.imgur.com/E5lCO.jpg)](https://i.stack.imgur.com/E5lCO.jpg) The next step is to produce markup (for every possible data source out there): [![enter image description here](https://i.stack.imgur.com/6SJ4v.png)](https://i.stack.imgur.com/6SJ4v.png) That content is published into CDN and browser picks which version to load = personalization works! In other words, the question you've asked turned into a cutting-edge product that **can do so much more** on top of that! You could reverse-engineer the Uniform assemblies to see how they actually do that ;)
43,181,597
I'm working on a magento project with a plugin changes the `onclick` attribute on the `(document).ready()`. I tried to access this attribute using jquery to update it after a user action but it returns `undefined`. And I've noticed that the onclick attribute is NOT visible in the inspector but visible in the page source accessed by `view page source`or`Ctrl + u`. in inspector the targeted button looks like ``` <button type="button" id="addtocart_btn_5" title="Add to cart" class="button btn-cart btn-cart-with-qty"> <span>Add to cart<span> </button> ``` in the page source view it looks like: ``` <button type="button" id="addtocart_btn_5" title="Add to cart" class="button btn-cart btn-cart-with-qty" onclick="setLocation('http://mysite.local/eg_ar/checkout/cart/add/uenc/aHR0cDovL2hhaXJidXJzdGFyYWJpYS5sb2NhbC9lZ19hci8,/product/5/form_key/lqUtnptjQU7Cn7E1/qty/1/')"> <span>Add to cart</span> </button> ``` this button is correctly accessed via the variable `btn` and when i use `console.log(btn.attr("onclick"));` it returns `undefined` but with attribute like `id` it returns the id correctly. **NOTE**: the button is working very well. but I can't edit it. **Update**: as per @Saptal question I've to show more code. in the html part I've this block ``` <div class="add-to-cart"> <form id="product_addtocart_form_15"> <span class="custom-counter"> <input min="1" name="qty" id="qty" maxlength="2" value="1" title="qty" class="qty qty-updating" type="number"><div class="custom-counter-nav"><div class="custom-counter-button custom-counter-up">+</div><div class="custom-counter-button custom-counter-down">-</div></div> </span> <button type="button" id="addtocart_btn_15" title="Add to cart" class="button btn-cart btn-cart-with-qty"><span>Add to cart</span></button> </form> </div> ``` and in js I do that ``` <script> jQuery('.qty-updating').each(function(){ var qty = jQuery(this); qty.on('change', function(e){ alert('here'); var btn = qty.parent().siblings('.btn-cart'); console.log(btn.attr("onclick")); }); }); </script> ``` thanks in advance
2017/04/03
[ "https://Stackoverflow.com/questions/43181597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290292/" ]
click event is binded to the button and the onclick attribute isn't set explicitly as a html attribute on the button so, ``` btn.attr('onclick') ``` will return **undefined** and to solve this problem you need to off (unbind) the current click event and on (bind) the new click event as following: ``` btn.off('click'); btn.on('click', function() { yourFunction(); }); ``` hope this helps :)
34,249,401
I was trying to store a json string in local storage and retrieving the value in another function but its not working as expected For storing ``` var data = '{"history":['+'{"keyword":"'+key+'","msg":"'+msg+'","ver":"'+ver+'"}]}'; localStorage.setItem("history",JSON.stringify(data)); ``` For retriving ``` var historydata = JSON.parse(localStorage.getItem("history")); ``` tried to use the historydata.length and its showing 57 (its considering json array as a single string and showing its length ) I want the array size
2015/12/13
[ "https://Stackoverflow.com/questions/34249401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066325/" ]
The variable you are trying to store is already a json encoded string. You can not `stringify` it again. You can drop those `'` and reformat the json, then it would be a normal json, then you can call `stringify` on it. ``` var data = {"history":[{"keyword":key,"msg":msg,"ver":ver}]}; localStorage.setItem("history", JSON.stringify(data)); ``` To get the length of the array after retrieve: ``` var historydata = JSON.parse(localStorage.getItem("history")); console.log(historydata.history.length); ```
29,067,083
I already have this line for Linux box. ``` find . -type f -name '*.txt' -exec ls -l {} \; ``` It's getting all the TXT files in directory. But what I can't do and what I want to do is, to read all the .txt files on subfolder in one directory. For example : ParentTxtFolder --> ChildTxtFolder --> Txtfolder1, Txtfolder2, Txtfolder3. Per one Txtfolder it contains .txt files. So what I want is, to scan Txtfolder1 and count .txtfiles. If this output is possible, Expected output : ``` Txtfolder1 - 14 Txtfolder2 - 10 Txtfolder3 - 18 ``` I'm really stuck on this one. Thanks in advance!
2015/03/15
[ "https://Stackoverflow.com/questions/29067083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4472008/" ]
In your shiro.ini set a web session manager and set that into your security manager. See that helps. ``` sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager securityManager.sessionManager = $sessionManager ```
14,095,281
The idea in the following code is to have a bunch of "wanderer" objects that slowly "paint" an image onto a canvas. The problem is, that this code only seems to working on square images (in the code, the square image is identified as "hidden" (because it is unveiled by the "painters") and it is loaded in from the file called "UncoverTest.png"), not rectangular ones, which is mysterious to me. I get a segmentation fault error when trying to work with anything but a square. As far as I can tell, the segmentation fault error emerges when I enter the loop to iterate through the vector of type Agent (at the line `for (vector<Agent>::iterator iter = agents.begin(); iter != agents.end();++iter)`). ``` #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <vector> using namespace std; using namespace cv; //#define WINDOW_SIZE 500 #define STEP_SIZE 10.0 #define NUM_AGENTS 100 /********************/ /* Agent class definition and class prototypes */ /********************/ class Agent { public: Agent(); int * GetLocation(void); void Move(void); void Draw(Mat image); int * GetSize(void); private: double UnifRand(void); int * location; int * GetReveal(void); Mat hidden; }; int * Agent::GetSize(void) { int * size = new int[2]; size[0] = hidden.cols; size[1] = hidden.rows; return (size); } int * Agent::GetReveal(void) { int * BGR = new int[3]; location = GetLocation(); for (int i = 0; i < 3; i++) { BGR[i] = hidden.data[hidden.step[0]*location[0] + hidden.step[1]*location[1] + i]; } return (BGR); } void Agent::Draw(Mat image) { int * location = GetLocation(); int * color = GetReveal(); for (int i = 0;i < 3;i++) { image.data[image.step[0]*location[0] + image.step[1]*location[1] + i] = color[i]; } } void Agent::Move(void) { int dx = (int)(STEP_SIZE*UnifRand() - STEP_SIZE/2); int dy = (int)(STEP_SIZE*UnifRand() - STEP_SIZE/2); location[0] += (((location[0] + dx >= 0) & (location[0] + dx < hidden.cols)) ? dx : 0); location[1] += (((location[1] + dy >= 0) & (location[1] + dy < hidden.rows)) ? dy : 0); } Agent::Agent() { location = new int[2]; hidden = imread("UncoverTest.png",1); location[0] = (int)(UnifRand()*hidden.cols); location[1] = (int)(UnifRand()*hidden.rows); } double Agent::UnifRand(void) { return (rand()/(double(RAND_MAX))); } int * Agent::GetLocation(void) { return (location); } /********************/ /* Function prototypes unrelated to the Agent class */ /********************/ void DrawAgents(void); /********************/ /* Main function */ /********************/ int main(void) { DrawAgents(); return (0); } void DrawAgents(void) { vector<Agent> agents; int * size = new int[2]; Mat image; for (int i = 0; i < NUM_AGENTS; i++) { Agent * a = new Agent(); agents.push_back(* a); if (i == 0) { size = (* a).GetSize(); } } // cout << size[0] << " " << size[1] << endl; image = Mat::zeros(size[0],size[1],CV_8UC3); cvNamedWindow("Agent Example",CV_WINDOW_AUTOSIZE); cvMoveWindow("Agent Example",100,100); for (int stop = 1;stop != 27;stop = cvWaitKey(41)) { for (vector<Agent>::iterator iter = agents.begin(); iter != agents.end();++iter) { (* iter).Move(); (* iter).Draw(image); } imshow("Agent Example",image); } } ``` Can anyone explain to me how this error arises with square images only and how the problem might be fixed?
2012/12/30
[ "https://Stackoverflow.com/questions/14095281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1936768/" ]
You could do this programatically. XML is for static layouts. Excuse my pseudo Android: ``` private LinearLayout root; public void onCreate(Bundle b){ LinearLayout root = new LinearLayout(this); root.addChild(createGlucoseReadingView()); setContentView(root); } private View createGlucoseReadingView() { LinearLayout glucoseRoot = new LinearLayout(this); glucoseRoot.addChild(new TextView(this)); return glucoseRoot; } public void onPlusClick(View button){ root.addChild(createGlucoseReadingView()); } ``` Something along those lines, I've obviosuly left out formatting and adding the layout params to the views, but you get the idea.
71,453,541
I am trying to deploy my app on Heroku with node.js. App is running fine on my local but when I try to deploy it on Heroku it gives the following error: ``` 2022-03-13T00:12:16.474210+00:00 heroku[web.1]: Starting process with command `bin/boot` 2022-03-13T00:12:17.528943+00:00 app[web.1]: bash: bin/boot: No such file or directory 2022-03-13T00:12:17.679770+00:00 heroku[web.1]: Process exited with status 127 2022-03-13T00:12:17.738233+00:00 heroku[web.1]: State changed from starting to crashed 2022-03-13T00:13:07.280433+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sopra-fs22-gulec-egeonu-client.herokuapp.com request_id=73dc7825-de2b-4a24-bf3f-4d7bfe67ec60 fwd="213.55.224.62" dyno= connect= service= status=503 bytes= protocol=https 2022-03-13T00:13:07.460574+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sopra-fs22-gulec-egeonu-client.herokuapp.com request_id=d29010bf-9c0b-4e27-b902-9540d393f667 fwd="213.55.224.62" dyno= connect= service= status=503 bytes= protocol=https 2022-03-13T00:13:41.656858+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sopra-fs22-gulec-egeonu-client.herokuapp.com request_id=91ecbc00-ee15-4eed-bbfd-c3d3af522548 fwd="213.55.224.62" dyno= connect= service= status=503 bytes= protocol=https 2022-03-13T00:13:41.867824+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sopra-fs22-gulec-egeonu-client.herokuapp.com request_id=cfd378e9-ab85-46a3-b636-3e4fac1140ad fwd="213.55.224.62" dyno= connect= service= status=503 bytes= protocol=https ``` My Proficle is this: ``` web: bin/boot ``` and package.json ``` { "name": "sopra-fs22-client-template", "version": "0.1.0", "private": true, "dependencies": { "axios": "^0.24.0", "moment": "^2.29.1", "node-gyp": "^8.4.1", "node-sass": "^7.0.1", "react": "^17.0.2", "react-datetime-picker": "^3.5.0", "react-dom": "^17.0.2", "react-router-dom": "^5.3.0", "react-scripts": "^5.0.0", "styled-components": "^5.3.3" }, "scripts": { "dev": "react-scripts start", "start": "serve -s build", "build": "react-scripts build", "eject": "react-scripts eject", "test": "react-scripts test --env=jsdom", "heroku-postbuild": "npm run build" }, "eslintConfig": { "extends": "react-app" }, "browserslist": [ ">0.2%", "not dead", "not ie <= 11", "not op_mini all" ] } ``` I also checked the other posts and tried other things as well but I don't know where else to check thank you very much.
2022/03/13
[ "https://Stackoverflow.com/questions/71453541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17481832/" ]
I would recommend to switch from a web page that serves the sitemap when it's called, to a script that generates static XMLs and that you can optionally call via `crontab`. Step 1: Define directory where sitemaps are saved ------------------------------------------------- This will be used to write one static `xml` file for each sitemap, plus the sitemap index. The directory needs to be writable from the user running the script and accessible via web. ``` define('PATH_TO_SITEMAP', __DIR__.'/www/'); ``` Step 2: Define the public URL where the sitemaps will be reachable ------------------------------------------------------------------ This is the Web URL of the folder you defined above. ``` define('HTTP_TO_SITEMAP', 'https://yourwebsite.com/'); ``` Step 3: Write sitemaps to file ------------------------------ Instead of `echo` the Sitemap, write it to static xml files in the folder defined above. Furthermore keep a counter (`$count_urls` in my example below) for the number of URLs and when it reaches 50k reset the counter, close the sitemap and open a new one. Also, keep a counter of how many sitemaps you're creating (`$count_sitemaps` in my example below). Here's a working example that keeps your structure but writes the multiple files. It's not ideal, you should use a class/method or a function to write the sitemaps and avoid repeated code, but I thought this would be easier to understand as it keeps the same approach you had in your code. ``` $h = fopen(PATH_TO_SITEMAP.'sitemap_'.$count_sitemaps.'.xml', 'w+'); fwrite($h, '<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="'.PROTOCOL.'://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>'.SITE_HOST.'</loc> <priority>1.0</priority> </url> '); $count_urls = 0; foreach ($dataAll1 as $val) { $count_urls++; $data = json_decode(file_get_contents('cache-data/'.$val), 1); if ($val == 'index.php') { continue; } // When you reach 50k, close the sitemap, increase the counter and open a new sitemap if ($count_urls >= 50000) { fwrite($h, '</urlset>'); fclose($h); $count_sitemaps++; $h = fopen(PATH_TO_SITEMAP.'sitemap_'.$count_sitemaps.'.xml', 'w+'); fwrite($h, '<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="'.PROTOCOL.'://www.sitemaps.org/schemas/sitemap/0.9">'); $count_urls = 0; } fwrite($h, ' <url> <loc>'.SITE_HOST.'/job-detail/'.$data['jk'].'jktk'.$data['tk'].'-'.$service->slugify($data['title']).'</loc> <priority>0.9</priority> <changefreq>daily</changefreq> </url> '); } // Important! Close the final sitemap and save it. fwrite($h, '</urlset>'); fclose($h); ``` Step 4: Write SitemapIndex -------------------------- Finally you write a [sitemapindex](https://www.sitemaps.org/protocol.html#index) file that points to all the sitemaps you generated using the same `$count_sitemaps` counter. ``` // Build the SitemapIndex $h = fopen(PATH_TO_SITEMAP.'sitemap.xml', 'w+'); fwrite($h, '<?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'); for ($i = 1; $i <= $count_sitemaps; $i++) { fwrite($h, ' <sitemap> <loc>'.HTTP_TO_SITEMAP.'sitemap_'.$i.'.xml</loc> <lastmod>'.date('c').'</lastmod> </sitemap> '); } fwrite($h, ' </sitemapindex>'); fclose($h); ``` Step 5 (optional): ping Google ------------------------------ ``` file_get_contents('https://www.google.com/webmasters/tools/ping?sitemap='.urlencode(HTTP_TO_SITEMAP.'sitemap.xml')); ``` Conclusions ----------- As mentioned this approach is a bit messy and doesn't follow best practices on code re-use, but it should be quite clear on how to loop, store multiple sitemaps and finally build the sitemapindex file. For a better approach, I suggest you to look at this [open source Sitemap class](https://github.com/andreaolivato/Sitemap).
51,889,794
Here's my custom module stored in `util.py` that wrapps up 3-steps what I always gone-through to read images when using `tensorflow` ``` #tf_load_image from path def load_image(image_path, image_shape, clr_normalize = True ): '''returns tensor-array on given image path and image_shape [height, width]''' import tensorflow as tf image = tf.read_file(image_path) image = tf.image.decode_jpeg(image, channels=3) if clr_normalize == True: image = tf.image.resize_images(image, image_shape) / 127.5 - 1 else: image = tf.image.resize_images(image, image_shape) return image ``` But this is quite inefficient to deal with lots of image load since it generally calls `import tensorflow as tf` everytime I read "single image". I'd like to let this function to inherit `tf` command from the `main.py`'s tf where the load\_image actually imported into. Like.. ``` import tensor flow as tf from util import load_image image = load_image("path_string") #where load_image no longer wraps the import tensorflow as tf in itself. ```
2018/08/17
[ "https://Stackoverflow.com/questions/51889794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8889050/" ]
> > But this is quite inefficient (...) since it generally calls `import tensorflow as tf` everytime I read "single image". > > > imported modules are cached in `sys.modules` on first import (I mean "the very first time a module is imported in a given process"), subsequent calls will retrieve already imported modules from this cache, so the overhead is way less than you might think. But anyway: > > I'd like to let this function to inherit tf command from the main.py's tf where the load\_image actually imported into. > > > The only way would be to explicitely pass the module to your function, ie: ``` # utils.py def load_image(tf, ....): # code here using `tf` ``` and then ``` # main.py import tensorflow as tf from utils import load_image im = load_image(tf, ...) ``` BUT this is actually totally useless: all you have to do is, in utils.py, to move the import statement out of the function: ``` # utils.py import tensorflow as tf def load_image(image_path, image_shape, clr_normalize = True ): '''returns tensor-array on given image path and image_shape [height, width]''' import tensorflow as tf image = tf.read_file(image_path) image = tf.image.decode_jpeg(image, channels=3) if clr_normalize: image = tf.image.resize_images(image, image_shape) / 127.5 - 1 else: image = tf.image.resize_images(image, image_shape) return image ``` FWIW, [it IS officially recommanded to put all your imports at the top of the module](https://www.python.org/dev/peps/pep-0008/#imports), before any other definitions (functions, classes, whatever). Importing within a function should only be used as a Q&D last resort fix for circular imports (which are usually a sure sign you have a design issue and should actually be fixed by fixing the design itself).
21,769,489
I'm attempting create the following using HTML and CSS only. * Each rectangle is either `50px` by `100px` and `100px` by `50px`. * The RGB are `#ffffff`, `#cccccc`, `#999999`, `#666666`, `#333333`, order does not matter. * The border is `1px` in color `#000000`. * Place the product at the center of the page. What I have so far ``` <section id="main"> <div id="container"> <div class="horizontal" id="box1">1</div> <div class="vertical" id="box2">2</div> <div class="vertical" id="box3">3</div> <div class="horizontal" id="box4">4</div> </div> </section> ``` CSS ``` * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; } #container { background-color:#ff0000; height:153px; max-width:154px; } .horizontal { border:1px solid #000000; width:100px; height:50px; margin:0px; padding:0px; } .vertical { border:1px solid #000000; width:50px; height:100px; margin:0px; padding:0px; } #box1 { float:left; background-color:#ffffff; margin:0px; padding:0px; } #box2 { float:right; background-color:#cccccc; clear:right; margin:0px; padding:0px; } #box3 { float:left; background-color:#999999; margin:0px; padding:0px; clear:left; } #box4 { background-color:#666666; float:left; margin:0px; padding:0px; } ``` My issue lies within making this a exact square and the borders overlapping so they are only `1px`. also when I zoom out the bottom div is falling outside of the container. Anyone wanna give this a shot? **\* Like this \*** ``` ___________________________________ | | | | | | | | | |-----------------------| | | | | | | | | | | | | | | | | | | | | | | | | | | |_______________|_________| | | | | | | | | | ----------------------------------- ```
2014/02/14
[ "https://Stackoverflow.com/questions/21769489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Your borders push it out. Set the border to the container and leave the height and width at 150px, as it should be with rectangles of 100x50 in the layout you posted. Cleaned up the code. [**JSFiddle demonstration.**](http://jsfiddle.net/v8uR7/) ``` * { margin:0px auto; } #main { height:100%; width:100%; margin-top:20%; } #container { display: block; border: 1px solid #000; background-color:#ff0000; height:150px; width:150px; } .horizontal { width:100px; height:50px; } .vertical { width:50px; height:100px; } #box1 { background-color:#ffffff } #box2 { background-color:#cccccc; } #box3 { background-color:#999999; } #box4 { background-color:#666666 } #box1, #box3 { float: left; } #box2, #box4 { float: right; } ```
1,326,572
Let $X$ be a (possibly T1, that is, singleton subsets are closed) topological space. Suppose that there is a *proper* subset $D \subset X$ such that: * $D$ is dense in $X$; * $D$ is homeomorphic to $X$. What can be said about $X$?
2015/06/15
[ "https://math.stackexchange.com/questions/1326572", "https://math.stackexchange.com", "https://math.stackexchange.com/users/248346/" ]
$$32(x + 1) = y^2 \implies 32 \mid y^2 \implies 4 \mid y$$ so let $y = 4z$. $$2(x+1) = z^2 \implies 2 \mid z$$ so let $z = 2w$ $$x + 1 = 2w^2 $$ so given any $w$ we can solve for $x$. So the set of solutions is $$\{(2w^2 - 1, 8w) \mid w \in \Bbb Z\}$$
18,024,759
I want to prevent a ComboBox to resize acording to the size of the selected item. Consider this simplified example: ``` <Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="150" Width="300"> <GroupBox Header="Group Header" Margin="5"> <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <ComboBox MinWidth="100" Grid.Column="0" Margin="5" MaxWidth="150"/> <ComboBox Grid.Column="1" Margin="5" MinWidth="110"> <ComboBoxItem Content="Very loooooooooooooooooooooooooooooooooooooooong text"/> <ComboBoxItem Content="Normal text"/> </ComboBox> </Grid> </ScrollViewer> </GroupBox> </Window> ``` When you select the first item in the second ComboBox, that ComboBox is expanded so the whole content of the selected item fits, hiding the ComboBox from the left I would like to achieve three things: * Have the scrollviewer so the controls fit in their minimum size * If the Window is very large, I want the second ComboBox to fit the remaining size * If I select a very long item in the second ComboBox, I want it to preserve the size it had and **not** adjust to the contents of the selected item Is it possible?
2013/08/02
[ "https://Stackoverflow.com/questions/18024759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1094526/" ]
Edit: ----- I looked again at the problem and found out much simpler solution than previously proposed. The idea is to override MeasureOverride function of the ComboBox class and provide limited space that is available, where width is equal to the MinWidth property of the ComboBox. In order to do that we create ComboBox derived class: ``` public class MyComboBox : ComboBox { protected override Size MeasureOverride(Size constraint) { return base.MeasureOverride(new Size(MinWidth, constraint.Height)); } } ``` and then we use it in our control in place of ComboBox with HorizontalContentAlignment set to Stretch: ``` <local:MyComboBox Grid.Column="1" Margin="5" MinWidth="110" HorizontalContentAlignment="Stretch"> <ComboBoxItem Content="Very loooooooooooooooooooooooooooooooooooooooong text"/> <ComboBoxItem Content="Normal text"/> </local:MyComboBox> ``` Previously proposed, too complex solution: ------------------------------------------ You can bind the MaxWidth property of the second ComboBox to the space which is left (you can calculate it): ``` <Window x:Class="Example.MainWindow" xmlns:local="clr-namespace:Example" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="150" Width="300"> <Window.Resources> <local:SubstractConverter x:Key="SubstractConverter"/> </Window.Resources> <GroupBox Header="Group Header" Margin="5"> <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" x:Name="ScrollViewer1"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <ComboBox MinWidth="100" Grid.Column="0" Margin="5" MaxWidth="150" x:Name="ComboBox1"/> <ComboBox Grid.Column="1" Margin="5" MinWidth="110"> <ComboBox.MaxWidth> <MultiBinding Converter="{StaticResource SubstractConverter}"> <Binding ElementName="ScrollViewer1" Path="ActualWidth"/> <Binding ElementName="ComboBox1" Path="ActualWidth"/> <Binding ElementName="ComboBox1" Path="Margin.Left"/> <Binding ElementName="ComboBox1" Path="Margin.Right"/> <Binding Path="Margin.Left" RelativeSource="{RelativeSource Self}"/> <Binding Path="Margin.Right" RelativeSource="{RelativeSource Self}"/> </MultiBinding> </ComboBox.MaxWidth> <ComboBoxItem Content="Very loooooooooooooooooooooooooooooooooooooooong text"/> <ComboBoxItem Content="Normal text"/> </ComboBox> </Grid> </ScrollViewer> </GroupBox> </Window> ``` I'm substracting ActualWidth of the first combobox, its margins and margins of the second combobox from the ActualWidth of the scrollviewer. In order to have less elements to substract, you can put a border around ComboBox1. You will then substract border's ActualWidth instead of ComboBox1 properties. Converter which is used here: ``` public class SubstractConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { if (values != null && values.Any()) { var result = System.Convert.ToDouble(values.First()); var toSubstract = values.Skip(1); foreach (var number in toSubstract) { result -= System.Convert.ToDouble(number); } return result; } return 0d; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } ```
462,153
I have thermoelectric modules and set it in series, then I connected to a DC to DC step up (CN6009) to enhance the voltage. Then I connected to my phone with usb charger to try charge with it, but the voltage suddenly drops. Should I change the step up or increase the amount of the module?
2019/10/09
[ "https://electronics.stackexchange.com/questions/462153", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/233718/" ]
You've got a couple of things going on that are causing your problems: 1. The output resistance of [TEG modules](https://en.wikipedia.org/wiki/Thermoelectric_generator#Practical_limitations) is fairly high. They act like a battery with a big resistor in series. 2. By boosting the voltage, you increase the needed current. Say you need 5V at 1A to charge your phone, and your TEG can deliver 2.5V. Your TEG will have to provide 2.5V at 2A in order to deliver the 5 watts of power your charger needs. Those two combine to cause your voltage drop. 1. Voltage **always** drops when current flows through a resistor. The TEG doesn't have a seperate resistor in it. Its construction involves materials and connections that raise the electrical resistance. They **must** be made that way to work, it isn't an artificial limit. 2. You have the TEGs in series, so the internal resistance adds up. If you have, say, three TEGs in series then you have three times the resistance. 3. Boosting the voltage increases the current draw from the TEG, and makes the voltage drop worse. The problem boils down to your charger needing more power than the TEGs can provide. * You can try putting more TEGs in parallel. * You can try using a more efficient boost converter. * You could use larger TEGs. * You could put the TEGs in parallel and charge a low voltage battery, then charge your phone from the low voltage battery using a boost converter. That last solution means you charge a low voltage battery slowly with your TEGs. When that battery is fully charged, you use it with a boost converter to quickly charge your phone.
1,295,381
I'm trying to convert a **mkv** file and add a watermark logo to it, but I tried a bunch of different instructions but it is always missing the logo after 24 seconds of the video. Here's my code: ``` ffmpeg \ -i RTed83e104ac4d98c46383630d733a3282.mkv \ -i RT894ce44c6ba84eb98300566adae4e7bf.mka \ -i logo_white.png \ -filter_complex "[2] scale=120:18 [ovr1], [0:v][ovr1]overlay=10:452" \ output.mp4 ``` For example: <https://cl.ly/0F3K1K121E2W> you can see the image is gone after 24 seconds. What I'm doing wrong? **OUTPUT/LOGS**: ``` ffmpeg \ -i RTed83e104ac4d98c46383630d733a3282.mkv \ -i RT894ce44c6ba84eb98300566adae4e7bf.mka \ -i logo_white.png \ -filter_complex "[2] scale=120:18 [ovr1], [0:v][ovr1]overlay=10:452" \ output.mp4 ffmpeg version 3.4.1 Copyright (c) 2000-2017 the FFmpeg developers built with Apple LLVM version 9.0.0 (clang-900.0.39.2) configuration: --prefix=/usr/local/Cellar/ffmpeg/3.4.1 --enable-shared --enable-pthreads --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-gpl --enable-libmp3lame --enable-libx264 --enable-libxvid --enable-opencl --enable-videotoolbox --disable-lzma libavutil 55. 78.100 / 55. 78.100 libavcodec 57.107.100 / 57.107.100 libavformat 57. 83.100 / 57. 83.100 libavdevice 57. 10.100 / 57. 10.100 libavfilter 6.107.100 / 6.107.100 libavresample 3. 7. 0 / 3. 7. 0 libswscale 4. 8.100 / 4. 8.100 libswresample 2. 9.100 / 2. 9.100 libpostproc 54. 7.100 / 54. 7.100 Input #0, matroska,webm, from 'RTed83e104ac4d98c46383630d733a3282.mkv': Metadata: encoder : GStreamer matroskamux version 1.8.1.1 creation_time : 2018-02-13T18:16:31.000000Z Duration: 00:05:48.26, start: 1.456000, bitrate: 528 kb/s Stream #0:0(eng): Video: h264 (Constrained Baseline), yuv420p(progressive), 640x480, SAR 1:1 DAR 4:3, 30 fps, 30 tbr, 1k tbn, 2k tbc (default) Metadata: title : Video Input #1, matroska,webm, from 'RT894ce44c6ba84eb98300566adae4e7bf.mka': Metadata: encoder : GStreamer matroskamux version 1.8.1.1 creation_time : 2018-02-13T18:16:31.000000Z Duration: 00:05:47.78, start: 1.421000, bitrate: 45 kb/s Stream #1:0(eng): Audio: opus, 48000 Hz, stereo, fltp (default) Metadata: title : Audio Input #2, png_pipe, from 'logo_white.png': Duration: N/A, bitrate: N/A Stream #2:0: Video: png, rgba(pc), 600x90, 25 tbr, 25 tbn, 25 tbc Stream mapping: Stream #0:0 (h264) -> overlay:main (graph 0) Stream #2:0 (png) -> scale (graph 0) overlay (graph 0) -> Stream #0:0 (libx264) Stream #1:0 -> #0:1 (opus (native) -> aac (native)) Press [q] to stop, [?] for help [libx264 @ 0x7fc62308c400] using SAR=1/1 [libx264 @ 0x7fc62308c400] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 AVX2 LZCNT BMI2 [libx264 @ 0x7fc62308c400] profile High, level 3.0 [libx264 @ 0x7fc62308c400] 264 - core 148 r2795 aaa9aa8 - H.264/MPEG-4 AVC codec - Copyleft 2003-2017 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00 Output #0, mp4, to 'output.mp4': Metadata: encoder : Lavf57.83.100 Stream #0:0: Video: h264 (libx264) (avc1 / 0x31637661), yuv420p(progressive), 640x480 [SAR 1:1 DAR 4:3], q=-1--1, 30 fps, 15360 tbn, 30 tbc (default) Metadata: encoder : Lavc57.107.100 libx264 Side data: cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: -1 Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 128 kb/s (default) Metadata: title : Audio encoder : Lavc57.107.100 aac Past duration 0.609993 too large 0kB time=00:00:01.73 bitrate= 0.2kbits/s dup=7 drop=0 speed=3.43x Last message repeated 2 times frame=10449 fps=152 q=-1.0 Lsize= 11658kB time=00:05:48.20 bitrate= 274.3kbits/s dup=151 drop=0 speed=5.06x video:5860kB audio:5422kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 3.338063% [libx264 @ 0x7fc62308c400] frame I:42 Avg QP:13.16 size: 32061 [libx264 @ 0x7fc62308c400] frame P:2657 Avg QP:18.79 size: 1347 [libx264 @ 0x7fc62308c400] frame B:7750 Avg QP:22.91 size: 138 [libx264 @ 0x7fc62308c400] consecutive B-frames: 0.9% 0.5% 0.5% 98.1% [libx264 @ 0x7fc62308c400] mb I I16..4: 13.1% 64.6% 22.3% [libx264 @ 0x7fc62308c400] mb P I16..4: 0.3% 0.7% 0.1% P16..4: 10.4% 3.3% 1.7% 0.0% 0.0% skip:83.5% [libx264 @ 0x7fc62308c400] mb B I16..4: 0.0% 0.0% 0.0% B16..8: 8.0% 0.1% 0.0% direct: 0.0% skip:91.7% L0:41.7% L1:56.6% BI: 1.7% [libx264 @ 0x7fc62308c400] 8x8 transform intra:63.1% inter:64.4% [libx264 @ 0x7fc62308c400] coded y,uvDC,uvAC intra: 75.8% 77.6% 61.0% inter: 1.3% 2.0% 0.2% [libx264 @ 0x7fc62308c400] i16 v,h,dc,p: 17% 13% 37% 33% [libx264 @ 0x7fc62308c400] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 25% 17% 25% 5% 4% 4% 5% 6% 9% [libx264 @ 0x7fc62308c400] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 30% 18% 17% 8% 5% 5% 5% 5% 7% [libx264 @ 0x7fc62308c400] i8c dc,h,v,p: 57% 20% 18% 5% [libx264 @ 0x7fc62308c400] Weighted P-Frames: Y:0.0% UV:0.0% [libx264 @ 0x7fc62308c400] ref P L0: 65.0% 9.6% 16.7% 8.8% [libx264 @ 0x7fc62308c400] ref B L0: 85.7% 12.4% 1.9% [libx264 @ 0x7fc62308c400] ref B L1: 93.5% 6.5% [libx264 @ 0x7fc62308c400] kb/s:137.80 [aac @ 0x7fc623086600] Qavg: 5304.135 ```
2018/02/15
[ "https://superuser.com/questions/1295381", "https://superuser.com", "https://superuser.com/users/873164/" ]
WebRTC sourced inputs are often sloppy and may change parameters midstream resulting in surprises. In your case a lazy solution could be to loop the overlay image: ``` ffmpeg \ -i RTed83e104ac4d98c46383630d733a3282.mkv \ -i RT894ce44c6ba84eb98300566adae4e7bf.mka \ -loop 1 -i logo_white.png \ -filter_complex "[2] scale=120:18 [ovr1], [0:v][ovr1]overlay=10:452:shortest=1" \ output.mp4 ```
73,937,079
I have a table that contains this (HIght value, LOw value data according to a DatetTime): ``` mysql> select dt, hi, lo from mytable where dt >='2022-10-03 09:20:00' limit 20; +---------------------+--------+--------+ | dt | hi | lo | +---------------------+--------+--------+ | 2022-10-03 09:21:00 | 4.1200 | 4.1180 | | 2022-10-03 09:24:00 | 4.1080 | 4.1040 | | 2022-10-03 09:25:00 | 4.1040 | 4.1000 | | 2022-10-03 09:26:00 | 4.0960 | 4.0940 | | 2022-10-03 09:28:00 | 4.0940 | 4.0920 | | 2022-10-03 09:29:00 | 4.0980 | 4.0940 | | 2022-10-03 09:31:00 | 4.1020 | 4.0980 | | 2022-10-03 09:32:00 | 4.1000 | 4.1000 | | 2022-10-03 09:33:00 | 4.0940 | 4.0940 | | 2022-10-03 09:36:00 | 4.0720 | 4.0720 | | 2022-10-03 09:37:00 | 4.0600 | 4.0500 | | 2022-10-03 09:39:00 | 4.0620 | 4.0560 | | 2022-10-03 09:42:00 | 4.0660 | 4.0580 | | 2022-10-03 09:47:00 | 4.0620 | 4.0620 | | 2022-10-03 09:48:00 | 4.0620 | 4.0620 | | 2022-10-03 09:50:00 | 4.0580 | 4.0580 | | 2022-10-03 09:51:00 | 4.0580 | 4.0580 | | 2022-10-03 09:52:00 | 4.0560 | 4.0540 | | 2022-10-03 09:53:00 | 4.0460 | 4.0460 | | 2022-10-03 09:55:00 | 4.0420 | 4.0360 | +---------------------+--------+--------+ 20 rows in set (0,00 sec) ``` I want to obtain, in MySQL (because I'm learning a little), for each line the differance (rdif) between the 'hi' of the line and the 'lo' of 10 minutes ago. I get it like this: (I know, the 'as' are optional, but it helps to understand better) ``` mysql> select dt as rdt, hi as rhi, (select lo from mytable where dt = rdt-interval 10 minute) as rlo, (hi-(select rlo)) as rdif from mytable where dt >= '2022-10-03 09:20:00' limit 20; +---------------------+--------+--------+---------+ | rdt | rhi | rlo | rdif | +---------------------+--------+--------+---------+ | 2022-10-03 09:21:00 | 4.1200 | 3.9900 | 0.1300 | | 2022-10-03 09:24:00 | 4.1080 | 4.0180 | 0.0900 | | 2022-10-03 09:25:00 | 4.1040 | 4.0500 | 0.0540 | | 2022-10-03 09:26:00 | 4.0960 | 4.0800 | 0.0160 | | 2022-10-03 09:28:00 | 4.0940 | NULL | NULL | | 2022-10-03 09:29:00 | 4.0980 | NULL | NULL | | 2022-10-03 09:31:00 | 4.1020 | 4.1180 | -0.0160 | | 2022-10-03 09:32:00 | 4.1000 | NULL | NULL | | 2022-10-03 09:33:00 | 4.0940 | NULL | NULL | | 2022-10-03 09:36:00 | 4.0720 | 4.0940 | -0.0220 | | 2022-10-03 09:37:00 | 4.0600 | NULL | NULL | | 2022-10-03 09:39:00 | 4.0620 | 4.0940 | -0.0320 | | 2022-10-03 09:42:00 | 4.0660 | 4.1000 | -0.0340 | | 2022-10-03 09:47:00 | 4.0620 | 4.0500 | 0.0120 | | 2022-10-03 09:48:00 | 4.0620 | NULL | NULL | | 2022-10-03 09:50:00 | 4.0580 | NULL | NULL | | 2022-10-03 09:51:00 | 4.0580 | NULL | NULL | | 2022-10-03 09:52:00 | 4.0560 | 4.0580 | -0.0020 | | 2022-10-03 09:53:00 | 4.0460 | NULL | NULL | | 2022-10-03 09:55:00 | 4.0420 | NULL | NULL | +---------------------+--------+--------+---------+ 20 rows in set (0,00 sec) ``` The 'NULL' is normal because there is not always the previous minute that corresponds (in addition it suits me in this case) But I have questions: 1) In "(hi-(select rlo)) as rdif" why can't I just use 'rlo' (have to add the select)? (Even if you answer the question below, please answer this one anyway) 2) How to avoid double select-from in table? (is that a subquery?) There must be better… What do you suggest? 3) I then consider other operations, in this style, more or less simple but complicated for me in MySQL. (calculations plus column updates..., not necessarily selections to display...) Do I have a better way to simply read/write the table and code these calculations in my app in nodejs (which I master: I'm learning a little MySQL, ok, but I still want to finsh my app…) (How much would run time be?) Thanks !
2022/10/03
[ "https://Stackoverflow.com/questions/73937079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15157921/" ]
You have to use `(select rlo)` because you can't refer to a column alias in the same query The more proper way to do this is with a self-join, then you don't need multiple selects for each calculation. You need to use `LEFT JOIN` to get null values when there's no matching row. ``` SELECT t1.dt as rdt, t1.hi as rhi, t2.lo AS rlo, t1.hi - t2.lo AS rdif FROM mytable AS t1 LEFT JOIN mytable AS t2 ON t2.dt = t1.dt - INTERVAL 10 MINUTE where t1.dt >= '2022-10-03 09:20:00' limit 20 ``` [DEMO](https://www.db-fiddle.com/f/bAUjRtNB3wQH9JMZpwUcf8/1)
59,394,539
When estimating the time complexity of a certain algorithm, let's say the following in pseudo code: ``` for (int i=0; i<n; i++) ---> O(n) //comparison? ---> ? //substitution ---> ? for (int i=0; i<n; i++) ---> O(n) //some function which is not recursive ``` In this case the time complexity of these instructions is `O(n)` because we iterate over the input `n`, but how about the comparison and substitution operations are they constant time since they don't depend on `n`? Thanks
2019/12/18
[ "https://Stackoverflow.com/questions/59394539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4627565/" ]
First, read [this](http://kddlab.zjgsu.edu.cn:7200/students/lipengcheng/%E7%AE%97%E6%B3%95%E5%AF%BC%E8%AE%BA%EF%BC%88%E8%8B%B1%E6%96%87%E7%AC%AC%E4%B8%89%E7%89%88%EF%BC%89.pdf) book. Here is good explanation of this topic. 1. Comparsion. For instance, we have two variables **a** and **b**. And when we doing this `a==b`we just take **a** and **b** from the memory and compare them. Let's define "*c*" as cost of memory, and "*t*" as cost of time. In this case we're using *2c* (because we're using two cells of the memory) and *1t* (because there is only one operation with the constant cost), therefore the *1t* - is the constan. Thus the time complexity is constant. 2. Substitution. It's pretty same as the previous operation. We're using two variables and one operation. This operation is same for the any type, therefore the cost of the time of the substitutin is constant. Then complexity is constant too.
17,365,606
I am using FormView control, and I want to programmatically insert null value in OnItemInserting and OnItemUpdating event, by NewValues dictioanry in FormViewUpdateEventArgs parameter. But if I use ``` protected void FormView_ItemUpdating(object sender, FormViewUpdateEventArgs e) { e.NewValues["EntityFrameworkEntityPropertyName"] = null; } ``` such modification is ignored, database column is not updated and keeps its old value. EntityFramework entity property is: Type Int32, Nullable True, StoreGeneratedPattern None. If I bind TextBox control directly to property by Bind(), nulls are inserted well. Also if values are different from null, everything works fine. How can I insert null value?
2013/06/28
[ "https://Stackoverflow.com/questions/17365606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831219/" ]
To remove you can simply use: ``` [myTextField removeFromSuperview]; ```
118,458
Does any know how to get the RDP version Windows is running with?
2010/03/10
[ "https://superuser.com/questions/118458", "https://superuser.com", "https://superuser.com/users/-1/" ]
Or you could Right click on the window and select About ![enter image description here](https://i.stack.imgur.com/CvjyF.png)
21,971,036
I tried to export a settings.json as documented in the meteor.js documentation in order to connect my Meteor.js app with an external MongoHQ database : ``` { "env": { "MONGO_URL" : "mongodb://xxx:[email protected]:10037/xxx" } } ``` with the command : ``` mrt deploy myapp.meteor.com --settings settings.json ``` It doesn't even work, My app continue to connect the local database provided with the Meteor.app ! My MONGO\_URL env variable didnt changed. Is there any solution to export my MONGO\_URL env variable to connect an external MongoDB database ? I saw that is possible to change it while using heroku or modulus, what about the standard deploying meteor.com solution ?
2014/02/23
[ "https://Stackoverflow.com/questions/21971036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2917448/" ]
You are not able to use your own `MONGO_URL` with Meteor deploy hosting. Meteor deploy hosting takes care of the Email with Mailgun (if you use it), and provides mongodb for all apps deployed there. It is possible to change the `MAIL_URL`, but it is not possible to use a different mongodb. You can try, though im not sure it will work: Place this in your server side code somewhere ``` process.env.MONGO_URL = '..'; ```
15,679,498
When I'm using Kunena on my site I have problems on the navigation bar. Whenever I'm in a Kunena "page" the navigation is not showing the FORUM as active.
2013/03/28
[ "https://Stackoverflow.com/questions/15679498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2112678/" ]
A work around will be to change the active with java script or jquery add this script to your index template ``` <script> var j = jQuery.noConflict(); var isForumActive = <?php if (strpos($_SERVER['REQUEST_URI'], "/forum") !== false){ echo "true"; } else echo "false";?>; if(isForumActive){ j(".item120").addClass("active"); } </script> ``` You will need to change the id (120) with your menu id and be sure that the alias is the correct. you need jquery as well....
58,374,987
I am pulling some results from MySQL database like below: ``` GetJobCodes=paste0("select EMPLID from jobCurrent where JOBCODE='",JOBCODE,"'") JOBCODES = dbGetQuery(connection,GetJobCodes) ``` and I want to pass above JOBCODES results to other SQL statement ``` statement=sprintf("SELECT A.EMPLID, A.CLASS_ID FROM lmsEnroll A JOIN lmsCourses\ B ON A.COURSE_ID=B.COURSE_ID AND B.REQUIRED=0 WHERE A.EMPLID IN (%s)",JOBCODES) ``` But when I am passing to above statement it is print like ```sql SELECT A.EMPLID, A.CLASS_ID FROM lmsEnroll A JOIN lmsCourses\ B ON A.COURSE_ID=B.COURSE_ID AND B.REQUIRED=0 WHERE A.EMPLID IN "C("00330022","00033322")") ``` which is not correct, I want to print them like : ```sql SELECT A.EMPLID, A.CLASS_ID FROM lmsEnroll A JOIN lmsCourses\ B ON A.COURSE_ID=B.COURSE_ID AND B.REQUIRED=0 WHERE A.EMPLID IN ("00330022","00033322") ``` I have used ShQuote function, but it is not help. I appreciate if anyone could help me.
2019/10/14
[ "https://Stackoverflow.com/questions/58374987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3018099/" ]
You can check [scrollLeft](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft) and [scrollTop](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop). You can change the property using javascript
29,313,546
Can anyone help me use a message box to display the random number and the square in two columns with a label for each? ``` const int NUM_ROWS = 10; const int NUM_COLS = 2; int[,] randint = new int [NUM_ROWS,NUM_COLS]; Random randNum = new Random(); for (int row = 0; row < randint.GetLength(0); row++) { randint[row,0] = randNum.Next(1,100); randint[row,1] = randint[row,0]*randint[row,0]; Console.Write(string.Format("{0,5:d} {1,5:d}\n", randint[row,0], randint[row,1])); ```
2015/03/28
[ "https://Stackoverflow.com/questions/29313546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4722898/" ]
I have achieved it by adding reference of System.Windows.Forms to my console application and got the result you desired. Here is my code: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace ConsoleApplication6 { class Program { static void Main(string[] args) { const int NUM_ROWS = 10; const int NUM_COLS = 2; int[,] randint = new int[NUM_ROWS, NUM_COLS]; Random randNum = new Random(); for (int row = 0; row < randint.GetLength(0); row++) { randint[row, 0] = randNum.Next(1, 100); randint[row, 1] = randint[row, 0] * randint[row, 0]; Console.Write(string.Format("{0,5:d} {1,5:d}\n", randint[row, 0], randint[row, 1])); MessageBox.Show(string.Format("{0,5:d} {1,5:d}\n", randint[row, 0], randint[row, 1])); Console.ReadKey(); } } } } ``` **My output:** ![Output](https://i.stack.imgur.com/tLXc2.png) Also though this is not asked but just in case to add reference to System.Windows.Form look right click on the references in your solution explorer and select .Net tab and then press ok after selecting the desired dll. Cheers! ![Adding ref](https://i.stack.imgur.com/jCuN7.png) ![Selecting desired reference](https://i.stack.imgur.com/kjcTC.png)
28,641,948
This addresses "a specific programming problem" from [On-Topic](https://stackoverflow.com/help/on-topic) I am working on an interview question from [Amazon Software Interview](http://www.glassdoor.com/Interview/Given-a-triangle-of-integers-find-the-path-of-the-largest-sum-without-skipping-QTN_623875.htm) The question is " Given a triangle of integers, find the path of the largest sum without skipping. " My question is how would you represent a triangle of integers? I looked this up on [Triangle of Integers](https://stackoverflow.com/questions/25143410/how-to-print-a-triangle-of-integers-with-number-of-lines-specified-by-the-user) and saw that a triangle of integers looked something like ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ``` What is the best way(data structure) to represent something like this? My idea was having something like ``` int[] r1 = {1}; int[] r2 = {2, 3}; int[] r3 = {4, 5, 6}; int[] r4 = {7, 8, 9, 10}; int[] r5 = {11, 12, 13, 14, 15}; ``` Is this the best way to represent this triangle integer structure? I thought about using a 2 dimensional matrix structure but those have to have arrays of the same size.
2015/02/21
[ "https://Stackoverflow.com/questions/28641948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3761297/" ]
You should put them in linear memory and access them as: ``` int triangular(int row){ return row * (row + 1) / 2 + 1; } int[] r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; for(int i=0; i<n_rows; i++){ for(int j=0; j<=i; j++){ System.out.print(r[triangular(i)+j]+" "); }System.out.println(""); } row, column if row>column: index=triangular(row)+column ``` Since it's a predictable structure there's an expression for the offset of the beginning of each row. This will be the most efficient way.
33,073,061
ListView does not show the Checked items that I want to add by default. ``` String[] allComplaintActions = POCValues.pocMap.get(chiefComplaint.getSelectedItem().toString()); ArrayAdapter<String> actionArrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_multiple_choice, allComplaintActions); actionList.setAdapter(actionArrayAdapter); Log.d(TAG, "Count : " + actionList.getCount()); actionList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); actionList.setItemChecked(2, true); Log.d(TAG, "CheckedItem: "+ actionList.getCheckedItemPosition()); ``` Will Spit out this Log > > Count : 4 > > > CheckedItem: 2 > > > but the remains completely blank. I am on an emulator. Could that be the problem? This is what I see [Test](http://i.stack.imgur.com/0EiUU.png) But "Something more reasonable" should be checked
2015/10/12
[ "https://Stackoverflow.com/questions/33073061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3716606/" ]
Try this... ``` <li><div class="some css class here"><a id="atag" onserverclick="atag_ServerClick" runat="server">Logout</a></div></li> ``` In codebehind you have to call the anchor tag's function: ``` private void atag_ServerClick(object sender, System.EventArgs e) { atag.Target="url"; } ``` **OR** As per your Requirement: ``` private void atag_ServerClick(object sender, System.EventArgs e) { FormsAuthentication.SignOut(); Session.Clear(); Session.Abandon(); Response.Redirect("~/login.aspx"); } ``` Hope this helps...
14,029,038
I am developing a registration system that lists events and the users will be able to register in these events. Each event has a specific number of seats. The problem that I am facing now is even when the number of registration reaches the number of seats, the event is still avaiable and I cannot stop the booking process by disabling booking button. For your information, I have the following database design: ``` Event Table: ID, Title, NumberOfSeats BookingDetails Table: BookingID, EventID, Username User Table: Username, Name ``` The events will be listed in a GridView control and there is LinkButton inside the GridView for booking in the event. I am using a ModalPopUp Extender control and this is why I am using a LinkButton as shown in the ASP.NET code below. In the code-behind, inside the GrivView\_RowDataBound, I compared between the number of seats and the number of bookings for each event. If the number of bookings greater than or equal to the number of seats. Booking button should be disabled. I wrote the code but I don't know why it is not working with me and why I am getting the following error: ***Unable to cast object of type 'System.Web.UI.WebControls.GridView' to type 'System.Web.UI.WebControls.LinkButton'.*** ***ASP.NET code:*** ``` <asp:GridView ID="ListOfAvailableEvents_GrivView" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="10" onrowdatabound="ListOfAvailableEvents_GrivView_RowDataBound"> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" CssClass="generaltext" /> <Columns> <asp:TemplateField HeaderText=""> <ItemTemplate> <asp:LinkButton ID="lnkTitle" runat="server" CssClass="button" Text="Book &rarr;" OnClick="lnkTitle_Click"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" /> <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" /> <asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location" /> <asp:BoundField DataField="StartDateTime" HeaderText="Start Date & Time" SortExpression="StartDateTime" /> <asp:BoundField DataField="EndDateTime" HeaderText="End Date & Time" SortExpression="EndDateTime" /> </Columns> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <HeaderStyle Font-Bold="True" CssClass="complete" /> <EditRowStyle BackColor="#999999" /> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> <EmptyDataTemplate><h2>No Events Available</h2></EmptyDataTemplate> </asp:GridView> ``` ***Code-Behind (C#) code:*** ``` protected void ListOfAvailableEvents_GrivView_RowDataBound(object sender, GridViewRowEventArgs e) { int numberOfBookings = 0; int numberOfAvailableSeats = 0; string connString = "..........." string selectCommand = @"SELECT COUNT(*) AS UserBookingsCount, dbo.Events.NumberOfSeats FROM dbo.BookingDetails INNER JOIN dbo.Events ON dbo.BookingDetails.EventID = dbo.Events.ID GROUP BY dbo.Events.NumberOfSeats"; using (SqlConnection conn = new SqlConnection(connString)) { //Open DB Connection conn.Open(); using (SqlCommand cmd = new SqlCommand(selectCommand, conn)) { SqlDataReader reader = cmd.ExecuteReader(); if (reader != null) if (reader.Read()) { numberOfBookings = Int32.Parse(reader["UserBookingsCount"].ToString()); numberOfAvailableSeats = Int32.Parse(reader["NumberOfSeats"].ToString()); } } //Close the connection conn.Close(); } if (numberOfBookings >= numberOfAvailableSeats) { LinkButton bookButton = (LinkButton)(sender); bookButton.Enabled = false; } } ``` **So could you please tell me how to fix this problem?** **UPDATE:** The GridView lists many different events. Let us take one of them. If event A has 3 available seats and the number of bookings reaches 3, the 'Book' button should be disabled only for this event not for all of them. So the button will be disabled for this event when the number of bookings reaches the number of available seats.
2012/12/25
[ "https://Stackoverflow.com/questions/14029038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1897016/" ]
Try : ``` LinkButtton lbtn = new LinkButtton(); lbtn = (LinkButton)e.Row.FindControl("ButtonId"); ``` Then use `lbtn` for further operations. Thanks
8,688,185
How I can find in XPath 1.0 all rows with empty `col name="POW"`? ``` <row> <col name="WOJ">02</col> <col name="POW"/> <col name="GMI"/> <col name="RODZ"/> <col name="NAZWA">DOLNOŚLĄSKIE</col> <col name="NAZDOD">województwo</col> <col name="STAN_NA">2011-01-01</col> </row> ``` I tried many solutions. Few times in Firefox extension XPath Checker selection was ok, but `lxml.xpath()` says that expression is invalid or just returns no rows. My Python code: ``` from lxml import html f = open('TERC.xml', 'r') page = html.fromstring(f.read()) for r in page.xpath("//row[col[@name = 'POW' and not(text())]]"): print r.text_content() print "-------------------------" ```
2011/12/31
[ "https://Stackoverflow.com/questions/8688185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/499768/" ]
> > How I can find in XPath 1.0 all rows with empty `col name="POW"`? > > > There are many possible definitions of "empty" and for each one of them there is a different XPath expression selecting "empty" elements. A reasonable definition for an empty element is: an element that has no children elements and no text-node children, or an element that has a single text-node child, whose string value contains only whitespace characters. **This XPath expression**: ``` //row[col[@name = 'POW'] [not(*)] [not(normalize-space())] ] ``` selects all `row` elements in the XML document, that have a `col` child, that has an attribute `name` with string value `"POW"` and that has no children - elements and whose string value consists either entirely of whitespace characters, or is the empty string. **In case by "empty" you understand "having no children at all"**, which means no children elements and no children PI nodes and no children comment nodes, then use: ``` //row[col[@name = 'POW'] [not(node())] ] ```
52,269,829
I am having trouble finding a way to authenticate an user. When you start the Node JS Server manually this worked fine (and yeah its ugly code): ``` if (data.URL.includes("https://share.url.com")) { await page.type('#userNameInput', 'user'); await page.type('#passwordInput', 'pass'); await page.click('#submitButton'); await page.waitForNavigation({waitUntil: 'load'}); await page.waitFor(6000); } ``` Sharepoint didnt know my user data so they navigated me to a login page where I could fill in the Login Information and then move to my requested site. But in the meantime there were 2 changed made: 1. This Login Page doesnt exist anymore, if the login information isnt found I just get linked to a page where it says "Sorry you don't have access to this page". The 2nd problem or change is that the node server is started by a service. At the end I just need to somehow access the page and then take a screenshot of it. But the auth is making me trouble. I now need a workaround to this problem, but I cant think about other solutions. **Puppeteer authenticate:** ``` await page.authenticate({ username: "user", password: "pass" }); ``` This doesnt work or using this with an auth header doesnt work either. **Saving user cred. in browser (chrom(ium)):** I tried to save the user cred. for the page inside the browser, but this didnt have any affect. **URL Auth:** I tried to auth inside the URL like (<https://user:[email protected]/bla/site.aspx>) but it doesnt work. I am out of ideas how to approach this problem, have you got any suggestions how I could try this in an other way or did you see errors in my code or in my thoughts? Thanks go to Bill Gates
2018/09/11
[ "https://Stackoverflow.com/questions/52269829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7156350/" ]
About > > Saving user cred. in browser (chrom(ium)): > > > I had similar situation - I wanted to do screenshot from facebook when I'm logged in. To achieve it I did steps like: 1) Created temp user data dir ``` mkdir /tmp/puppeteer_test ``` 2) Run Chrome with these arguments ``` /usr/bin/google-chrome --user-data-dir=/tmp/puppeteer_test --password-store=basic ``` 3) Go to facebook.com, log into and then close the browser 4) Run puppeteer with appropriate arguments: ``` const browser = await puppeteer.launch({ headless: false, executablePath: '/usr/bin/google-chrome', args: ['--user-data-dir=/tmp/puppeteer_test'] }); const page = await browser.newPage(); await page.goto('https://facebook.com', { waitUntil: 'networkidle2' }); await page.screenshot({path: 'facebook.png'}); await browser.close(); ```
33,581,329
How I can pass a Map parameter as a GET param in url to Spring REST controller ?
2015/11/07
[ "https://Stackoverflow.com/questions/33581329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219755/" ]
There are different ways (*but a simple `@RequestParam('myMap')Map<String,String>` does not work - maybe not true anymore!*) The (IMHO) easiest solution is to use a command object then you could use `[key]` in the url to specifiy the map key: @Controller ``` @RequestMapping("/demo") public class DemoController { public static class Command{ private Map<String, String> myMap; public Map<String, String> getMyMap() {return myMap;} public void setMyMap(Map<String, String> myMap) {this.myMap = myMap;} @Override public String toString() { return "Command [myMap=" + myMap + "]"; } } @RequestMapping(method=RequestMethod.GET) public ModelAndView helloWorld(Command command) { System.out.println(command); return null; } } ``` * Request: http://localhost:8080/demo?myMap[line1]=hello&myMap[line2]=world * Output: `Command [myMap={line1=hello, line2=world}]` *Tested with Spring Boot 1.2.7*
12,124,297
I need a scheduler (for one time only actions) for a site I'm coding (in php), and I had two ideas: 1- Run a php script with crontab and verify against a database of scheduled actions and execute ones that are older than current time. 2- Schedule various tasks with the "at" command. The second option seems much better and simpler, so that's what I'm trying to do. However, I haven't found a way to tell "at" to run a command using the PHP interpreter, and so far I've been creating a .sh script, which contains a single command, which is to run a file through the php interpreter. That is far from the optimal setting, and I wish I could just execute the php code directly through "at", something like: ``` at -e php -f /path/to/phpscript time ``` Is it possible? I haven't found anything about using environments other than bash in either the man or online.
2012/08/25
[ "https://Stackoverflow.com/questions/12124297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1445420/" ]
You can prepend `phpscript` with a `#!/usr/bin/php` (or wherever your php script is stored) and make `/path/to/phpscript` executable. This is exactly what the `#!` syntax is for. Just so it's clear, your `phpscript` would look like this: ``` #!/usr/bin/php ...your code goes here ```
55,690,637
I have some data files with around 10k records; each record containing a value plus the standard deviation for it. I'm plotting the standard deviation as a slightly transparent `filledcurve`. However, since there were some weird artifacts with painting so many points, I've resorted to using the `every` command to plot every 99 points. ``` '$1' using 1:(\$3-\$5):(\$3+\$5) every 99::0 with filledcurves ls $COUNTER notitle ``` This works perfectly; however my problem is that depending on how many exact records I have in the file, the `every` command may skip the last entries, which ends up with the colored standard deviation area ending before its respective line. [![Missing std](https://i.stack.imgur.com/54OJB.png)](https://i.stack.imgur.com/54OJB.png) Is there any way to include the last record to the every command/filled plot so that the colored area extends to where it needs to? EDIT: The effect I'm trying to avoid is this: [![flickery plot](https://i.stack.imgur.com/l8HTh.png)](https://i.stack.imgur.com/l8HTh.png) I can't seem to really reproduce it atm as I'm working with new data, but I'm sure that picking points every once in a while avoids it.
2019/04/15
[ "https://Stackoverflow.com/questions/55690637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1356926/" ]
[amended to show full treatment of NaN value. Demo'ed with a real data file] Instead of `every`, you can construct a filter function for the `using` specifier. ``` set xrange [100:600] xmax = 600 filter(x) = (int(column(0))%9 == 0 || x == xmax) ? 1 : 0 set datafile missing NaN plot 'silver.dat' using (filter($1)?$1:NaN) : ($2-$3) : ($2+$3) with filledcurves, \ '' using 1:2 with lines ``` [![enter image description here](https://i.stack.imgur.com/2JKiI.png)](https://i.stack.imgur.com/2JKiI.png)
10,664
What is the food with the highest calorie per unit price that you can buy and eat regularly? The food cannot give you any undesirable health effect due to the sole reason that you eat it regularly.
2017/01/01
[ "https://health.stackexchange.com/questions/10664", "https://health.stackexchange.com", "https://health.stackexchange.com/users/7809/" ]
For **1 US Dollar** you can get: Foods with mainly *carbohydrates:* * **Polenta/cornmeal,** raw, 847 g = **2,930** Cal * **Potatoes, white,** raw, 2,400 g = **1,844** Cal * **Bread, black,** 680 g = **1,536** Cal * **Oatmeal,** raw, 340 g = **1,244** Cal * **Rice, white,** raw, 320 g = **1,117** Cal- * **Chickpeas (garbanzo beans),** canned, (also contain protein), 340 g = **558** Cal Foods with mainly *protein/fat:* * **Chicken,** raw, 405 g = **640** Cal * **Sardines,** canned, 142 g = **354** Cal These are examples of cheap high-calorie foods you can eat regularly as part of a healthy diet. *Cal = 1 kilocalorie* *Prices, as available in Slovenia/Europe at 6th January 2017* --- Calculations and sources: * Bread, black, 1kg = 1,39 € = 1.47 $; for $1 you get 680 g = 1,536 Cal (226 Cal/100 g) ([source](https://trgovina.mercator.si/market/izdelek/1536699/crni-hlebec-mercator-1kg)) * Rice, white, 1 kg = 2.98 € = 3.15 $; for $1 you get 320 g = 1,117 Cal (349 Cal/100 g) ([source](https://trgovina.mercator.si/market/izdelek/28543/srednjezrnati-brusen-riz-za-domace-jedi-zlato-polje-1-kg)) * Polenta (cornmeal), 500 g = 0.56 € = 0.59 $; for $1 you get 847 g = 2.930 Cal (346 Cal/100 g) ([price](https://trgovina.mercator.si/market/izdelek/16879812/instant-polenta-mercator-500-g), [Calories](http://www.mlinotest.si/okusi/mlinotest/moke-in-mlevski-izdelki/instant-mlevski-izdelki/instant-polenta-500-g/)) * Oatmeal, 500 g = 1.39 € = 1.47 $; for $1 you get 340 g = 1,244 Cal (366 Cal/100 g) ([source](https://trgovina.mercator.si/market/izdelek/82115/ovseni-kosmici-zito-500-g)) * Potatoes, white, 5 kg = 2 € = 2.1 $; for $1 you get 2,400 g = 1,844 Cal (77 Cal/100 g) ([price](https://trgovina.mercator.si/market/izdelek/14939390/krompir-mercator-5kg-pakirano), [Calories](http://www.cenim.se/hranilne-vrednosti.php?id=2924)) * Chickpeas, canned, for $1 you get 340 g = 558 Cal ([price](https://www.walmart.com/ip/La-Preferida-Chick-Peas-15-oz-Pack-of-12/19475594?action=product_interest&action_type=title&beacon_version=1.0.2&bucket_id=irsbucketdefault&client_guid=b0a2d57f-0c10-43c6-81c7-0a31e7ad0827&config_id=106&customer_id_enc&findingMethod=p13n&guid=b0a2d57f-0c10-43c6-81c7-0a31e7ad0827&item_id=19475594&parent_anchor_item_id=10534041&parent_item_id=10534041&placement_id=irs-106-t1&reporter=recommendations&source=new_site&strategy=PWVAV&visitor_id=Qywxb4F8UbLMSgaZbzoypE)), [(Calories)](https://ndb.nal.usda.gov/ndb/foods/show/4796?man=&lfacet=&count=&max=50&qlookup=chickpeas&offset=&sort=default&format=Abridged&reportfmt=other&rptfrm=&ndbno=&nutrient1=&nutrient2=&nutrient3=&subset=&totCount=&measureby=&Qv=3.4&Q9005=1&Qv=1&Q9005=1) * Canned fish, sardines, 105 g = 0.7 € = 0.74 $; for $1 you get 142 g = 354 Cal (249 Cal/100 g) ([source](https://trgovina.mercator.si/market/izdelek/16882804/sardine-v-rastlinskem-olju-mercator-105-g)) * Chicken, whole, 1.5 kg = 3.5 € = 3.7 $; for $1 you get 405 g = 640 Cal (160 (Cal/100 g) ([source](https://trgovina.mercator.si/market/izdelek/12208088/piscanec-mercator-pakirano-cena-za-kg))
2,716,178
How do I handle closing tags (ex: `</h1>`) with the Java HTML Parser Library? For example, if I have the following: ``` public class MyFilter implements NodeFilter { public boolean accept(Node node) { if (node instanceof TagNode) { TagNode theNode = (TagNode) node; if (theNode.getRawTagName().equals("h1")) { return true; } else { return false; } } return false; } } public class MyParser { public final String parseString(String input) { Parser parser = new Parser(); MyFilter theFilter = new MyFilter(); parser.setInputHTML("<h1>Welcome, User</h1>"); NodeList theList = parser.parse(theFilter); return theList.toHtml(); } } ``` When I run my parser, I get the following output back: ``` <h1>Welcome, User</h1>Welcome, User</h1> ``` The NodeList contains a list of size 3 with the following entities: ``` (tagNode) <h1> (textNode) Welcome, User (tagNode) </h1> ``` I would like the output to be "`<h1>Welcome, User</h1>`". Does anyone see what is wrong in my sample parser?
2010/04/26
[ "https://Stackoverflow.com/questions/2716178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326284/" ]
A `DataContext` follows a pattern known as a Unit of Work. It tracks all inserts, updates, and deletes you do during a piece of code. Once that piece of code is done running, the `SubmitChanges` method sends all modifications to the database *at one time*. There is no need for you to do anything; changes you make will automatically be persisted.
60,937,975
> > Since Digital Ocean Spaces API is compatible with AWS SDK, how to > upload images to Digital Ocean Spaces programmatically using AWS SDK > for Yii2? > > > Here my details ``` Good, we have the following data: 1. endpoint: fra1.digitaloceanspaces.com 2. bucket name: dev-abc 3. api key: xxxxxxxxxxxxx and api secret: xxxxxxx 4. The url that you need to use to deliver assets is https://dev-abc ``` I have tried with this code whis is not working ``` $uploader = new FileUpload(FileUpload::S_S3, [ 'version' => 'latest', 'region' => 'fra1', 'endpoint' => 'https://fra1.digitaloceanspaces.com', 'credentials' => [ 'key' => 'xxxxxxxxxxxxx ', 'secret' => 'xxxxxxx' ], 'bucket' => 'dev-abc' ]); ```
2020/03/30
[ "https://Stackoverflow.com/questions/60937975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5994023/" ]
You can php code to upload image in digital ocean: 1. Configure a client: use Aws\S3\S3Client; ``` $client = new Aws\S3\S3Client([ 'version' => 'latest', 'region' => 'us-east-1', 'endpoint' => 'https://nyc3.digitaloceanspaces.com', 'credentials' => [ 'key' => getenv('SPACES_KEY'), 'secret' => getenv('SPACES_SECRET'), ], ]); ``` 2. Create a New Space ``` $client->createBucket([ 'Bucket' => 'example-space-name', ]); ``` 3. Upload Image ``` $client->putObject([ 'Bucket' => 'example-space-name', 'Key' => 'file.ext', 'Body' => 'The contents of the file.', 'ACL' => 'private' ]); ```
188,156
The users need to be about to print the forms they've filled out on SharePoint after they've filled them out. In just wondering if it is easily possible because I'm not finding anything. Forms are hosted on SharePoint and created in InfoPath
2016/07/29
[ "https://sharepoint.stackexchange.com/questions/188156", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/56516/" ]
* Go to list > Customize List> select your form. * Add a Content Editor Web part or Script Editor for SharePoint 2013 to the page. [![enter image description here](https://i.stack.imgur.com/9aUbI.png)](https://i.stack.imgur.com/9aUbI.png) - Add the following code. ``` `< input type="button" value=" Print this page " onclick="window.print();return false;" />` ``` You can also add `on click` the following function `function printInfoPathForm(){ var ipForm = $(INFOPATH_FORM); if (ipForm) { //build html for print page var html = "<HTML><HEAD>\n"+ $("head").html()+ "</HEAD>\n<BODY>\n"+ ipForm.html()+ "\n</BODY></HTML>"; //open new window var printWP = window.open("","printWebPart"); printWP.document.open(); //insert content printWP.document.write(html); printWP.document.close(); //open print dialog printWP.print(); } }` For more details check this [article](http://www.enjoysharepoint.com/Articles/Details/add-print-button-to-display-form-in-sharepoint-2013-using-20837.aspx)
84,473
The Nachem prayer for tisha b'av describes he city as השוממה מאין יושב, "desolate without inhabitant." What does this mean? In what way was Jerusalem desolate without inhabitants? Does this have a non-literal meaning? NOTE: I am not referring to the question of Nachem after 1967. I am asking what this prayer could have meant for the nineteen hundred years beforehand.
2017/07/31
[ "https://judaism.stackexchange.com/questions/84473", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/14599/" ]
Two thousand years beforehand, they may not have said this text. [Rambam's text](http://www.mechon-mamre.org/i/2700.htm#23), for example, does not have it, nor do Seder Rav Amram Gaon (ed. Harpenes: Seder Tisha B'av), or Seder Rav Sa'adya Gaon, which just has השוממה. Nevertheless, it is present in the Siddur of [R. Eleazar Rokeah](https://en.wikipedia.org/wiki/Eleazar_of_Worms) (ch. 123 p. 637). His Siddur makes clear that the references to being bereft of its inhabitants refer particularly to the Jewish inhabitants. > > והשוממה מכל טוב. האבלה מבלי בניה שאין ישראל בתוכה, דרכי ציון אבילות מבלי באי מועד...והשוממה מבלי יושב אין איש מיהודה יושב בה, כל שעריה שוממין. היא יושבת בגוים > > > Desolate of all good. That is in mourning without her children: for the Jews are not in it; "The paths of Zion are mourning, without pilgrims." And bereft with no inhabitants; there is no man of Judah living in it: "All its gates are destroyed." > > > The line השוממה מאין יושב is thus particularly understandable in light of the line: ויבלעוה לגיונים, ויירשוה עובדי פסילים; that it was occupied by foreign legions and idolaters. This prayer referencing general destruction, absence of Jewish inhabitants, and occupation by foreign armies was always true to one degree or another following the destruction of the Second Templ, until modern times. For example, following the destruction of Jerusalem (in 70), Josephus writes ([The Wars of the Jews: Book VII:1](http://sacred-texts.com/jud/josephus/war-7.htm)): > > Now as soon as the army had no more people to slay or to plunder, because there remained none to be the objects of their fury (for they would not have spared any, had there remained any other work to be done), [Titus] Caesar gave orders that they should now demolish the entire city and Temple...**there was left nothing to make those that came thither believe it [Jerusalem] had ever been inhabited**. > > > Furthermore, the [Bar Kokhba revolt](https://en.wikipedia.org/wiki/Bar_Kokhba_revolt) 65 years later: > > Resulted in the extensive depopulation of Judean communities, more so than the First Jewish–Roman War of 70 CE. According to Cassius Dio, 580,000 Jews perished in the war and many more died of hunger and disease. In addition, many Judean war captives were sold into slavery. The Jewish communities of Judea were devastated to an extent which some scholars describe as a genocide. ([Wikipedia](https://en.wikipedia.org/wiki/Bar_Kokhba_revolt)). > > > Furthermore, Jews were barred from entering Jerusalem except for on Tisha B'av (ibid). They remained banned throughout the remainder of its time as a Roman province, except during a brief period of Persian rule from 614 to 629. ([Wikipedia](https://en.wikipedia.org/wiki/History_of_Jerusalem#Post-Crisis_Roman_and_Early_Byzantine_Empire_period)) Later, during the [First Crusade](https://en.wikipedia.org/wiki/First_Crusade), Jerusalem was captured by Christians in 1099, and: > > The capture was accompanied by a massacre of almost all of the Muslim and Jewish inhabitants ([Wikipedia](https://en.wikipedia.org/wiki/History_of_Jerusalem#Kingdom_of_Jerusalem_.28Crusaders.29_period)). > > > Specifically: > > According to the Muslim chronicle of Ibn al-Qalanisi, "The Jews > assembled in their synagogue, and the Franks burned it over their > heads. ([Wikipedia](https://en.wikipedia.org/wiki/Siege_of_Jerusalem_(1099)#Jews)) > > > This period lasted until the Crusaders were defeated at the [Siege and Fall of Jerusalem in 1187](https://en.wikipedia.org/wiki/Siege_of_Jerusalem_(1187)). About 30 years later, Jerusalem and its Jewish inhabitants *again* suffered destruction when the Ayyubid ruler of Syria, Al-Mu'azzam destroyed Jerusalem: > > The city suffered two waves of destruction in 1219 and 1220. This was absolute and brutal destruction, with most buildings in Jerusalem and its walls destroyed...The vast majority of the population, including the Jewish community, left Jerusalem. ([Wikipedia](https://en.wikipedia.org/wiki/History_of_Jerusalem_during_the_Kingdom_of_Jerusalem#Destruction_of_Jerusalem)). > > > From 1229 to 1244 the city was returned to mostly Christian control, by Abassids allied with them. In the [Siege of 1244](https://en.wikipedia.org/wiki/Siege_of_Jerusalem_(1244)), however, As-Salih Ayyub who not allied with the Crusaders, summoned a huge mercenary army of Khwarezmians, who proceeded to again, destroy the city. In 1260, after the city is retaken by the Ayyubids from the Khwarezmians, it is raided by Mongols. ([Wikipedia](https://en.wikipedia.org/wiki/Timeline_of_Jerusalem#Bahri_Mamluk_and_Burji_Mamluk_periods)) Almost a decade later, when Ramban moved to Jerusalem, he is reputed to have found just two Jewish families ([Wikipedia](https://en.wikipedia.org/wiki/Timeline_of_Jerusalem#Bahri_Mamluk_and_Burji_Mamluk_periods)). While the population grew with time, even 200 years later, in the late 15th century the Jewish population of Jerusalem varied from 76-250 families ([Wikipedia](https://en.wikipedia.org/wiki/Demographic_history_of_Jerusalem#Middle_Ages)). Following a "mass" migration led by Yehuda Hassid (see [here](https://judaism.stackexchange.com/q/60882/8775) about him and his synagogue) in 1700 (when the Jewish population was about 1200), the Jewish population rose to 2000 by 1723. (AFAIK the highest it was since the destruction of temple, and probably just a fraction of a percent of its population then). By the early 19th century, its Jewish population [was no higher](https://en.wikipedia.org/wiki/Demographic_history_of_Jerusalem#Muslim_.22relative_majority.22). After multiple waves of immigration, and significant philanthropic efforts on behalf of residents, the population reached 10000 at the end of the 19th century, and rapidly grew to almost 100000 in 1944. While the city wasn't always totally uninhabited, or even bereft of all of Jewish inhabitants, (See [timeline](https://en.wikipedia.org/wiki/Timeline_of_Jerusalem)) it frequently changed hands among foreign invaders, was destroyed multiple times, banned Jews for centuries, and for nearly two millennia did not return, to even a shadow of its former self (with a Jewish population of hundreds of presumably hundreds of thousands (Tacitus says 600000) before the destruction of the second Temple.). --- Alternatively, the [Imrei Emmet](https://en.wikipedia.org/wiki/Avraham_Mordechai_Alter) explains this as referring to the heavenly Jerusalem not being inhabited by God, as it is stated (Ta'anit 5a) that God will not enter the heavenly Jerusalem, until he enters the terrestrial Jerusalem. (Cited in Daf Al HaDaf to Ta'anit 5a).
15,174,517
I want to send multiple SMS' via using smslib. I make a Java class to send SMS in a loop. But it works only one time. then it returns the following exception: ``` org.smslib.GatewayException: Comm library exception: java.lang.RuntimeException: javax.comm.PortInUseException: Port currently owned by org.smslib at org.smslib.modem.SerialModemDriver.connectPort(SerialModemDriver.java:102) at org.smslib.modem.AModemDriver.connect(AModemDriver.java:114) at org.smslib.modem.ModemGateway.startGateway(ModemGateway.java:189) at org.smslib.Service$1Starter.run(Service.java:276) ``` This is my class: ``` import javax.swing.JOptionPane; import org.smslib.AGateway; import org.smslib.IOutboundMessageNotification; import org.smslib.OutboundMessage; import org.smslib.Service; import org.smslib.modem.SerialModemGateway; public class SendSMS1 { private static String id; private static String port; private static int bitRate; private static String modemName; private static String modemPin; private static String SMSC; public static void doIt(String number, String text) { try { OutboundMessage msg; OutboundNotification outboundNotification = new OutboundNotification(); SerialModemGateway gateway = new SerialModemGateway(id, port, bitRate, modemName, "E17u-1"); gateway.setInbound(true); gateway.setOutbound(true); gateway.setSimPin(modemPin); Service.getInstance().setOutboundMessageNotification(outboundNotification); Service.getInstance().addGateway(gateway); Service.getInstance().startService(); msg = new OutboundMessage(number, text); Service.getInstance().sendMessage(msg); System.out.println(msg); Service.getInstance().stopService(); } catch (Exception ex) { if (ex.getStackTrace()[2].getLineNumber() == 189) { JOptionPane.showMessageDialog(null, "Port currently owned by usb Modem's application. \n Please close it & run the programm again.", "Port Exception", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } else { JOptionPane.showMessageDialog(null, ex.getMessage(), "Sending faile", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } } public static class OutboundNotification implements IOutboundMessageNotification { public void process(AGateway gateway, OutboundMessage msg) { System.out.println("Outbound handler called from Gateway: " + gateway.getGatewayId()); System.out.println(msg); } } public static void main(String[] args) throws Exception { String number = "+94772347634", text = "Hello world"; modemName = "Huwawi"; port = "COM4"; bitRate = 115200; modemPin = "0000"; SMSC = "+947500010"; for (int i = 0; i < 5; i++) { SendSMS1 app = new SendSMS1(); app.doIt(number, text); } } } ``` Please give me advice, what should I do differently?
2013/03/02
[ "https://Stackoverflow.com/questions/15174517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2126003/" ]
I don't know the smslib, but I imagine everything until `startService` should only happen once, not each time you want to send a message, as follows: ``` class SendSMS1 { public SendSMS1(String modemName, String port, int bitRate, String modemPin, String SMSC) { OutboundNotification outboundNotification = new OutboundNotification(); SerialModemGateway gateway = new SerialModemGateway(id, port, bitRate, modemName, "E17u-1"); gateway.setInbound(true); gateway.setOutbound(true); gateway.setSimPin(modemPin); Service.getInstance().setOutboundMessageNotification(outboundNotification); Service.getInstance().addGateway(gateway); Service.getInstance().startService(); } public static void doIt(String number, String text) { try { OutboundMessage msg = new OutboundMessage(number, text); Service.getInstance().sendMessage(msg); System.out.println(msg); Service.getInstance().stopService(); } catch (Exception ex) { if (ex.getStackTrace()[2].getLineNumber() == 189) { JOptionPane.showMessageDialog(null, "Port currently owned by usb Modem's application. \n Please close it & run the programm again.", "Port Exception", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } else { JOptionPane.showMessageDialog(null, ex.getMessage(), "Sending faile", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } } public static void main(String[] args) throws Exception { String number = "+94772347634", text = "Hello world"; SendSMS1 app = new SendSMS1("Huwawi", "COM4", 115200, "0000", "+947500010"); for (int i = 0; i < 5; i++) { app.doIt(number, text); } } } ```
60,657,831
I've set my mapping up as follows: ``` CreateMap<SourceClass, DestinationClass>().ForMember(destinationMember => destinationMember.Provider, memberOptions => memberOptions.MapFrom(src => src.Providers.FirstOrDefault())); ``` Where I'm mapping from a List in my SourceClass to a string in my destination class. My question is, how can I handle the case where "Providers" is null? I've tried using: `src?.Providers?.FirstOrDefault()` but I get an error saying I can't use null propagators in a lambda. I've been reading up on Automapper and am still unsure if AM automatically handles the null case or not. I tried to build the expression tree, but was not able to see any information that provided additional informations. If it helps, I'm using automapper v 6.1.1.
2020/03/12
[ "https://Stackoverflow.com/questions/60657831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4162438/" ]
Like what @goto1 mentioned in a comment, you may create a custom hook to use for a cleaner and reusable look. Here's my take on a custom hook called `useCbOnce` which calls any event callback once: ``` const useCbOnce = (cb) => { const [called, setCalled] = useState(false); // Below can be wrapped in useCallback whenever re-renders becomes a problem return (e) => { if (!called) { setCalled(true); cb(e); } } } const MyForm = (props) => { const handleSubmit = useCbOnce((e) => { e.preventDefault() console.log('submitted!') }); return <form onSubmit={handleSubmit}>...</form>; } ```
120,425
There are several questions around limiting ftp users to certain directories. However, most of them refer to vsftpd, which I don't think I have installed on my system. I'm running Ubuntu 9.04. How can I tell what ftp service I have installed, and then limit certain users to only the `/home/ftpuser` directory instead of having full access to the file system? I think I can add them to a separate group and give that group access to the proper directories, but then do I have to remove that groups permissions from all other directories? It seems like there should be an easy way like setting the `chroot_local_user` value in the `/etc/vsftpd/vsftpd.conf` file, but that doesn't exist on my system. **Update** Here are the results of: `dpkg --list |grep -i ftp`: `ii curl 7.18.2-8ubuntu4.1 Get a file from an HTTP, HTTPS or FTP server` I can connect to this servier using sftp but there are no ftp servers installed. Do I have to install one?
2010/03/08
[ "https://serverfault.com/questions/120425", "https://serverfault.com", "https://serverfault.com/users/37112/" ]
I'd recommend using [proftpd](http://www.proftpd.org/) with Ubuntu.... I follwed these steps recently and it worked ver y well.... Here's quick install steps: ``` sudo apt-get install proftpd # Add this line in /etc/shells file (sudo gedit /etc/shells to open the file) /bin/false cd /home sudo mkdir FTP-shared sudo useradd userftp -p your_password -d /home/FTP-shared -s /bin/false sudo passwd userftp cd /home sudo chmod 755 FTP-shared and edit your proftpd.conf file like that if it fit to your need sudo gedit /etc/proftpd.conf or sudo gedit /etc/proftpd/proftpd.conf sudo /etc/init.d/proftpd start ``` These steps are from this very helpful [thread](http://ubuntuforums.org/showthread.php?t=79588) on ubuntuforums.org
22,528,853
I have a data frame with alternating columns that I want to reshape. The problem is that `stats::reshape` and `reshape2::reshape` are both very slow and memory intensive on my actual use case. I suspect that the no-copy approach of `data.table` will save me time and use less resources, but I barely know where to start with the syntax (previous related efforts [1](https://stackoverflow.com/q/16494665/1036500), [2](https://stackoverflow.com/q/16494665/1036500)). Here's an example of how my data frame is structured: ``` set.seed(4) dt <- data.frame(names = letters[1:10], one = rep(23,10), two = sample(1000,10), three = sample(10,10), onea = rep(24,10), twoa = sample(1000,10), threea = sample(10,10), oneb = rep(25,10), twob = sample(1000,10), threeb = sample(10,10), onec = rep(26,10), twoc = sample(1000,10), threec = sample(10,10), oned = rep(26,10), twod = sample(1000,10), threed = sample(10,10)) ``` Which looks like this: ``` names one two three onea twoa threea oneb twob threeb onec twoc threec oned 1 a 23 586 8 24 715 6 25 939 4 26 561 4 26 2 b 23 9 3 24 996 3 25 242 7 26 72 6 26 3 c 23 294 1 24 506 8 25 565 8 26 852 10 26 4 d 23 277 7 24 489 5 25 181 6 26 911 3 26 5 e 23 811 9 24 647 9 25 901 5 26 225 5 26 6 f 23 260 6 24 827 7 25 84 3 26 626 8 26 7 g 23 721 4 24 480 2 25 896 1 26 69 2 26 8 h 23 900 2 24 836 4 25 886 10 26 512 9 26 9 i 23 942 5 24 510 1 25 718 2 26 799 1 26 10 j 23 73 10 24 526 10 25 560 9 26 964 7 26 twod threed 1 911 2 2 709 10 3 571 5 4 915 9 5 899 3 6 59 1 7 46 4 8 982 7 9 205 8 10 921 6 ``` Here's what I'm currently doing with `stats::reshape` which takes a long time and uses a lot of memory on my actual use case: ``` df_l <- stats::reshape(dt, idvar='names', varying=list(ones = colnames(dt[seq(from=2, to=ncol(dt), by=3)]), twos = colnames(dt[seq(from=4, to=ncol(dt), by=3)])), direction="long") ``` Here's the desired output (I don't care about any of the `three` columns): ``` df_l names two twoa twob twoc twod time one three a.1 a 586 715 939 561 911 1 23 8 b.1 b 9 996 242 72 709 1 23 3 c.1 c 294 506 565 852 571 1 23 1 d.1 d 277 489 181 911 915 1 23 7 e.1 e 811 647 901 225 899 1 23 9 f.1 f 260 827 84 626 59 1 23 6 g.1 g 721 480 896 69 46 1 23 4 h.1 h 900 836 886 512 982 1 23 2 i.1 i 942 510 718 799 205 1 23 5 j.1 j 73 526 560 964 921 1 23 10 a.2 a 586 715 939 561 911 2 24 6 b.2 b 9 996 242 72 709 2 24 3 c.2 c 294 506 565 852 571 2 24 8 d.2 d 277 489 181 911 915 2 24 5 e.2 e 811 647 901 225 899 2 24 9 f.2 f 260 827 84 626 59 2 24 7 g.2 g 721 480 896 69 46 2 24 2 h.2 h 900 836 886 512 982 2 24 4 i.2 i 942 510 718 799 205 2 24 1 j.2 j 73 526 560 964 921 2 24 10 a.3 a 586 715 939 561 911 3 25 4 b.3 b 9 996 242 72 709 3 25 7 c.3 c 294 506 565 852 571 3 25 8 d.3 d 277 489 181 911 915 3 25 6 e.3 e 811 647 901 225 899 3 25 5 f.3 f 260 827 84 626 59 3 25 3 g.3 g 721 480 896 69 46 3 25 1 h.3 h 900 836 886 512 982 3 25 10 i.3 i 942 510 718 799 205 3 25 2 j.3 j 73 526 560 964 921 3 25 9 a.4 a 586 715 939 561 911 4 26 4 b.4 b 9 996 242 72 709 4 26 6 c.4 c 294 506 565 852 571 4 26 10 d.4 d 277 489 181 911 915 4 26 3 e.4 e 811 647 901 225 899 4 26 5 f.4 f 260 827 84 626 59 4 26 8 g.4 g 721 480 896 69 46 4 26 2 h.4 h 900 836 886 512 982 4 26 9 i.4 i 942 510 718 799 205 4 26 1 j.4 j 73 526 560 964 921 4 26 7 a.5 a 586 715 939 561 911 5 26 2 b.5 b 9 996 242 72 709 5 26 10 c.5 c 294 506 565 852 571 5 26 5 d.5 d 277 489 181 911 915 5 26 9 e.5 e 811 647 901 225 899 5 26 3 f.5 f 260 827 84 626 59 5 26 1 g.5 g 721 480 896 69 46 5 26 4 h.5 h 900 836 886 512 982 5 26 7 i.5 i 942 510 718 799 205 5 26 8 j.5 j 73 526 560 964 921 5 26 6 ``` How can I do this with `data.table`?
2014/03/20
[ "https://Stackoverflow.com/questions/22528853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1036500/" ]
You could either do it this way ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.newapp.Firstscreen$PlaceholderFragment" > <ImageView android:id="@+id/imageView1" android:layout_width="match_paren" android:layout_height="match_paren" android:scaleType="fitXY" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:src="@drawable/background" /> </RelativeLayout> ``` OR ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:background="@drawable/background" tools:context="com.example.newapp.Firstscreen$PlaceholderFragment" > <!-- CONTENT HERE --> </RelativeLayout> ```
5,077,070
I have a scenario where my Java program has to continuously communicate with the database table, for example my Java program has to get the data of my table when new rows are added to it at runtime. There should be continuous communication between my program and database. If the table has 10 rows initially and 2 rows are added by the user, it must detect this and return the rows.
2011/02/22
[ "https://Stackoverflow.com/questions/5077070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/399944/" ]
With HSQLDB, this is supported without continuous polling. HSQLDB TRIGGERs support synchronous or asynchronous notifications to be sent by the trigger event. The target may be the user's app or any other app. See <http://hsqldb.org/doc/2.0/guide/triggers-chapt.html>
7,114,082
I'm using django to do a pixel tracker on an email Is it easy to return an actual image from a django view (and how would this be done?) or is it easier to just return a redirect to the url where the actual image lives?
2011/08/18
[ "https://Stackoverflow.com/questions/7114082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/443722/" ]
You don't need an actual image for a tracker pixel. In fact, it's better if you don't have one. Just use the view as the source for the image tag, and have it return a blank response.
12,917,001
I have this site : <http://test.tamarawobben.nl> What's the best way to achieve that the footer will always be on the bottom of the screen?
2012/10/16
[ "https://Stackoverflow.com/questions/12917001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692026/" ]
CSS for the footer ``` footer { position:absolute; bottom:0; width:100%; height:60px; /* Height of the footer */ background:#6cf; } ``` Full article on this : [How to keep footers at the bottom of the page](http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page)
49,674,318
I've noticed that in PHP the following code works with no complaints: ``` class A { public static function echoes($b) { echo $b->protectedFunction(); } } class B extends A { protected function protectedFunction() { return "this is protected"; } } $b = new B(); A::echoes($b); ``` Example <https://3v4l.org/JTpuQ> However I've tried this in C# and it does not work as the parent cannot access the child protected members. My question is who's got the OOP principles right here? I've read through the LSP but it doesn't seem concerned with parent classes, so is it correct for a parent to access child protected members (like PHP assumes it is) or should it be restricted (like C# assumes it should be)?
2018/04/05
[ "https://Stackoverflow.com/questions/49674318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/487813/" ]
The way that C# restricts access seems to be the most logical way to do it. A parent should not be able to inherit anything from a child. And without inheriting anything from the child, the parent should not have access to the child's protected methods.
69,737,525
I am working on a form in React e-commerce project. Here's how it should work: When user fills up the form and clicks the submit button I want to post the form data to a server and redirect the user to a confirmation/thank you page. Unfortunately, when I fill up the form and click the submit button the following code works in a specific way: 1st click - it sends the data but "setSubmitted(true)" doesn't work so I am not redirected 2nd click - is sends the data again, setSubmitted works and I am redirected Could you tell me how to fix the code? ``` let history = useHistory(); const [submitted, setSubmitted] = useState(false); const handleSubmit = (e) => { e.preventDefault(); fetch('http://localhost:8000/orders', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ cart: 1 }), //dummy data }) .then((response) => { setSubmitted(true); return response.json(); }) .then(() => { if (submitted) { return history.push('/thank-you-page'); } }); }; return ( <form onSubmit={handleSubmit}> ... </form> ); ```
2021/10/27
[ "https://Stackoverflow.com/questions/69737525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15278400/" ]
You can loop over each key value pair and replace the value if its empty. Be aware that a backslash is used for escaping a character. To fix this we first replace the backslashes with dashes and then replace the rest. The regex could also be simplified to `/[^-|]/g` which means replace all symbols except `-` and `|` ```js const lines = { "part": "Intro", "e": "------5/6-----8\\6-|-------------------|-------------------", "B": "-----------9-------|---------6p8---(6)-|-------------------", "G": "--8----------------|---8h9-------------|--<8>--------------", "D": "", "A": "", "E": "", "endMsg": "Continue..." }; const createFullLines = (lines, blacklist = ['part', 'endMsg']) => { // Find a line that is not empty const line = Object.entries(lines).find(([key, line]) => { return !blacklist.includes(key) && line.trim(); }); // Exit if all lines are empty if(!line) return lines; // Destructure to get only value const [_, filledLine] = line; // Create new line with only dashes const newLine = filledLine.replace(/[^-|]/g, '-'); // Update lines for(const key in lines) { lines[key] ||= newLine; } return lines; } const result = createFullLines(lines); console.log(result); ```
269,379
I am using the `fp` package to write a coursework in mechanics **and** calculate the numerical values on the fly. Here is some example code: ``` \documentclass{article} \usepackage[nomessages]{fp} % http://ctan.org/pkg/fp \begin{document} \section{Requirements} \FPset{P_output_kW}{11} \FPset{n_output_max_rpm}{5000} P_output_kW = \FPprint{P_output_kW} kW n_output_max_rpm = \FPprint{n_output_max_rpm} rpm \end{document} ``` As is evident, I am attempting to print every assigned variable by name, value and measurement unit. First of all, the above code does not compile with the error: ``` ! Missing $ inserted. ``` I would like to invoke into a single command (with a single parameter) the two operations: * print variable name, followed by `=` * print variable value How can that be achieved?
2015/09/24
[ "https://tex.stackexchange.com/questions/269379", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/45581/" ]
The following sets the variable name in typewriter font, the number via `\FPprint` and the unit is taken from the variable name: ``` \documentclass{article} \usepackage[nomessages]{fp} % http://ctan.org/pkg/fp \newcommand*{\VarOutput}[1]{% \begingroup \fontencoding{T1}% \fontfamily{lmvtt}\selectfont % variable typewriter font % alternative: \ttfamily \detokenize{#1}% make _ to character \endgroup ~=~% \FPprint{#1}% \,% \ExtractUnit{#1}% } \newcommand*{\ExtractUnit}[1]{% \expandafter\ExtractUnitAux\detokenize{#1_}\relax } \begingroup \catcode`\_=12 % \gdef\ExtractUnitAux#1_#2\relax{% \ifx\\#2\\% #1 \else \ExtractUnitAux#2\relax \fi } \endgroup \begin{document} \section{Requirements} \FPset{P_output_kW}{11} \FPset{n_output_max_rpm}{5000} \VarOutput{P_output_kW}\\ \VarOutput{n_output_max_rpm} \end{document} ``` > > [![Result](https://i.stack.imgur.com/3QRTo.png)](https://i.stack.imgur.com/3QRTo.png) > > >
969,824
I'm trying to set up a brand-new Epson WorkForce WF-3640 printer and it seems there are some weird mechanical issues. It would seem the carriage is not moving freely. This is *before* I get to install the ink cartridges. The printer may make a loud grinding noise and return errors 0xF1, 0xEA, 0xE8, or 0xE1. Alternatively, the printer may report a paper jam when there is no paper in the paper path at all. Any ideas? --- It seems the carriage is getting stuck on a movable plastic clip at the front right end of the unit or is not engaging correctly at the right end. Why would this be happening?
2015/09/08
[ "https://superuser.com/questions/969824", "https://superuser.com", "https://superuser.com/users/73918/" ]
### 0xE8 and later 0xEA codes > > There is a blue tape on the interior that needs to be removed- once I did this it worked fine. > > > ... > > I had the same issue: 0xE8 and later 0xEA codes. I could see that it > was the white moving clip under the ink tank holder when on the far > right that was catching it. The ONLY thing that fixed it was: once it > made a noise and errored I unwillingly pushed the tank holder over to > the left until the tanks pushed past the white clip and all the way to > the left.. > > > Then there were no more errors. > > > Source [0xE8 and later 0xEA codes](http://www.askmefast.com/Epson_wf3620__need_resolution_for_error_code_0xE8-qna8892260.html#q6764814) --- ### 520 FATAL CODE:0xF1 EPSON Workforce > > This relates to the print head not being able to completely pass from the left to right side during startup. I had a plastic carriage on the one side that was stuck in a position that stop the carriage from make the complete run from side to side. When I forced the plastic carriage down and it clicked into place the error stopped and the printer started up normally with no codes. > > > If anything is causing the print head to not travel completely from left to right during startup, this will probable cause the code. It will be hard to see if the print head is being obstructed if you don't remove the sides. > > > Source [520 FATAL CODE:0xF1 EPSON Workforce](http://hpprintermanual.blogspot.co.uk/2013/03/520-fatal-code0xf1-epson-workforce.html) --- ### Print Error Code0xE3 and 0xEA > > We have seen some success with this issue by following these > instructions. Please try this procedure one more time using the > instructions below. > > > 1. Turn the printer off, then disconnect the power and the interface cable. Open the cover and check for any torn or jammed paper > and remove it. > 2. Reconnect the power cable and turn the printer back on. > 3. Press the Copy button and see if the unit responds. > > > Note: Also check that the ink cartridges and lids are pushed down > fully. > > > If the issue persists, the hardware itself is malfunctioning and will > require service > > > Source [Print Error Code0xE3 and 0xEA](http://www.fixya.com/support/t25141495-print_error_code0xe3_0xea)
43,830,633
How create query with using CriteriaQuery and EntityManager for this SQL query: ``` SELECT * FROM user WHERE user.login = '?' and user.password = '?' ``` I try so: ``` final CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); final CriteriaQuery<User> criteriaQuery = criteriaBuilder.createQuery(User.class); Root<User> root = criteriaQuery.from(User.class); criteriaQuery.select(root); criteriaQuery.where(criteriaBuilder.gt(root.get("login"), userLogin)); return getEntityManager().createQuery(criteriaQuery).getResultList().get(0); ```
2017/05/07
[ "https://Stackoverflow.com/questions/43830633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7785247/" ]
Your code looks like it's on the right track, except that it only has one `WHERE` condition, which does not agree with your raw SQL query, which has two conditions. ``` CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> q = cb.createQuery(User.class); Root<User> c = q.from(User.class); q.select(c); ParameterExpression<String> p1 = cb.parameter(String.class); ParameterExpression<String> p2 = cb.parameter(String.class); q.where( cb.equal(c.get("login"), p1), cb.equal(c.get("password"), p2) ); return em.createQuery(q).getResultList().get(0); ``` As a side note, in real life you would typically *not* be storing raw user passwords in your database. Rather, you be storing a salted and encrypted password. So hopefully your actual program is not storing raw passwords.
53,452,937
While reading a csv file with PHP a problem occured with a line break within the CSV file. The contents of one cell will be split once a comma is followed by a line break: ``` $csv = array_map('str_getcsv', file($file)); first,second,"third, more,text","forth" next,dataset ``` This will result in: ``` 1) first | second | third 2) more text | forth 3) next | dataset ``` While it should result in: ``` 1) first | second | third more text | forth 2) next | dataset ``` Is this a bug within str\_getcsv?
2018/11/23
[ "https://Stackoverflow.com/questions/53452937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547262/" ]
Don't do that, use [`fgetcsv()`](https://secure.php.net/manual/en/function.fgetcsv.php). You're having problems because `file()` doesn't care about the string encapsulation in your file. ``` $fh = fopen('file.csv', 'r'); while( $line = fgetcsv($fh) ) { // do a thing } fclose($fh); ``` <https://secure.php.net/manual/en/function.fgetcsv.php> And try not to store all the lines into an array before performing your operations if you can help it. Your system's memory usage will thank you.
50,488,474
The data source passed to a report has a `Serial` property, I need to write a field in this format for every details section: [Serial] from [Top serial] I wrote this formula for the top serial: ``` Maximum({VW_Sizes.Serial}) ``` but it gets the current serial, so instead of : 1 of 2, 2 of 2 It gets 1 of 1, 2 of 2.
2018/05/23
[ "https://Stackoverflow.com/questions/50488474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6197785/" ]
The problem you are running into is that when each iteration of the details section prints to the report, it only knows the Max value for SERIAL for the rows that have already printed to the report. I prefer to use a SQL Expression Field to get around this issue. This allows you to use a SQL query to retrieve the maximum value of SERIAL for the grouped data before all of the rows are printed to the report. Something like this usually works for me. ``` ( SELECT MAX("ORD_DETAIL"."ORD_DET_SEQNO") FROM ORD_DETAIL WHERE "ORD_DETAIL"."ORDERS_ID" = "ORDERS"."ID" ) ``` In my example, I have two tables, `ORDERS` and `ORD_DETAIL`. `ORD_DETAIL.ORD_DET_SEQNO` contains the sequence numbers of order detail rows. My data is grouped on `ORDERS.ID` to iterate through each Order and the following formula field would print an output for each detail line that indicates its sequence out of the maximum value of all sequence numbers for that order. ``` ToText({ORD_DETAIL.ORD_DET_SEQNO}) + " of " + ToText({%Max}); ``` In this formula, `%Max` is the name of the SQL Expression Field in the example above. If you have no point in your data where the SERIAL number resets, then your SQL Expression Field would look like this. ``` ( SELECT MAX(Serial) FROM VW_Sizes ) ``` If you need a reset at certain points, simply add a WHERE clause that references the table.column that is used to group a set of SERIAL values.