text
stringlengths
64
81.1k
meta
dict
Q: Why can a socket connect() to its own ephemeral port? I can reliably get a Winsock socket to connect() to itself if I connect to localhost with a port in the range of automatically assigned ephemeral ports (5000–65534). Specifically, Windows appears to have a system-wide rolling port number which is the next port that it will try to assign as a local port number for a client socket. If I create sockets until the assigned number is just below my target port number, and then repeatedly create a socket and attempt to connect to that port number, I can usually get the socket to connect to itself. I first got it to happen in an application that repeatedly tries to connect to a certain port on localhost, and when the service is not listening it very rarely successfully establishes a connection and receives the message that it initially sent (which happens to be a Redis PING command). An example, in Python (run with nothing listening to the target port): import socket TARGET_PORT = 49400 def mksocket(): return socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) while True: sock = mksocket() sock.bind(('127.0.0.1', 0)) host, port = sock.getsockname() if port > TARGET_PORT - 10 and port < TARGET_PORT: break print port while port < TARGET_PORT: sock = mksocket() err = None try: sock.connect(('127.0.0.1', TARGET_PORT)) except socket.error, e: err = e host, port = sock.getsockname() if err: print 'Unable to connect to port %d, used local port %d: %s' % (TARGET_PORT, port, err) else: print 'Connected to port %d, used local port %d' (TARGET_PORT, port) On my Mac machine, this eventually terminates with Unable to connect to port 49400, used local port 49400. On my Windows 7 machine, a connection is successfully established and it prints Connected to port 49400, used local port 49400. The resulting socket receives any data that is sent to it. Is this a bug in Winsock? Is this a bug in my code? Edit: Here is a screenshot of TcpView with the offending connection shown: A: This appears to be a 'simultaneous initiation' as described in #3.4 of RFC 793. See Figure 8. Note that neither side is in state LISTEN at any stage. In your case, both ends are the same: that would cause it to work exactly as described in the RFC.
{ "pile_set_name": "StackExchange" }
Q: Change background color of JTable I have added a table, but the problem is, the panel doesnt show its background color. I have tried setting scrollpane background color, etc. But it doesn't work. The frame has a button 'Verify', which when clicked, displays a table beneath it. Until it is clicked, the portion where the table will appear is solid gray. I want the whole portion to be ivory background. Kindly help me diagnose the problem. try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn1=DriverManager.getConnection("jdbc:odbc:vasantham","",""); Statement st1=conn1.createStatement(); ResultSet rs1=st1.executeQuery("select * from try where DATEDIFF('d',NOW(),exdate) &lt; 61 order by tname"); ResultSetMetaData md1=rs1.getMetaData(); int cols1=md1.getColumnCount(); model1=new DefaultTableModel(); model1.addColumn("Purpose"); model1.addColumn("Name"); model1.addColumn("Composition"); model1.addColumn("Expiry"); model1.addColumn("Stock"); model1.addColumn("Cost"); model1.addColumn("Type"); model1.addColumn("Supplier"); model1.addColumn("Supplier Number"); model1.addColumn("Rack"); table1=new JTable(model1); Color ivory=new Color(255,255,208); table1.setOpaque(false); table1.setBackground(ivory); String[] tabledata1=new String[cols1]; int i=0; while(rs1.next()) { for(i=0;i&lt;cols1;i++) { if(i==3) { Date intr1=(rs1.getDate(i+1)); tabledata1[i]=formatter1.format(intr1); } else tabledata1[i]=rs1.getObject(i+1).toString(); } model1.addRow(tabledata1); } JScrollPane scroll1 = new JScrollPane(table1); scroll1.setBackground(new Color(255,255,208)); scroll1.getViewport().setBackground(ivory); panel1.setLayout(new BorderLayout()); panel1.setBackground(ivory); table1.getTableHeader().setBackground(ivory); panel1.add(scroll1,BorderLayout.CENTER); frame1.add(panel1,BorderLayout.CENTER); conn1.close(); } A: Scroll Panes contain another component, known as the ViewPort. This is actually where the components been assigned to the scroll pane get added. If you want to maintain the JTable as transparent (table1.setOpaque(false);), then you need to change the view ports background scroll1.getViewport().setBackground(ivory); Otherwise, set the table to opaque and table1.setFillsViewportHeight(true); to force the table to fill the entire viewport UPDATED Works fine for me model1 = new DefaultTableModel(); model1.addColumn("Purpose"); model1.addColumn("Name"); model1.addColumn("Composition"); model1.addColumn("Expiry"); model1.addColumn("Stock"); model1.addColumn("Cost"); model1.addColumn("Type"); model1.addColumn("Supplier"); model1.addColumn("Supplier Number"); model1.addColumn("Rack"); for (int index = 0; index < 10; index++) { Vector vector = new Vector(); vector.add("p" + index); vector.add("n" + index); vector.add("c" + index); vector.add("e" + index); vector.add("s" + index); vector.add("c" + index); vector.add("t" + index); vector.add("s" + index); vector.add("s" + index); vector.add("r" + index); model1.addRow(vector); } table1 = new JTable(model1); Color ivory = new Color(255, 255, 208); table1.setOpaque(true); table1.setFillsViewportHeight(true); table1.setBackground(ivory); JScrollPane scroll1 = new JScrollPane(table1); table1.getTableHeader().setBackground(ivory); add(scroll1, BorderLayout.CENTER); You can comment out the row creation section and it will still paint in ivory.
{ "pile_set_name": "StackExchange" }
Q: GridView makes other controls in the same layout invisible in RelativeLayout I have a problem with my Layout design. When I am trying to add a GridView with in a Linearlayout it makes the controls invisible (which are below GridView). My required design is : http://www.imagesup.net/pt-514145877008.png I tried to create it with Relativelayout and used one gridView also. Here is the XML layout file: purchase.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#FFFFFF"> <LinearLayout android:id="@+id/button_area" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:background="#FFFFFF" android:orientation="vertical" android:padding="10dp" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="One Year Subscription" android:textColor="#000000" android:textSize="18sp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:paddingBottom="10dp" android:paddingTop="15dp" android:text="Rs. 500" android:textColor="#000000" android:textSize="18sp" /> <Button android:id="@+id/button_continue" android:layout_width="match_parent" android:layout_height="50dp" android:layout_gravity="right" android:layout_marginBottom="5dp" android:layout_marginTop="5dp" android:background="#FF0000" android:text="Buy" android:textColor="#FFFFFF" > <!-- continue button --> <!-- select All check box --> </Button> </LinearLayout> <View android:layout_width="match_parent" android:layout_height="3dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:background="#CDCDCD"/> <LinearLayout android:id="@+id/monthly_subscription" android:orientation="vertical" android:layout_below="@+id/button_area" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:paddingBottom="10dp" android:paddingTop="15dp" android:text="monthly Subscription" android:textColor="#000000" android:textSize="18sp" /> <TextView android:id="@+id/price_text" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_gravity="right" android:layout_marginRight="5dp" android:layout_weight="1" android:gravity="right" android:text="Rs 0" android:textColor="#000000" android:textSize="18sp" /> <GridView android:id="@+id/book_grid" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:numColumns="3" android:padding="10dp" tools:listitem="@layout/book_list_item" > </GridView> <Button android:id="@+id/button_continue_bottom" android:layout_width="match_parent" android:layout_height="50dp" android:layout_gravity="right" android:layout_margin="10dp" android:layout_marginBottom="5dp" android:layout_marginTop="10dp" android:background="#FF0000" android:text="Buy" android:textColor="#FFFFFF" > </Button> </LinearLayout> </RelativeLayout> Here What I got when I tried with this code, and also included the result when I tried by setting the Visibility of GridView to "gone" http://www.imagesup.net/pm-314145913100.png What is wrong with my design? what makes the controls invisible.? please help me to setup it as my required layout. A: You should put your bottom button outside the linear layout. Try this code: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#FFFFFF> <!-- Align to parent top--> <LinearLayout android:id="@+id/button_area" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:background="#FFFFFF" android:gravity="center" android:orientation="vertical" android:padding="10dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="One Year Subscription" android:textColor="#000000" android:textSize="18sp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:paddingBottom="10dp" android:paddingTop="15dp" android:text="Rs. 500" android:textColor="#000000" android:textSize="18sp" /> <Button android:id="@+id/button_continue" android:layout_width="match_parent" android:layout_height="50dp" android:layout_gravity="right" android:layout_marginBottom="5dp" android:layout_marginTop="5dp" android:background="#FF0000" android:text="Buy" android:textColor="#FFFFFF"> <!-- continue button --> <!-- select All check box --> </Button> </LinearLayout> <!-- layout below top linearlayout--> <View android:id="@+id/line" android:layout_width="match_parent" android:layout_height="3dp" android:layout_below="@+id/button_area" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:background="#CDCDCD" /> <!-- layout below line view but above bottom button--> <LinearLayout android:id="@+id/monthly_subscription" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_above="@+id/button_continue_bottom" android:layout_below="@+id/line" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:paddingBottom="10dp" android:paddingTop="15dp" android:text="monthly Subscription" android:textColor="#000000" android:textSize="18sp" /> <TextView android:id="@+id/price_text" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_gravity="right" android:layout_marginRight="5dp" android:layout_weight="1" android:gravity="right" android:text="Rs 0" android:textColor="#000000" android:textSize="18sp" /> <GridView android:id="@+id/book_grid" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:numColumns="3" android:padding="10dp" android:stretchMode="columnWidth" tools:listitem="@layout/book_list_item"></GridView> </LinearLayout> <!-- layout outside of linear layout and align to parent bottom--> <Button android:id="@+id/button_continue_bottom" android:layout_width="match_parent" android:layout_height="50dp" android:layout_alignParentBottom="true" android:layout_margin="10dp" android:layout_marginBottom="5dp" android:layout_marginTop="10dp" android:background="#FF0000" android:text="Buy" android:textColor="#FFFFFF" /> </RelativeLayout>
{ "pile_set_name": "StackExchange" }
Q: VirtualBox Sound is Skippy Under Windows 7/Windows 7 I've setup VirtualBox to run a Windows 7 Guest under a Windows 7 host. I get sound, but it's "skippy" and/or clackling when I listen to music on Winamp or Media Player Classic. Haven't tried other players yet. The setup was done as follows: Installed a VirtualBox on my machine. Created a new Windows 7 VM. Set it up to have 1936 MB (RAM) and 64 MB (VIDEO), and a HD of 20GB. Installed Windows 7 N from a clean install under the VM. After Windows installed, I've run Windows Update. Got all fixes available and made sure it installed Realtek AC97 drivers. Installed VirtualBox extensions on the Guest. Installed Winamp on the VM, and copied a few mp3 files to the guest in order to test it. That's when I've found out that the sound wasn't working properly. Not sure if this is a common or a very specific problem, does anyone experienced anything similar on a Windows Guest or even on a Linux Guest? A: Yeah... that happens. You're running a machine on a machine, and there is a ton of overhead, not to mention issues with CPU priority for your virtual machine and what not. Also, that is a lot of RAM on a VM... how much do you have on your PC? This is a very common issue. At least in Winamp, you can increase the buffer for sound card playback. I'd imagine you can do the same in Windows Media Player. This may help you, but keep in mind that the sound card is software controlled as well.
{ "pile_set_name": "StackExchange" }
Q: Look for a cleaner way to perform this searching function Given that there are 2 classes A and B. They both get an integer attribute , ID. Now you have an arrayA which contains all classes A object and an arrayB which contains all classes B object. What is the best or cleaner way to select the objects in arrayB which has the same id as the object in arrayA? (Someone suggests intersection. I think this complies faster but the code looks not nice) Here is the sample code: NSMutableArray *resultArray = [NSMutableArray array]; for (ClassB *bObject in arrayB) { for (ClassA *aObject in arrayA) { if ([bObject ID] == [aObject ID]) { [resultArray addObject:bObject]; break; } } } A: The simplest approach is to (a) build an array of ID values; and then (b) use that a predicate: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ID IN %@", [arrayA valueForKey:@"ID"]]; NSArray *results = [arrayB filteredArrayUsingPredicate:predicate]; See the Predicate Programming Guide.
{ "pile_set_name": "StackExchange" }
Q: Bootstrap tooltip need to be in single line I have created a tooltip using bootstrap for dropdown control. It shows the tooltip. But since this control is binded inside class="col-sm-4" tooltip text is broken to new lines. But I expect to show this in a single line. Any idea to make this? <div class="col-sm-4"> <select class="form-control" id="ddlSchoolAttended" data-toggle="tooltip" data-placement="right" title="Some tooltip 2!Some tooltip 2!Some "> <option value="08">08 -Year 8 or below</option> <option value="09">09 -Year 9 or equivalent</option> <option value="10">10 -Completed Year 10</option> <option value="11">11 -Completed Year 11</option> <option value="12">12 -Completed Year 12</option> <option selected="selected" value="">--Not Specified--</option> </select><br/> </div> A: .tooltip-inner { white-space:nowrap; max-width:none; } Add this to your CSS after the Bootstrap CSS. However, using the hover on a right, even right auto, will be off screen on smaller viewports, but since smaller viewports are generally touch, hovers may make this require a double tap to work. I usually use a script to detect touch for IOS, Android, and Windows mobile and then only use the tooltip on no-touch devices, so this doesn't interfere with user taps. A: Although Christina's answer works, it only patches the problem and may create other problems elswhere. In the bootstrap documentation it is mentioned this: Tooltips in button groups, input groups, and tables require special setting When using tooltips on elements within a .btn-group or an .input-group, or on table-related elements, you'll have to specify the option container: 'body' to avoid unwanted side effects (such as the element growing wider and/or losing its rounded corners when the tooltip is triggered). see Bootstrap docs so all you need to do is add container: 'body' like so: $(function () { $('[data-toggle="tooltip"]').tooltip({container: 'body'})} ); hope this helps
{ "pile_set_name": "StackExchange" }
Q: eclipse GetAnnotation returns @NonNull I am trying to use the Eclipse org.eclipse.jdt.annotation.NonNull annotations and i don't understand this method signature: @NonNull MyAnnotation java.lang.reflect.Field.getAnnotation(Class<@NonNull MyAnnotation> annotationClass) for loop: if(field.getAnnotation(MyAnnotation.class)!=null) continue; Eclipse declares the following code dead code try{ Why does eclipse think the getAnnotation class returns @NonNull? The docs clearly state it can return null. I have verified via a debugger that the code is not dead, stepping trough. EDIT: I do not use @NonNullByDefault on any package I tried: adding @Nullable to MyAnnotation, i get The nullness annotation 'Nullable' is not applicable at this location @Nullable MyAnnotation n=field.getAnnotation(MyAnnotation.class); still same problem A: Got rid of the warning by adding the first line: Class<MyAnnotation> c = MyAnnotation.class; if(field.getAnnotation(c)!=null) continue; After that i do not get the dead code warning. Somehow Eclipse is adding the @NonNull annotation automatically to MyAnnotation.
{ "pile_set_name": "StackExchange" }
Q: state_focused didn't work on checkbox I tried the following link But state_focused didn't work. checkbox_selector.xml <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/checked" android:state_checked="true"/> <item android:drawable="@drawable/unchecked" android:state_checked="false"/> <item android:state_checked="true" android:state_focused="false" android:drawable="@drawable/unchecked_focus"/> <item android:state_checked="false" android:state_focused="true" android:drawable="@drawable/unchecked_focus" /> </selector> In my class, I add like this. cbx.setButtonDrawable(R.drawable.checkbox_selector); First is unchecked state, second is focused state and last is for checked state. I have also tried android:state_pressed but it didn't work. Is there another way to do it? Thanks. A: from the docs: During each state change, the state list is traversed top to bottom and the first item that matches the current state is used—the selection is not based on the "best match," but simply the first item that meets the minimum criteria of the state. so your item will be shown in either "checked" or "not checked" state, is it what you see?
{ "pile_set_name": "StackExchange" }
Q: When does `make` apply the implicit rule `Makefile: Makefile.o`? In my working directory, there is a makefile, an empty obj folder and a src folder that contains foo.c. I have a simple rule that takes an object file, substitutes everything until the first slash with src and replaces the ending .o with .c. Example: obj/foo.o --> src/foo.c With the help of MadScientist (credits to him) I obtained the pattern rule below (Please do not propose easier rules --> I am aware of their existance, but only this rule demonstrates my problem): OBJFILES=obj/foo.o all: $(OBJFILES) @echo "all executed" Y = $(shell echo $1 | sed -e 's,^[^\/]*,src,' -e 's,\.o$$,.c,') .SECONDEXPANSION: %.o: $$(call Y,$$@) @echo "OBJECTS executed for $@ - [$^]" src/foo.c: @echo "Congrats" Once I run the above makefile, I get a circular dependency: xxxx@null:~/Desktop/experiment$ make make: Circular src.o <- src dependency dropped. OBJECTS executed for obj/foo.o - [src/foo.c] all executed The reason is found quickly: Make creates the implicit rule Makefile: Makefile.o, which triggers my pattern rule. Since Makefile.o does not contain a slash, sed evaluates to src. Make again applies the implicit rule src:src.o which eventually causes the circular dependency. This can be seen in the make output: make --print-data-base | grep src make: Circular src.o <- src dependency dropped. OBJECTS executed for obj/foo.o - [src/foo.c] Y = $(shell echo $1 | sed -e 's,^[^\/]*,src,' -e 's,\.o$$,.c,') # src (device 64769, inode 14031369): No files, no impossibilities so far. Makefile.o: src src: src.o # Implicit/static pattern stem: 'src' src.o: # Implicit/static pattern stem: 'src' # @ := src.o # * := src # < := src.o obj/foo.o: src/foo.c # + := src/foo.c # < := src/foo.c # ^ := src/foo.c # ? := src/foo.c src/foo.c: If we now redefine Y in that way: Y = $(patsubst obj/%.o,src/%.c,$1), no circular dependency occurs, because make doesn't even try to apply the implicit rule Makefile:Makefile.o make --print-data-base | grep src OBJECTS executed for obj/foo.o - [src/foo.c] Y = $(patsubst obj/%.o,src/%.c,$1) # src (device 64769, inode 14031369): No files, no impossibilities so far. obj/foo.o: src/foo.c # + := src/foo.c # < := src/foo.c # ^ := src/foo.c # ? := src/foo.c src/foo.c: When does make create the implicit rule Makefile: Makefile.o? What is the difference between the two different definitions of Y? A: The first thing is, if you're going to use secondary expansion it's your responsibility to ensure that the result is correct. In pattern rules that means your expansion has to handle all different values of %. Here your problem is fundamentally that you're not properly handling values of % that don't contain slashes, but your target %.o will apply to all targets, not just targets in a subdirectory. You need to fix your sed invocation. One option would be: Y = $(shell echo $1 | sed -e 's,^[^\/]*/,src/,' -e 's,\.o$$,.c,') By adding the slash that substitution won't match a simple filename. The replacement of the .o with .c will still happen however. The reason you see this behavior is because make tries to remake makefiles. So it wants to build a target Makefile. There is a built-in pattern rule that knows how to build an executable from an object file with the same name: % : %.o The Makefile matches % so make tries to build Makefile.o. It sees your pattern rule %.o and tries to apply it and in the second expansion it converts Makefile.o to src as discussed above. So, in addition to the above there are other things you can consider: If you have a sufficiently new version of make (and you define all your own rules) you can disable all built-in rules by adding: MAKEFLAGS += -r This is a good idea regardless since it allows make to run much faster by removing all built-in rules. Second, you could change your pattern to be more specific so it will only match object files, like this: obj/%.o: $$(call Y,$$@) ... Now, this pattern rule will only match .o files in that subdirectory.
{ "pile_set_name": "StackExchange" }
Q: ASP.NET AJAX pageLoad() with multiple Updatepanels Greetings, I'm working with some guys who are developing an app with Update Panels. I'd like to use the jQuery datepicker on a textfield that is part of a row that can be added multiple times via this update panel, and I've got the JavaScript below to work successfully: function pageLoad(sender, args) { if(args.get_isPartialLoad()) { $(".datepicker").datepicker({ //rebind to all step datepickers duration: '' }); } } However, there are multiple update panels on this page so it's being trigged when they all update - is there a way to add a parameter or similar so this only fired when that specific event is needed? Thanks, Chris A: PageRequestManager's pageLoaded event has more information. The args has a get_panelsUpdated and get_panelsCreated (for nested update panels) property. You could use that to determine which UpdatePanels have updated. You could probably just pass the update panel'd div itself into the jquery selector to filter to only elements within it.
{ "pile_set_name": "StackExchange" }
Q: Asp.Net GridView order data bound columns before declarative ones I have a gridview that is databound to a XmlDataSource. I also want to add a <columns> section with a buttonfield at the end of the gridview. When I add a columns section it prepends it (before xml columns). How could I order <asp:XmlDataSource ID="xmlDataSource1" runat="server" datafile="some.xml" TransformFile="some.xslt" /> <asp:GridView ID="linksGrid" runat="server" DataSourceID="xmlDataSource1" CssClass="adminGrid" AllowPaging="True" AlternatingRowStyle-BackColor="WhiteSmoke"> <Columns> <asp:ButtonField runat="server" ButtonType="Button" Text="details" /> </Columns> </asp:GridView> this produces a table like this: I want the order to be reversed: Title, Url, Button column bones question, how could I space the columns so the modify button has no weight (fits to column) and the remaining cells to get even space? A: The code below will surely help you. <asp:GridView ID="MyGridView" runat="server" ShowFooter="True"> <Columns> <asp:TemplateField > <FooterTemplate > <asp:Button ID="MyButton" runat="server" Text="Click Me"/> </FooterTemplate> </asp:TemplateField> </Columns> </asp:GridView>
{ "pile_set_name": "StackExchange" }
Q: Avoid file_get_contents of a file giving me headers before the contents I've created a file with file_put_contents() with a text "En un lugar de la mancha". I want to get that file from another php using file_get_contents and (for instance) print the output. The problem is that I'm getting also the headers: Content-type: text/html X-Powered-By: PHP/4.3.9 En un lugar de la Mancha Why? I just want to get the contents of the file..How can I avoid it? I've tried with file() but with the same result (first two elements of the array are headers) A: Those are not the headers of the file, but part of the text. Chances are you added the headers to the file content when used file_put_content (headers are sent by the server, they are not part of the file itself).
{ "pile_set_name": "StackExchange" }
Q: Check for same rows in a while loop and put them in a separate table I would want to first check for all equal rows and then put them into a separate table. This is what I have done so far: table1 | id | name | | 1 | JUS | | 1 | NUM | | 2 | SET | /** * this is the the query for retrieving the data * from table1 */ $query="SELECT id, name FROM table1 order by id"; $results=$db->query($query); $previous=''; while($row=mysqli_fetch_assoc($results)){ $id=$row['id']; $name=$row['name']; if($id==$previous){ /** * This is where i am stucked up */ $current=''; } $previous=$id; } I want to get the id with 1 as the value into one html table, like below first html table ID | 1 | 1 | Name | JUS | NUM | and also get the id with 2 as the value into another html table. So in all we will get separate tables if the id are not the same: second html table ID | 2 | Name | SET | Any idea as to how to go about it is appreciated. A: You could just gather all them first in a container, using ids as your keys so that they'll be grouped together. After that, just print them accordingly: $data = array(); while($row = $results->fetch_assoc()){ $id = $row['id']; $name = $row['name']; $data[$id][] = $name; // group them } foreach($data as $id => $values) { // each grouped id will be printed in each table echo '<table>'; // header echo '<tr>'; echo '<td>ID</td>' . str_repeat("<td>$id</td>", count($values)); echo '</tr>'; echo '<tr>'; echo '<td>Name</td>'; foreach($values as $value) { echo "<td>$value</td>"; } echo '</tr>'; echo '</table><br/>'; } This will work if those fields are just like that, if you need something more dynamic, you need another dimension, and instead of just pushing name, you'll need the push the entire row: $results = $db->query('SELECT id, name, age FROM table1'); $data = array(); while($row = $results->fetch_assoc()){ $id = $row['id']; unset($row['id']); $data[$id][] = $row; // group them } $fields = array('name', 'age'); foreach($data as $id => $values) { // each grouped id will be printed in each table echo '<table>'; // header echo '<tr>'; echo '<td>ID</td>' . str_repeat("<td>$id</td>", count($values)); echo '</tr>'; foreach($fields as $field) { // construct td $temp = ''; echo "<tr><td>$field</td>"; for($i = 0; $i < count($values); $i++) { $temp .= '<td>' . $values[$i][$field] . '</td>'; } echo $temp; // constructed td echo '</tr>'; } echo '</table><br/>'; }
{ "pile_set_name": "StackExchange" }
Q: Bind to an expression to evaluate With JavaFX2 I have this code: FXMLLoader loader = new FXMLLoader(App.class.getResource("App.fxml")); TabPane tabPane = (TabPane) loader.getNamespace().get("tabPane"); Tab tab = (Tab) loader.getNamespace().get("closeAllTab"); Now I'm looking to disable tab when tabPane has less than 3 tabs (tabs can be closed). I need a binding like this: tab.disableProperty().bind(tabPane.disableProperty()); but, of course, I need to evaluate tabPane.getTabs().size(). How to do this ? A: You should consider using ObservableList bindings: tabPane.getTabs().addListener(new ListChangeListener() { public void onChanged(ListChangeListener.Change<? extends E> c) { tabPane.setDisabled(tabPane.getSize() < 3); } }); Java 8 form: tabPane.getTabe().addListener(e -> tabPane.setDisabled(tabPane.getSize() < 3));
{ "pile_set_name": "StackExchange" }
Q: How to store multiple values into an array and then to DB? I am doing a billing software in C#. I need to get and store multiple values from dataGridView into an array and then into Database. I need to store all of those values as a single value into the "invoice" column. I got some coding, but it not helping me. string[,] invoice = new string[dataGridView1.Rows.Count, dataGridView1.Columns.Count]; foreach (DataGridViewRow row in dataGridView1.Rows) { foreach (DataGridViewColumn col in dataGridView1.Columns) { invoice[row.Index, col.Index] = dataGridView1.Rows[row.Index].Cells[col.Index].Value.ToString(); } } Also i have a button within the datagridview so the above code have some issues with it "Object reference not set to an instance of an object" Any help is appreciated. A: Assuming the Invoice field is a varchar field you can build a string with all values and store that result: var sb = new StringBuilder(); foreach (DataGridViewRow row in dataGridView1.Rows) { sb.Append('<'); foreach (DataGridViewColumn col in dataGridView1.Columns) { sb.Append(dataGridView1.Rows[row.Index].Cells[col.Index].Value); sb.Append(' '); } sb.Append('>'); } var toInvoiceField = sb.ToString();
{ "pile_set_name": "StackExchange" }
Q: set empty text behavior for django-tables2 Some columns in my django table happened to be empty and as a result the text rendered there is 'None'. I would like to see a blank space instead. django tables2 has some documentation on the subject, but I don't understand it completely. Where do I have to define this empty_text behavior parameter? Tried in the relevant class meta, but apparently it has no effect. A: You can override the default value in your column definition. If you are not explicitly declaring your column (for example you are letting tables2 figure it out from your model) then you will have to define it so that you can set options for it. It is ok to do that with data coming from models.. as long as the column name you define matches the model field name it will match them up. class TableClass(tables.Table): mycolumn = tables.Column(default=' ') If you need to dynamically work out your default value on a row-by-row basis then define your column and pass empty_values=[], eg: class TableClass(tables.Table): mycolumn = tables.Column(empty_values=[]) This tells tables2 that it should not consider any values to be 'empty'.. you can then declare a custom rendering method for that column: def render_mycolumn(value): # This is a very simplified example, you will have to work out your # own test for blankness, depending on your data. And, if you are # returning html, you need to wrap it in mark_safe() if not value: return 'Nobody Home' return value Keep in mind that render_ methods are not called if tables2 thinks the value is blank hence you must also set empty_values=[]. Here is the tables2 documentation which describes how custom render methods work: http://django-tables2.readthedocs.org/en/latest/pages/custom-rendering.html?highlight=empty#table-render-foo-method
{ "pile_set_name": "StackExchange" }
Q: Why is my onclick event not working? <script> function clear() { document.getElementById('Div1').style.display = 'block'; document.getElementById('Div2').style.display = 'none'; } </script> <div id="Div1"> <p>hi</p> </div> <div id="Div2"> <p>bye</p> </div> <button type="button" onclick="return clear()" id="Refresh"> While clicking the refresh button, I need to show "hi", but my script function is not working. I'm trying to hide Div2 and to show Div1, but nothing happens. A: There's an old deprecated function, document.clear, that you appear to be clashing with. The current spec defines this as: The clear(), captureEvents(), and releaseEvents() methods must do nothing. If you use clear2 for instance, it works as expected. A better, more modern approach, would be to move your script block after your HTML content, and using an event listener to hook up to the click event, that way you don't even need a function name: <div id="Div1"> <p>hi</p> </div> <div id="Div2"> <p>bye</p> </div> <button type="button" id="Refresh">Click</button> <script> document.getElementById('Refresh').addEventListener('click', function() { document.getElementById('Div1').style.display = 'block'; document.getElementById('Div2').style.display = 'none'; }); </script> In case it's not obvious, we put the script block after the HTML content so that when the script runs during page load, the getElementById('Refresh') is able to find the <button>. If the script block was at the top, when the code runs the button wouldn't exist in the page, and it would fail to find it.
{ "pile_set_name": "StackExchange" }
Q: When is there a newer version of Samba 4? Can someone tell me when Ubuntu comes with a newer version of there samba 4 package. The current version is samba 4.3.11-Ubuntu. When I look at the Samba site, this version is EOL, and already as of 2017-03-11. A: You are on 14.04 or 16.04 (both use 4.3.11). Those 2 will never receive a newer version; they will only get patched (that means it gets updated but the version number will never change) if there is a security issue. You have at least 2 options to get a newer version: 17.10 uses 4.6.7; 18.04 will use 4.7.3 You can use the samba team nightly to install the newest version. sudo add-apt-repository ppa:samba-team/ppa sudo apt-get update to add the PPA.
{ "pile_set_name": "StackExchange" }
Q: Using lodash or a similar library, how do you sort collections by closest result? I have an array of objects and I'm filtering our these objects based on the user input. Now what I'd like to do is sort the objects by closest matching. _internalSearch = (input) => { const { data } = this.props; const filteredData = _.filter(data, (collection) => { const subCollection = _.pick(collection, ["name", "alias"]; return _.includes( subCollection.toString().toLowerCase(), input.toString().toLowerCase() ); }); //psudo code: /** return _.sortBy( items-by-closest-matching-search ) */ } Where data looks something like: [ { "id": 2, "name": "Guide", "url": "http://gify.net", "alias": "Maps" }, { "id": 0, "name": "Summa", "alias": "Fun Town" }, { "id": 1, "name": "Mars", "url": "https://funstuff.org", "alias": "Dentist" } ] Now if the input is ma all three results show, which is good, but I would like to sort these results by closest-matching by name. So the results would be in the order: Mars, Summa, Guide I guess the process would be: 1) Sort alphabetically (optional) 2) Sort on "alias" by distance of substring from start of string 3) Sort on "name" by distance of substring from start of string A: I was able to figure it out myself. The solution is pretty simple. I ended up caring to sort the aliases and found that sorting on name was plenty. Sorting on aliases increased my computational complexity for, in my use case, practically no gain. sortResults = (data, input) => { _.sortBy(data, [ ({ name }) => { const index = name.indexOf(input); return index === -1 ? Number.MAX_SAFE_INTEGER : index; } ]); };
{ "pile_set_name": "StackExchange" }
Q: ScriptExitException after tests pass in grails 2.3.8 Edit: I can no longer reproduce this issue. The root cause remains a mystery to me. When running grails test-app on a very small sample project with 2 unit tests, the tests all PASS but I get an error message afterwards: grails> test-app | Running without daemon... ............................................... |Compiling 1 source files . |Running 2 unit tests... |Running 2 unit tests... 1 of 2 |Running 2 unit tests... 2 of 2 |Completed 2 unit tests, 0 failed in 0m 7s ................. |Tests PASSED - view reports in C:\src\grails238-test\target\test-reports Picked up _JAVA_OPTIONS: -Duser.home=C:\Users\rmorrise -Xms128M -Xmx512M -XX:PermSize=128M -XX:MaxPe rmSize=384M | Error Error running script test-app: org.codehaus.groovy.grails.cli.ScriptExitException (Use --sta cktrace to see the full trace) If it's an error in my code, can anyone give me a hint of what to look for? --stacktrace output and test Spec code follow. | Error Error running script test-app --stacktrace: org.codehaus.groovy.grails.cli.ScriptExitExcepti on (NOTE: Stack trace has been filtered. Use --verbose to see entire trace.) org.codehaus.groovy.grails.cli.ScriptExitException at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:133) at _GrailsTest_groovy$_run_closure1.doCall(_GrailsTest_groovy:98) at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:133) at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall( GantBinding.groovy:185) at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall( GantBinding.groovy) at org.codehaus.gant.GantBinding.withTargetEvent(GantBinding.groovy:90) at org.codehaus.gant.GantBinding.this$4$withTargetEvent(GantBinding.groovy) at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16.doCall(GantBindin g.groovy:185) at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16.doCall(GantBindin g.groovy) at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:133) at TestApp$_run_closure1.doCall(TestApp.groovy:32) at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:133) at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall( GantBinding.groovy:185) at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall( GantBinding.groovy) at org.codehaus.gant.GantBinding.withTargetEvent(GantBinding.groovy:90) at org.codehaus.gant.GantBinding.this$4$withTargetEvent(GantBinding.groovy) at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16.doCall(GantBindin g.groovy:185) at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16.doCall(GantBindin g.groovy) at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381) at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415) at gant.Gant$_dispatch_closure7.doCall(Gant.groovy) at gant.Gant.withBuildListeners(Gant.groovy:427) at gant.Gant.this$2$withBuildListeners(Gant.groovy) at gant.Gant$this$2$withBuildListeners$2.callCurrent(Unknown Source) at gant.Gant$this$2$withBuildListeners$2.callCurrent(Unknown Source) at gant.Gant.dispatch(Gant.groovy:415) at gant.Gant.this$2$dispatch(Gant.groovy) at gant.Gant.invokeMethod(Gant.groovy) at gant.Gant.executeTargets(Gant.groovy:591) at gant.Gant.executeTargets(Gant.groovy:590) | Error Error running script test-app --stacktrace: org.codehaus.groovy.grails.cli.ScriptExitExcepti on Here are my two test specs: BookSpec: package grails238.test import grails.test.mixin.TestFor import spock.lang.Specification /** * See the API for {@link grails.test.mixin.domain.DomainClassUnitTestMixin} for usage instructions */ @TestFor(Book) class BookSpec extends Specification { def setup() { } def cleanup() { } void "test foo"() { when: domain.title = "Foo" then: domain.title == "Foo" } } BookControllerSpec: package grails238.test import grails.test.mixin.TestFor import spock.lang.Specification /** * See the API for {@link grails.test.mixin.web.ControllerUnitTestMixin} for usage instructions */ @TestFor(BookController) class BookControllerSpec extends Specification { def setup() { } def cleanup() { } void "test foo"() { when: "index" controller.index() then: "expect nothing" controller.response.contentAsString == "Hello World" } } A: With grails 2.3.5 and 2.3.8 on windows, this can be fixed by editing "scripts/_GrailsTest.groovy". Line 97: if(exitCode != null) { should be replaced with if(exitCode != null && exitCode != 0) { Reference: https://jira.grails.org/browse/GRAILS-10809
{ "pile_set_name": "StackExchange" }
Q: To prove that for $\alpha \in \mathbb{Z}_p$, $\alpha^{p^n} \equiv \alpha^{p^{n-1}}\ \text{mod}p^n$ for all $n \in \mathbb{N}$ I have to show that for $\alpha \in \mathbb{Z}_p$, $\alpha^{p^n} \equiv \alpha^{p^{n-1}}\ \text{mod}p^n$ for all $n \in \mathbb{N}$. I tried using mathematical induction, but I end up with something like $\alpha^{p^n} = (\alpha^{p^{n-1}})^p \equiv (\alpha^{p^{n-2}})^p \text{mod}p^{n-1} = \alpha^{p^{n-1}} \text{mod}p^{n-1} $ But clearly I'm missing something. Can I get some help? This is a part of Question 19 in the first Exercise of Koblitz's book on p-adic analysis A: This can be proved using the following lemma: Suppose $\alpha, \beta \in \mathbb{Z}_p$, and $n \ge 1$. If $\alpha \equiv \beta \pmod{p^n}$, then $\alpha^p \equiv \beta^p \pmod{p^{n+1}}$. Proof: $\alpha^p - \beta^p = (\alpha-\beta) (\alpha^{p-1} + \alpha^{p-2} \beta + \cdots + \beta^{p-1})$. Now by hypothesis, $p^n \mid \alpha - \beta$; but also, since $n \ge 1$, we have $\alpha \equiv \beta \pmod{p}$, so then $\alpha^{p-1} + \alpha^{p-2} \beta + \cdots + \beta^{p-1} \equiv p \alpha^{p-1} \equiv 0 \pmod{p}$, so $p \mid \alpha^{p-1} + \alpha^{p-2} \beta + \cdots + \beta^{p-1}$. Now, to apply this to an inductive proof of the desired statement: for $n=1$ it reduces to $\alpha^p \equiv \alpha \pmod{p}$ which is just Fermat's little theorem. For the inductive step, applying the lemma to the inductive hypothesis $\alpha^{p^n} \equiv \alpha^{p^{n-1}} \pmod{p^n}$ pretty much gives directly that $\alpha^{p^{n+1}} \equiv \alpha^{p^n} \pmod{p^{n+1}}$.
{ "pile_set_name": "StackExchange" }
Q: If $\int_0^xf(t)dt=[f(x)]^2$ but $f(x)\neq 0$, what is $f(x)$? From the problems plus in Stewart Calculus 6e, it asks if $f$ is a differentiable function such that $f(x)$ is never $0$ and for any $x$, $\int_0^xf(t)dt=[f(x)]^2$, then what is $f(x)$? I figured since it's differentiable I could take the derivative of both sides to get: $$f(x)=2f(x)f'(x)$$ Since $f(x)$ is never $0$, then $f'(x)=1/2$. But that means that $f(x)=x/2+c$, which will equal $0$ for $x=-2c$. I can't just take $0$ out of the function, since it has to be differentiable everywhere. So how do I solve this problem? A: I believe that you have misread the problem. I think when it says $f(x) \neq 0$ means that $f(x)$ is not the zero function (i.e. it is not always zero). Otherwise you seem to have solved the problem. EDIT: I just read your comment. I think your book either has a misprint or the correct answer is "there is no solution". When $x=0$, we get $0=f(0)^2$ so $f(0)=0$, so no matter what $f(x)$ must equal $0$ at some point.
{ "pile_set_name": "StackExchange" }
Q: Upgrading Ruby installation on Mac OS running Snow Leopard 10.6.5 I have a Mac Os running Snow Leopard 10.6.5 and I am trying to upgrade my Ruby installation. Before I did anything, I run the following commands and I had the following results: $ ruby -v ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] $ which ruby /usr/bin/ruby So, to upgrade my installation, I installed first macports and then Ruby using Ruby Version Manager (RVM). 1. bash < <(curl http://rvm.beginrescueend.com/releases/rvm-install-head) 2. mkdir -p ~/.rvm/src/ && cd ~/.rvm/src && rm -rf ./rvm/ && git clone --depth 1 git://github.com/wayneeseguin/rvm.git && cd rvm && ./install 3. rvm install 1.9.2 4. rvm 1.9.2 --default After that, I run the following commands and I had the following results: $ ruby -v ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] $ which ruby /usr/bin/ruby $ rvm list => ruby-1.9.2-p136 [ x86_64 ] Why Ruby is still at 1.8.7? What is wrong? Or, what I forgot? A: SOLVED: Edit the '.profile' file in home directory: Add the line at the bottom: export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$PATH" and then in the Terminal run source ~/.profile to set the changes.
{ "pile_set_name": "StackExchange" }
Q: Opal file called from client via getsctipt (or xhr'ed and evaled) can't be evaled and used I want to xhr some opal script, and use ruby code defined there. I tried to get it with $.getScript. But no success for me. $.ajax({ url: 'assets/foo.js.rb', success: function(data){ #{ClassInFooJs.new} }, dataType: "script" }); Moreover the script is evaled (in strange manner), I mean I can call Opal.modules["file_i_required"] from console, and it will return basically the compiled code. BUT inside of it nothing is evaled, (no console.logs, window["foos"] = #{something}), and I can't reference anything from that file. Any help? A: You should use either require "foo" from Opal or Opal.require("foo") from JavaScript. If the load "foo" behavior is required should be noted that Opal.load("foo") is also present. The alternative is to compile files on the server with the :requirable flag set to false but that's kinda difficult unless you compile manually. See the API docs for more info. Calling directly Opal.modules["foo"](Opal) should be avoided as it doesn't properly update $LOADED_FEATURES and in general can change in the future.
{ "pile_set_name": "StackExchange" }
Q: Can I use Visual Studio Community edition for testing projects? I've started doing test automation for my employer with Visual studio express but very soon realized that it does not have good plugin support. Now i'm planning to move away from it and after reading about Community version I think this is the best option to go. However, I'm not really sure on the licensing terms, it does say that I can't use it for commercial purposes but I'm just doing test automation for my employer which I'm sure will not be sold, does it still gets counted as commercial development ? If not then can I use Visual studio Community version ? A: From the website: An unlimited number of users within an organization can use Visual Studio Community for the following scenarios: in a classroom learning environment, for academic research, or for contributing to open source projects. For all other usage scenarios: In non-enterprise organizations, up to five users can use Visual Studio Community. In enterprise organizations (meaning those with >250 PCs or >$1 Million US Dollars in annual revenue), no use is permitted beyond the open source, academic research, and classroom learning environment scenarios described above. So you're allowed to use it in an enterprise if you're contributing to open source, research or teaching; or are a company with less than 250 PCs and under $1,000,000 in revenue and there are fewer than 5 users working with it
{ "pile_set_name": "StackExchange" }
Q: pause/play ffmp3 with JavaScript? There is an Open Source mp3 player that is flash based. I was wondering if anyone knew how to pause and play it using javascript. Here is a working example of it, but I can't necessarily figure out how it is being done. http://sightofnick.com/public/ffmp3/test-skin.html A: For the player: <object id="theIdOfThePlayer" ...> ... <embed name="theIdOfThePlayer"> ... Get the player like this: var player=(document.theIdOfThePlayer) ? document.theIdOfThePlayer : document.getElementById('theIdOfThePlayer'); Pause like this: player.stopSound(); Start like this: player.playSound();
{ "pile_set_name": "StackExchange" }
Q: SKPhysicsBody objects collisions are not aligned I have a player. He has to jump over some blocks. However, it seems like the SKPhysicsBody(rectangleOfSize: ... ) isn't aligned properly. When the character hits the upper half of the block it just passes through and he can't pass below it because it collides with an invisible SKPhysicsBody. Depending on how I put the anchor point it sometimes even happens that the physics body is to the left or right of it's SKSpriteNode. My code for the blocks: self.smallBlock.anchorPoint = CGPointMake(0.5, 0.5) self.smallBlock.position = CGPointMake(CGRectGetMaxX(self.frame) + self.smallBlock.size.width, CGRectGetMinY(self.frame) + self.runningBar.size.height * 2) self.smallBlock.physicsBody = SKPhysicsBody(rectangleOfSize: self.smallBlock.size) self.smallBlock.physicsBody?.dynamic = false self.smallBlock.physicsBody?.categoryBitMask = colliderType.Block.rawValue self.smallBlock.physicsBody?.contactTestBitMask = colliderType.Character.rawValue self.smallBlock.physicsBody?.collisionBitMask = colliderType.Character.rawValue self.smallBlock.physicsBody?.usesPreciseCollisionDetection = true self.addChild(self.smallBlock) self.character.anchorPoint = CGPointMake(0, 0.25) self.character.position = CGPointMake(CGRectGetMinX(self.frame) - self.character.size.width, CGRectGetMinY(self.frame) + self.character.size.height) self.initPosX = CGRectGetMinX(self.frame) + (self.character.size.width * 1.25) Code for the character self.character.anchorPoint = CGPointMake(0, 0.25) self.character.position = CGPointMake(CGRectGetMinX(self.frame) - self.character.size.width, CGRectGetMinY(self.frame) + self.character.size.height) self.initPosX = CGRectGetMinX(self.frame) + (self.character.size.width * 1.25) self.character.physicsBody = SKPhysicsBody(rectangleOfSize: self.character.size) self.character.physicsBody?.affectedByGravity = true self.character.physicsBody?.categoryBitMask = colliderType.Character.rawValue self.character.physicsBody?.contactTestBitMask = colliderType.Block.rawValue self.character.physicsBody?.collisionBitMask = colliderType.Block.rawValue self.character.physicsBody?.usesPreciseCollisionDetection = true self.character.physicsBody?.affectedByGravity = true self.character.physicsBody?.allowsRotation = false self.addChild(self.character) A: Solution: I've added skView.showsPhysics = true to my View Controller. When you run the app in the simulator it will outline every object like shown here. It turns out setting custom anchor points messes up the rectangleOfSize-positions.
{ "pile_set_name": "StackExchange" }
Q: iOS Keyword Spotting I would like to implement keyword spotting for 6 words in my app. I have downloaded Openears, but the recognition accuracy is very poor (just tapping on the table returns one of the 6 predefined words). Are there any other open source alternatives to OpenEars or a way to increase the accuracy of Openears? (The 6 words I am using are in english) A: Openears is just fine, you only need to know that for keyword spotting you can not use the default configuration, you need to install Rejecto Plugin specifically designed for keyword spotting task.
{ "pile_set_name": "StackExchange" }
Q: Facebook Prophet: Providing different data sets to build a better model My data frame looks like that. My goal is to predict event_id 3 based on data of event_id 1 & event_id 2 ds tickets_sold y event_id 3/12/19 90 90 1 3/13/19 40 130 1 3/14/19 13 143 1 3/15/19 8 151 1 3/16/19 13 164 1 3/17/19 14 178 1 3/20/19 10 188 1 3/20/19 15 203 1 3/20/19 13 216 1 3/21/19 6 222 1 3/22/19 11 233 1 3/23/19 12 245 1 3/12/19 30 30 2 3/13/19 23 53 2 3/14/19 43 96 2 3/15/19 24 120 2 3/16/19 3 123 2 3/17/19 5 128 2 3/20/19 3 131 2 3/20/19 25 156 2 3/20/19 64 220 2 3/21/19 6 226 2 3/22/19 4 230 2 3/23/19 63 293 2 I want to predict sales for the next 10 days of that data: ds tickets_sold y event_id 3/24/19 20 20 3 3/25/19 30 50 3 3/26/19 20 70 3 3/27/19 12 82 3 3/28/19 12 94 3 3/29/19 12 106 3 3/30/19 12 118 3 So far my model is that one. However, I am not telling the model that these are two separate events. However, it would be useful to consider all data from different events as they belong to the same organizer and therefore provide more information than just one event. Is that kind of fitting possible for Prophet? # Load data df = pd.read_csv('event_data_prophet.csv') df.drop(columns=['tickets_sold'], inplace=True, axis=0) df.head() # The important things to note are that cap must be specified for every row in the dataframe, # and that it does not have to be constant. If the market size is growing, then cap can be an increasing sequence. df['cap'] = 500 # growth: String 'linear' or 'logistic' to specify a linear or logistic trend. m = Prophet(growth='linear') m.fit(df) # periods is the amount of days that I look in the future future = m.make_future_dataframe(periods=20) future['cap'] = 500 future.tail() forecast = m.predict(future) forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail() fig1 = m.plot(forecast) A: Start dates of events seem to cause peaks. You can use holidays for this by setting the starting date of each event as a holiday. This informs prophet about the events (and their peaks). I noticed event 1 and 2 are overlapping. I think you have multiple options here to deal with this. You need to ask yourself what the predictive value of each event is related to event3. You don't have too much data, that will be the main issue. If they have equal value, you could change the date of one event. For example 11 days earlier. The unequal value scenario could mean you drop 1 event. events = pd.DataFrame({ 'holiday': 'events', 'ds': pd.to_datetime(['2019-03-24', '2019-03-12', '2019-03-01']), 'lower_window': 0, 'upper_window': 1, }) m = Prophet(growth='linear', holidays=events) m.fit(df) Also I noticed you forecast on the cumsum. I think your events are stationary therefor prophet probably benefits from forecasting on the daily ticket sales rather than the cumsum.
{ "pile_set_name": "StackExchange" }
Q: Certian links can't be clicked unless the page height is short I am learning bootstrap 4. I have a page with left navbar. The links point to paragraphs within the same page. The left nav stays in view all the time. The problem is: When the browser window's HEIGHT is in full screen, desktop mode, two of the links at the bottom can't be clicked-on from the left navbar (links for items: Item 3-2 and Item 4-2)-That is, one can't place the mouse over the link to click it. All other links work fine. When the browser window is made shorter in height manually, this problem goes away and I can click all the links. What is causing the problem in full-screen desktop mode? I guess this class is causing the issue - But I am not sure. .bd-example { position: -webkit-sticky; /* is it this? */ position: sticky; top: .5rem; height: calc(100vh - .5rem); overflow-y: auto; padding-top: .5rem; padding-bottom: .5rem; font-size: .875rem; display: inline-block; } Code as a document: page HTML and CSS code file I placed the code in jsFiddle: https://jsfiddle.net/ekareem/aq9Laaew/250605/ However, one needs to make the result page hight tall enough to observe the problem. Thanks. A: That's because the elements you're trying to scroll to are too short and the last ones fit all on a single screen. To fix this, you need to allow your page to actually scroll to them (place the item it scrolls to at the top of the page). In the example below, I'm using "the poor man's fix" - padding-bottom:100vh to the container - so you can see it working properly: .row { background: #f8f9fa; margin-top: 20px; } .col { border: solid 1px #6c757d; padding: 10px; } .bd-example { position: -webkit-sticky; position: sticky; top: .5rem; height: calc(100vh - .5rem); overflow-y: auto; padding-top: .5rem; padding-bottom: .5rem; font-size: .875rem; display: inline-block; /* could cause a slider when short vitewport */ } [data-target="#navbar-example3"] { padding-bottom: 100vh; } <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <div class="container"> <div class="row"> <div class="col"> 1 of 2 </div> <div class="col"> 2 of 2 </div> </div> <div class="row"> <div class="col"> 1 of 3 </div> <div class="col"> 2 of 3 </div> <div class="col"> 3 of 3 </div> </div> </div> <body data-spy="scroll" data-target=".bd-example"> <div class="container"> <div class="row"> <div class="col-4"> <div class="bd-example"> <nav id="navbar-example3" class="navbar navbar-dark bg-light"> <nav class="nav nav-pills flex-column"> <a class="navbar-brand" href="#" style="color:black;">Test</a> <a class="nav-link" href="#item-1">Item 1</a> <ul class="nav nav-pills flex-column"> <a class="nav-link ml-3 my-1" href="#item-1-1">Item 1-1</a> <a class="nav-link ml-3 my-1" href="#item-1-2">Item 1-2</a> </ul> <a class="nav-link" href="#item-2">Item2</a> <a class="nav-link" href="#item-3">Item3</a> <ul class="nav nav-pills flex-column"> <a class="nav-link ml-3 my-1" href="#item-3-1">Item 3-1</a> <a class="nav-link ml-3 my-1" href="#item-3-2">Item 3-2</a> </ul> <a class="nav-link" href="#item-4">Item4</a> <ul class="nav nav-pills flex-column"> <a class="nav-link ml-3 my-1" href="#item-4-1">Item 4-1</a> <a class="nav-link ml-3 my-1" href="#item-4-2">Item 4-2</a> </ul> </nav> </nav> </div> </div> <div class="col-8"> <div data-spy="scroll" data-target="#navbar-example3" data-offset="300"> <h4 id="item-1">Item 1</h4> <p>Ex consequat commodo adipisicing exercitation aute excepteur occaecat ullamco duis aliqua id magna ullamco eu. Do aute ipsum ipsum ullamco cillum consectetur ut et aute consectetur labore. Fugiat laborum incididunt tempor eu consequat enim dolore proident. Qui laborum do non excepteur nulla magna eiusmod consectetur in. Aliqua et aliqua officia quis et incididunt voluptate non anim reprehenderit adipisicing dolore ut consequat deserunt mollit dolore. Aliquip nulla enim veniam non fugiat id cupidatat nulla elit cupidatat commodo velit ut eiusmod cupidatat elit dolore. </p> <h5 id="item-1-1">Item 1-1</h5> <p>Amet tempor mollit aliquip pariatur excepteur commodo do ea cillum commodo Lorem et occaecat elit qui et. Aliquip labore ex ex esse voluptate occaecat Lorem ullamco deserunt. Aliqua cillum excepteur irure consequat id quis ea. Sit proident ullamco aute magna pariatur nostrud labore. Reprehenderit aliqua commodo eiusmod aliquip est do duis amet proident magna consectetur consequat eu commodo fugiat non quis. Enim aliquip exercitation ullamco adipisicing voluptate excepteur minim exercitation minim minim commodo adipisicing exercitation officia nisi adipisicing. Anim id duis qui consequat labore adipisicing sint dolor elit cillum anim et fugiat. </p> <h5 id="item-1-2">Item 2-2</h5> <p>Cillum nisi deserunt magna eiusmod qui eiusmod velit voluptate pariatur laborum sunt enim. Irure laboris mollit consequat incididunt sint et culpa culpa incididunt adipisicing magna magna occaecat. Nulla ipsum cillum eiusmod sint elit excepteur ea labore enim consectetur in labore anim. Proident ullamco ipsum esse elit ut Lorem eiusmod dolor et eiusmod. Anim occaecat nulla in non consequat eiusmod velit incididunt. </p> <h4 id="item-2">Item 2</h4> <p>Quis magna Lorem anim amet ipsum do mollit sit cillum voluptate ex nulla tempor. Laborum consequat non elit enim exercitation cillum aliqua consequat id aliqua. Esse ex consectetur mollit voluptate est in duis laboris ad sit ipsum anim Lorem. Incididunt veniam velit elit elit veniam Lorem aliqua quis ullamco deserunt sit enim elit aliqua esse irure. Laborum nisi sit est tempor laborum mollit labore officia laborum excepteur commodo non commodo dolor excepteur commodo. Ipsum fugiat ex est consectetur ipsum commodo tempor sunt in proident. </p> <h4 id="item-3">Item 3</h4> <p>Quis anim sit do amet fugiat dolor velit sit ea ea do reprehenderit culpa duis. Nostrud aliqua ipsum fugiat minim proident occaecat excepteur aliquip culpa aute tempor reprehenderit. Deserunt tempor mollit elit ex pariatur dolore velit fugiat mollit culpa irure ullamco est ex ullamco excepteur. </p> <h5 id="item-3-1">Item 3-1</h5> <p>Deserunt quis elit Lorem eiusmod amet enim enim amet minim Lorem proident nostrud. Ea id dolore anim exercitation aute fugiat labore voluptate cillum do laboris labore. Ex velit exercitation nisi enim labore reprehenderit labore nostrud ut ut. Esse officia sunt duis aliquip ullamco tempor eiusmod deserunt irure nostrud irure. Ullamco proident veniam laboris ea consectetur magna sunt ex exercitation aliquip minim enim culpa occaecat exercitation. Est tempor excepteur aliquip laborum consequat do deserunt laborum esse eiusmod irure proident ipsum esse qui. </p> <h5 id="item-3-2">Item 3-2</h5> <p>Labore sit culpa commodo elit adipisicing sit aliquip elit proident voluptate minim mollit nostrud aute reprehenderit do. Mollit excepteur eu Lorem ipsum anim commodo sint labore Lorem in exercitation velit incididunt. Occaecat consectetur nisi in occaecat proident minim enim sunt reprehenderit exercitation cupidatat et do officia. Aliquip consequat ad labore labore mollit ut amet. Sit pariatur tempor proident in veniam culpa aliqua excepteur elit magna fugiat eiusmod amet officia. </p> <h4 id="item-4">Item 4</h4> <p>Ex consequat commodo adipisicing exercitation aute excepteur occaecat ullamco duis aliqua id magna ullamco eu. Do aute ipsum ipsum ullamco cillum consectetur ut et aute consectetur labore. Fugiat laborum incididunt tempor eu consequat enim dolore proident. Qui laborum do non excepteur nulla magna eiusmod consectetur in. Aliqua et aliqua officia quis et incididunt voluptate non anim reprehenderit adipisicing dolore ut consequat deserunt mollit dolore. Aliquip nulla enim veniam non fugiat id cupidatat nulla elit cupidatat commodo velit ut eiusmod cupidatat elit dolore. </p> <h5 id="item-4-1">Item 4-1</h5> <p>Amet tempor mollit aliquip pariatur excepteur commodo do ea cillum commodo Lorem et occaecat elit qui et. Aliquip labore ex ex esse voluptate occaecat Lorem ullamco deserunt. Aliqua cillum excepteur irure consequat id quis ea. Sit proident ullamco aute magna pariatur nostrud labore. Reprehenderit aliqua commodo eiusmod aliquip est do duis amet proident magna consectetur consequat eu commodo fugiat non quis. Enim aliquip exercitation ullamco adipisicing voluptate excepteur minim exercitation minim minim commodo adipisicing exercitation officia nisi adipisicing. Anim ix duis qui consequat labore adipisicing sint dolor elit cillum anim et fugiat. </p> <h5 id="item-4-2">Item 4-2</h5> <p>Cillum nisi deserunt magna eiusmod qui eiusmod velit voluptate pariatur laborum sunt enim. Irure laboris mollit consequat incididunt sint et culpa culpa incididunt adipisicing magna magna occaecat. Nulla ipsum cillum eiusmod sint elit excepteur ea labore enim consectetur in labore anim. Proident ullamco ipsum esse elit ut Lorem eiusmod dolor et eiusmod. Anim occaecat nulla in non consequat eiusmod velit incididunt. </p> </div> </div> </div> </div> Other, more elaborate options include: adding any element after your content that would have a minimum height of 100vh minus the height of your last element (a nice, tall, footer, perhaps?) - if you can't think of anything else, simply put <div> with (min-height: 100vh; background: url('link-to-nice-picture' no-repeat 50% 50% /cover), and a "Thank you" fineprint message centered at its bottom. Example: .row { background: #f8f9fa; margin-top: 20px; } .col { border: solid 1px #6c757d; padding: 10px; } .bd-example { position: -webkit-sticky; position: sticky; top: .5rem; height: calc(100vh - .5rem); overflow-y: auto; padding-top: .5rem; padding-bottom: .5rem; font-size: .875rem; display: inline-block; /* could cause a slider when short vitewport */ } .bottom-message { background: url(https://static.boredpanda.com/blog/wp-content/uploads/2014/08/cat-looking-at-you-black-and-white-photography-1.jpg) no-repeat bottom center /cover; min-height: 100vh; display: flex; align-items: flex-end; justify-content: center; } .bottom-message em{ font-family: initial; font-size: 1.5rem; } <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <body data-spy="scroll" data-target=".bd-example"> <div class="container"> <div class="row"> <div class="col"> 1 of 2 </div> <div class="col"> 2 of 2 </div> </div> <div class="row"> <div class="col"> 1 of 3 </div> <div class="col"> 2 of 3 </div> <div class="col"> 3 of 3 </div> </div> </div> <div class="container"> <div class="row"> <div class="col-4"> <div class="bd-example"> <nav id="navbar-example3" class="navbar navbar-dark bg-light"> <nav class="nav nav-pills flex-column"> <a class="navbar-brand" href="#" style="color:black;">Test</a> <a class="nav-link" href="#item-1">Item 1</a> <ul class="nav nav-pills flex-column"> <a class="nav-link ml-3 my-1" href="#item-1-1">Item 1-1</a> <a class="nav-link ml-3 my-1" href="#item-1-2">Item 1-2</a> </ul> <a class="nav-link" href="#item-2">Item2</a> <a class="nav-link" href="#item-3">Item3</a> <ul class="nav nav-pills flex-column"> <a class="nav-link ml-3 my-1" href="#item-3-1">Item 3-1</a> <a class="nav-link ml-3 my-1" href="#item-3-2">Item 3-2</a> </ul> <a class="nav-link" href="#item-4">Item4</a> <ul class="nav nav-pills flex-column"> <a class="nav-link ml-3 my-1" href="#item-4-1">Item 4-1</a> <a class="nav-link ml-3 my-1" href="#item-4-2">Item 4-2</a> </ul> </nav> </nav> </div> </div> <div class="col-8"> <div data-spy="scroll" data-target="#navbar-example3" data-offset="300"> <h4 id="item-1">Item 1</h4> <p>Ex consequat commodo adipisicing exercitation aute excepteur occaecat ullamco duis aliqua id magna ullamco eu. Do aute ipsum ipsum ullamco cillum consectetur ut et aute consectetur labore. Fugiat laborum incididunt tempor eu consequat enim dolore proident. Qui laborum do non excepteur nulla magna eiusmod consectetur in. Aliqua et aliqua officia quis et incididunt voluptate non anim reprehenderit adipisicing dolore ut consequat deserunt mollit dolore. Aliquip nulla enim veniam non fugiat id cupidatat nulla elit cupidatat commodo velit ut eiusmod cupidatat elit dolore. </p> <h5 id="item-1-1">Item 1-1</h5> <p>Amet tempor mollit aliquip pariatur excepteur commodo do ea cillum commodo Lorem et occaecat elit qui et. Aliquip labore ex ex esse voluptate occaecat Lorem ullamco deserunt. Aliqua cillum excepteur irure consequat id quis ea. Sit proident ullamco aute magna pariatur nostrud labore. Reprehenderit aliqua commodo eiusmod aliquip est do duis amet proident magna consectetur consequat eu commodo fugiat non quis. Enim aliquip exercitation ullamco adipisicing voluptate excepteur minim exercitation minim minim commodo adipisicing exercitation officia nisi adipisicing. Anim id duis qui consequat labore adipisicing sint dolor elit cillum anim et fugiat. </p> <h5 id="item-1-2">Item 2-2</h5> <p>Cillum nisi deserunt magna eiusmod qui eiusmod velit voluptate pariatur laborum sunt enim. Irure laboris mollit consequat incididunt sint et culpa culpa incididunt adipisicing magna magna occaecat. Nulla ipsum cillum eiusmod sint elit excepteur ea labore enim consectetur in labore anim. Proident ullamco ipsum esse elit ut Lorem eiusmod dolor et eiusmod. Anim occaecat nulla in non consequat eiusmod velit incididunt. </p> <h4 id="item-2">Item 2</h4> <p>Quis magna Lorem anim amet ipsum do mollit sit cillum voluptate ex nulla tempor. Laborum consequat non elit enim exercitation cillum aliqua consequat id aliqua. Esse ex consectetur mollit voluptate est in duis laboris ad sit ipsum anim Lorem. Incididunt veniam velit elit elit veniam Lorem aliqua quis ullamco deserunt sit enim elit aliqua esse irure. Laborum nisi sit est tempor laborum mollit labore officia laborum excepteur commodo non commodo dolor excepteur commodo. Ipsum fugiat ex est consectetur ipsum commodo tempor sunt in proident. </p> <h4 id="item-3">Item 3</h4> <p>Quis anim sit do amet fugiat dolor velit sit ea ea do reprehenderit culpa duis. Nostrud aliqua ipsum fugiat minim proident occaecat excepteur aliquip culpa aute tempor reprehenderit. Deserunt tempor mollit elit ex pariatur dolore velit fugiat mollit culpa irure ullamco est ex ullamco excepteur. </p> <h5 id="item-3-1">Item 3-1</h5> <p>Deserunt quis elit Lorem eiusmod amet enim enim amet minim Lorem proident nostrud. Ea id dolore anim exercitation aute fugiat labore voluptate cillum do laboris labore. Ex velit exercitation nisi enim labore reprehenderit labore nostrud ut ut. Esse officia sunt duis aliquip ullamco tempor eiusmod deserunt irure nostrud irure. Ullamco proident veniam laboris ea consectetur magna sunt ex exercitation aliquip minim enim culpa occaecat exercitation. Est tempor excepteur aliquip laborum consequat do deserunt laborum esse eiusmod irure proident ipsum esse qui. </p> <h5 id="item-3-2">Item 3-2</h5> <p>Labore sit culpa commodo elit adipisicing sit aliquip elit proident voluptate minim mollit nostrud aute reprehenderit do. Mollit excepteur eu Lorem ipsum anim commodo sint labore Lorem in exercitation velit incididunt. Occaecat consectetur nisi in occaecat proident minim enim sunt reprehenderit exercitation cupidatat et do officia. Aliquip consequat ad labore labore mollit ut amet. Sit pariatur tempor proident in veniam culpa aliqua excepteur elit magna fugiat eiusmod amet officia. </p> <h4 id="item-4">Item 4</h4> <p>Ex consequat commodo adipisicing exercitation aute excepteur occaecat ullamco duis aliqua id magna ullamco eu. Do aute ipsum ipsum ullamco cillum consectetur ut et aute consectetur labore. Fugiat laborum incididunt tempor eu consequat enim dolore proident. Qui laborum do non excepteur nulla magna eiusmod consectetur in. Aliqua et aliqua officia quis et incididunt voluptate non anim reprehenderit adipisicing dolore ut consequat deserunt mollit dolore. Aliquip nulla enim veniam non fugiat id cupidatat nulla elit cupidatat commodo velit ut eiusmod cupidatat elit dolore. </p> <h5 id="item-4-1">Item 4-1</h5> <p>Amet tempor mollit aliquip pariatur excepteur commodo do ea cillum commodo Lorem et occaecat elit qui et. Aliquip labore ex ex esse voluptate occaecat Lorem ullamco deserunt. Aliqua cillum excepteur irure consequat id quis ea. Sit proident ullamco aute magna pariatur nostrud labore. Reprehenderit aliqua commodo eiusmod aliquip est do duis amet proident magna consectetur consequat eu commodo fugiat non quis. Enim aliquip exercitation ullamco adipisicing voluptate excepteur minim exercitation minim minim commodo adipisicing exercitation officia nisi adipisicing. Anim ix duis qui consequat labore adipisicing sint dolor elit cillum anim et fugiat. </p> <h5 id="item-4-2">Item 4-2</h5> <p>Cillum nisi deserunt magna eiusmod qui eiusmod velit voluptate pariatur laborum sunt enim. Irure laboris mollit consequat incididunt sint et culpa culpa incididunt adipisicing magna magna occaecat. Nulla ipsum cillum eiusmod sint elit excepteur ea labore enim consectetur in labore anim. Proident ullamco ipsum esse elit ut Lorem eiusmod dolor et eiusmod. Anim occaecat nulla in non consequat eiusmod velit incididunt. </p> </div> </div> </div> </div> <div class="bottom-message"><em>Say cheese...</em></div> </body> reducing the amount of scrollspy elements to a useful number (remember scrollspy's functionality is to allow users to scroll over large amounts of content quickly - so perhaps only adding it to the sections, not sub-sections!?). https://jsfiddle.net/websiter/uodnhqyp/ making each scrollspy section have a height of minumum 100vh, enriching your application with graphics, which are the backbone of compelling, modern design.
{ "pile_set_name": "StackExchange" }
Q: Fragment slide out animation doesn't work I have an android app in which I am loading another Fragment from one fragment on click of a button Fragment fragment = new EditImagesFragment(); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction tran = fragmentManager.beginTransaction(); tran.setCustomAnimations(R.anim.push, R.anim.pop); tran.replace(R.id.content_frame, fragment).addToBackStack(null).commit(); And I have push and pop (slide in and out ) kind of animations defined as follows <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" > <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android" android:duration="500" android:propertyName="x" android:valueFrom="1000" android:valueTo="0" android:valueType="floatType" /> </set> <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" > <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android" android:duration="500" android:propertyName="x" android:valueFrom="0" android:valueTo="-1000" android:valueType="floatType" /> </set> Now when i load fragment it slides in as expected but slide out animation doesn't work when i press back button and try to go back, I am supporting v14 and above API level. Can anybody spot the issue ? Thanks A: Try setCustomAnimations(int enter, int exit, int popEnter, int popExit) instead of setCustomAnimations(int enter, int exit) According to Android documentation, enter and exit animations will not be played on popping from back stack. A: You should use the 4 params method of FragmentTransaction.setCustomAnimations(...) instead of the 2. also, since you use the native fragment api(api 14+), I suppose the animation xmls should be placed in the animator res folder.
{ "pile_set_name": "StackExchange" }
Q: I just want elementary OS 5.0 Juno to work Powered up this morning to be greeted with the GNU Grub screen version 2.02. I chose +Advanced options, then elementary, with Linux 4.15.0-43-generic (recovery mode). After a long list of command lines, it ended with /dev/sda2: UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY. fsck exited with status code 4 done. Failure: File system check of the root filesystem failed. This happened two weeks ago and the tech I took it to was stumped - never seen anything like it before. He found a third "hidden" partial partition. (I run a MacBook Pro mid-2012) He couldn't save any of my files since I first switched to elementary OS. Lost a week's worth of converting and organizing files. Had to reinstall from thumb drive. Is this something from in the first partition? Is this a problem with the Libre Writer in the second partition? elementary OS had been running clean and fast up until this point. This is unacceptable. Help! A: First that "Tech Guy" didn't knew a thing or is lying to you if he never saw a message like that. You can even Google it and you'll find dozens of articles about this, even your exact same issue. The message you saw was a notice from the system that an error on the disk was detected, so it wanted you to run a command manually RUN fsck MANUALLY A fragment from fsck's manual DESCRIPTION fsck is used to check and optionally repair one or more Linux filesystems. filesys can be a device name (e.g. /dev/hdc1, /dev/sdb2), a mount point (e.g. /, /usr, /home), or an ext2 label or UUID specifier (e.g. UUID=8868abf6-88c5-4a83-98b8-bfc24057f7bd or LABEL=root). Normally, the fsck program will try to handle filesystems on different physical disk drives in parallel to reduce the total amount of time needed to check all of them. If no filesystems are specified on the command line, and the -A option is not specified, fsck will default to checking filesystems in /etc/fstab serially. This is equivalent to the -As options. The exit code returned by fsck is the sum of the following conditions: 0 No errors 1 Filesystem errors corrected 2 System should be rebooted 4 Filesystem errors left uncorrected 8 Operational error 16 Usage or syntax error 32 Checking canceled by user request 128 Shared-library error Your exit code was 4, that meant Filesystem errors left uncorrected and was on /dev/sda2 partition You may ask why that happen. Well could be multiple reasons. One of them was probably that the system did not shutdown normally I have to tell you that probably you didn't lose anything, was your "tech guy" stupidity and ignorance that caused that. I can't confirm this 100% because you never tried to fix the disk with the tools in hand. And about the hidden partition, a "tech guy" should know that in a GPT layout installation you will have a hidden partition used for recovery. Is part of the standard and doesn't have any ties with the system you choose to install. Probably that was that "mysterious hidden partition". You can see that this could happen also on Mac OS, almost identically because it's ties with Unix (same command fsck) https://www.howtogeek.com/236978/how-to-repair-disk-and-file-system-problems-on-your-mac/ Solution Follow what it says Run fsck /dev/sda2 (Say yes to everything) or run fsck -fy /dev/sda2 (forcing and saying yes to all automatically) Reboot If the problem persists after you run fsck, that could mean other things, but always go one step at a time. What you meant with "Crapple kernel"?
{ "pile_set_name": "StackExchange" }
Q: async in for loop in node.js without using async library helper classes I am a beginner to node.js. I was trying out the examples from the 'learnyounode' tutorial. I am trying to write a program that takes three url parameters and fetches some data from those urls and displays the returned data in the order in which the urls were provided. var http = require('http'); var bl = require('bl'); var url = []; url[0] = process.argv[2]; url[1] = process.argv[3]; url[2] = process.argv[4]; var data = []; var remaining = url.length; for(var i = 0; i < url.length; i++){ http.get(url[i], function (response){ response.setEncoding('utf8'); response.pipe(bl(function (err, chunk){ if(err){ console.log(err); } else{ data[i] = chunk.toString(); console.log(data[i]); remaining -= 1; if(remaining == 0) { for(var j = 0; j < url.length; j++){ console.log(data[j]); } } } })); }); } I have two console.log statements in the program. The output i get is as follows: It'll be chunder where lets throw a ford. We're going durry where mad as a cooee . Shazza got us some apples with come a strides. Mad as a swag when get a dog up y a roo. It'll be rapt piece of piss as cunning as a trackie dacks. As cross as a bogged with watch out for the boardies. As cunning as a digger fla min lets get some roo bar. As dry as a piker piece of piss he hasn't got a joey. Lets throw a strides mate we're going digger. undefined undefined undefined It seems like the data is correctly fetched and stored in the 'data' array but it still displays undefined. Any idea why this is happening? Thanks in advance! A: This is a very common issue in async programming in node.js or even in the browser. A main issue you have is that the loop variable i will not be what you want it to be some time later when the async callback is called. By then, the for loop will have run to the end of its loop and i will be at the end value for all response callbacks. There are numerous ways to solve this. You can use a closure to close over the i value and make it uniquely available to each callback. var http = require('http'); var bl = require('bl'); var url = []; url[0] = process.argv[2]; url[1] = process.argv[3]; url[2] = process.argv[4]; var data = []; var remaining = url.length; for(var i = 0; i < url.length; i++){ // create closure here to uniquely capture the loop index // for each separate http request (function(index) { http.get(url[index], function (response){ response.setEncoding('utf8'); response.pipe(bl(function (err, chunk){ if(err){ console.log(err); } else{ data[index] = chunk.toString(); console.log(data[index]); remaining -= 1; if(remaining == 0) { for(var j = 0; j < url.length; j++){ console.log(data[j]); } } } })); }); })(i); } If you do much node.js programming, you will find that you probably want to learn how to use promises because they are very, very handy for controlling the flow and sequence of async operations.
{ "pile_set_name": "StackExchange" }
Q: C++ with libtcod not allowing TCODColor type declaration I am attempting to make a simple rouge like game with c++ and libtcod. I am attempting to compile code that declares a col variable with TCODColor TCODColor col; and this is the actual error: error: TCODColor does not name a type The error occues in the header file but I have included the necessary #include "libtcod.h" in the .cpp file. I have no idea why it will not allow me to declare this type. Any ideas? A: You want to include libtcod.hpp not libtcod.h, the latter is for C, not C++ and TCODColor is in the C++ version.
{ "pile_set_name": "StackExchange" }
Q: How do I know (other than hovering over it) how many people are watching a tag? For an example, if I want to get a list of the 500 most watched tags, it would be impractical to check out the tag popup for each one of them. A: According to https://api.stackexchange.com/docs/types/tag , watchers info is deliberately missing from StackExchange web API. Likewise, it's missing from https://stackoverflow.com/tags/{tag}/info and https://stackoverflow.com/questions/tagged/{tag} . So, you're stuck with a scraper, the site doesn't offer any other way. Either hover things with a headless browser, or find an unsupported way to invoke the same functionality/get this info (which is going to break eventually).
{ "pile_set_name": "StackExchange" }
Q: How to make responsive text that isn't too large or too small I'm new to web design. I have a decent understanding of CSS/HTML, but I'm conflicted on how to style fonts to fit mobile devices. Currently I use px to make my fonts larger or smaller on my web pages. However, doing this will make my fonts look very small on high px/inch devices. How can I make my fonts appear legible on these high resolution screens without making them look super small? For example: .thisClass{ font-size:12px; } is what I am used to using. On my laptop it looks fine, but I have no idea how it looks on tablets because I don't own one D: A: Check this out from CSS3... 1vw = 1% of viewport width 1vh = 1% of viewport height 1vmin = 1vw or 1vh, whichever is smaller 1vmax = 1vw or 1vh, whichever is larger h1 { font-size: 5.9vw; } h2 { font-size: 3.0vh; } p { font-size: 2vmin; }
{ "pile_set_name": "StackExchange" }
Q: RESTeasy Name Binding Annotation Error in Eclipse I'm trying to bind a name to a filter in JAX-RS so I can secure some methods in the rest service as the following: Secured Name Binding: @NameBinding @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(value = RetentionPolicy.RUNTIME) public @interface Secured { } Authentication Filter: @Secured @Provider @Priority(Priorities.AUTHENTICATION) public class AuthenticationAgent implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { //do something } } However, eclipse is giving me this error when I'm adding the secured annotation to my filter. There is no JAX-RS application, resource or resource method with this name binding annotation. A: It's not really an error that will stop JAX-RS from working. It's more of just a warning (specific to that editor). Name Binding should only be used when you want to limit the filter to resources classes/methods also annotated with the name binding annotation. If this is the case, then annotate the classes/methods you want to go through that filter. If you want everything to go through the filter, then forget the annotation altogether. Just get rid of it.
{ "pile_set_name": "StackExchange" }
Q: Can't make weld scanning beans I must have missed something but I can't make Weld working ! It's a simple webapp, one servlet, one service (that i'd like to inject in the servlet) here are the files : pom.xml <dependency> <groupId>org.jboss.weld.servlet</groupId> <artifactId>weld-servlet-core</artifactId> <version>2.3.4.Final</version> </dependency> context.xml <Context> <Resource name="BeanManager" auth="Container" type="javax.enterprise.inject.spi.BeanManager" factory="org.jboss.weld.resources.ManagerObjectFactory"/> </Context> my service import javax.enterprise.context.SessionScoped; import javax.inject.Inject; import javax.inject.Named; @Named @SessionScoped public class ServiceTest { public String test(){ return "hello world"; } } my servlet : public class Hello extends HttpServlet { @Inject private ServiceTest service; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Set the response message's MIME type. response.setContentType("text/html;charset=UTF-8"); // Allocate a output writer to write the response message into the network socket. PrintWriter out = response.getWriter(); try { out.println("<!DOCTYPE html>"); // HTML 5 out.println("<html><head>"); out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>"); String title = service.test(); out.println("<title>" + title + "</title></head>"); out.println("<body>"); out.println("<h1>" + title + "</h1>"); // Prints "Hello, world!" out.println("</body></html>"); } finally { out.close(); // Always close the output writer } } } I'm just getting a NPE ... nothing else. here is the starting trace of my Tomcat 7 2016-06-07 22:49:27 DEBUG logging:37 - Logging Provider: org.jboss.logging.Log4jLoggerProvider 2016-06-07 22:49:27 INFO servletWeldServlet:57 - WELD-ENV-001008: Initialize Weld using ServletContainerInitializer 2016-06-07 22:49:27 INFO Version:153 - WELD-000900: 2.3.4 (Final) 2016-06-07 22:49:27 DEBUG Bootstrap:121 - WELD-ENV-000030: Cannot load class using the ResourceLoader: org.jboss.jandex.Index 2016-06-07 22:49:27 DEBUG Bootstrap:121 - WELD-ENV-000030: Cannot load class using the ResourceLoader: org.jboss.jandex.Index 2016-06-07 22:49:27 DEBUG Bootstrap:316 - WELD-ENV-000024: Archive isolation enabled - creating multiple isolated bean archives if needed 2016-06-07 22:49:27 INFO Bootstrap:166 - WELD-ENV-000028: Weld initialization skipped - no bean archive found juin 07, 2016 10:49:27 PM org.apache.coyote.AbstractProtocol start INFOS: Starting ProtocolHandler ["http-bio-8080"] juin 07, 2016 10:49:27 PM org.apache.coyote.AbstractProtocol start INFOS: Starting ProtocolHandler ["ajp-bio-8009"] juin 07, 2016 10:49:27 PM org.apache.catalina.startup.Catalina start INFOS: Server startup in 1127 ms beans.xml (under META-INF) <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"> <scan> </scan> </beans> A: 2016-06-07 22:49:27 INFO Bootstrap:166 - WELD-ENV-000028: Weld initialization skipped - no bean archive found This means Weld did not find any bean archive in your WAR. Note that in a WAR, beans.xml must be named WEB-INF/beans.xml or WEB-INF/classes/META-INF/beans.xml (see also the spec 12.1. Bean archives). I guess that you have META-INF/beans.xml.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to run the injected script without reload? I did a simple auto form filler, by sending info from a created html to the background and then the content script, so the injected script can change the info on the form. I know the content script run once the page is load. I want to know if I can run the content script again, without the need of reloading the page. I got sendRequest function in the content script, that I use to make sure it gets the info, only when the page is ready. It then add the info to the form, and wait for me to send it. In the content script, I added a onRequest and it works (it get the info). but, I don't see the changes on the form, unless I am realoding the page. I want to know if it is possible to do and if it does what subjects should I learn to implent this. I am new to chrome extentions and I am still learning :) in 1 of the pages, I use jQuery, so an answer with jQuery would be good too. A: i found out that if we create a chrome.tabs.sendRequest from background we can use chrome.extestion.onRequest from content script and it will execute every time becuse they both run allmost in the same time. so i did from background: chrome.tabs.query({}, function (tabs) { for (var i = 0; i < tabs.length; i++) { chrome.tabs.sendRequest(tabs[i].id, {...requests u want to send }, function (response) { }); } }); from content script: chrome.extension.onRequest.addListener(function (request, sender, sendRespons) { //get requested info here //call functions. sendResponse({}); //send info back to background page. });
{ "pile_set_name": "StackExchange" }
Q: C - How to Iterate through sub-nodes in a linked list? I have the following program which I'm developing: ... typedef struct node_tag{ int id; char pLabel[10]; struct node_tag *pNext; struct node_tag *pInner; }NODE; ... int main(int argc, char** argv) { NODE *list = create_node("start"); add_node(&list, "MUSIC"); add_node(&list, "VIDEOS"); add_node(&list, "PICTURES"); create_sub_node( &list, "2015" ); // sub node of PICTURES create_sub_node( &list, "Trip" ); // sub node of 2015 print_nodes(list); return (EXIT_SUCCESS); } Output: | |-> [ID:4] PICTURES | |-> [ID:40] 2015 | | |-> [ID:400] Trip | |-> [ID:3] VIDEOS | |-> [ID:2] MUSIC | |-> [ID:1] start | Everything works as I want so far, as can be seen on the output. However I want to implement different methodology of creating sub nodes. What I've got now is very limited as it can only create the depth of 2 sub nodes but I want to have unlimited depth: void create_sub_node( NODE **handle, char* label ) { NODE *new = malloc( sizeof(NODE) ); new->pNext = NULL; new->pInner = NULL; strncpy( new->pLabel , label , strlen(label) +1 ); if( (*handle)->pInner == NULL ) { new->id = (*handle)->id * 10; (*handle)->pInner = new; } else if( (*handle)->pInner->pInner == NULL ) { new->id = (*handle)->pInner->id * 10; (*handle)->pInner->pInner = new; } } I tried implementing while loops that could iterate through inner nodes until they found NULL one and then creating new node. The problem I'm having is that as I iterate through the nodes, the pointer addresses change and I'm left with one big mess that's no longer working. I tried making a copy of all the addresses of inner nodes, but then I wasn't able to re-assign them again. The thing is that I have to add the sub node to the list so I'll be changing various pointer addresses BUT to do that It looks like I need a copy of the list where I could play with it so that the original addresses don't change. How do I iterate through the sub nodes and create new ones so that I don't have to hard-code bunch of IF statements ? A: My C is a bit rusty but: NODE* tail(NODE* list) { if (list == NULL) return NULL; NODE* current = list; while (current->pInner != NULL) { current = current->pInner; } return current; } Then your function becomes: void create_sub_node( NODE **handle, char* label ) { NODE *new = malloc( sizeof(NODE) ); new->pNext = NULL; new->pInner = NULL; strncpy( new->pLabel , label , strlen(label) +1 ); NODE* last = tail((*handle)); new->id = last->id * 10; last->pInner = new; }
{ "pile_set_name": "StackExchange" }
Q: Script timed out before returning headers: wsgi.py on elastic beanstalk I'm trying to deploy a Django application to Elastic Beanstalk. When I visit the page it never loads. The logs say: Script timed out before returning headers: wsgi.py I can ssh into the server and run manage.py runserver and then curl 127.0.0.1:8000 from another terminal, which will return the page successfully. So I'm assuming it must be an issue with the Apache configuration that is set up as a part of Elastic Beanstalk. Here is more of the logs: [pid 15880] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [so:warn] [pid 15880] AH01574: module wsgi_module is already loaded, skipping [auth_digest:notice] [pid 15880] AH01757: generating secret for digest authentication ... [lbmethod_heartbeat:notice] [pid 15880] AH02282: No slotmem from mod_heartmonitor [mpm_prefork:notice] [pid 15880] AH00163: Apache/2.4.9 (Amazon) mod_wsgi/3.4 Python/2.7.5 configured -- resuming normal operations [core:notice] [pid 15880] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [:error] [pid 15881] /opt/python/run/venv/lib/python2.7/site-packages/numpy/oldnumeric/__init__.py:11: ModuleDeprecationWarning: The oldnumeric module will be dropped in Numpy 1.9 [:error] [pid 15881] warnings.warn(_msg, ModuleDeprecationWarning) [:error] [pid 15881] [core:error] [pid 15884] [client 10.248.110.45:58996] Script timed out before returning headers: wsgi.py And my wsgi.py file: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aurora.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Any clues as to what could be causing this? UPDATE: I rebuilt my environment and ran into this issue again. I updated /etc/httpd/conf.d/wsgi.conf to include WSGIApplicationGroup %{GLOBAL} as mentioned here. I am using Scipy, Numpy, and GeoDjango (which uses GDAL). I know GDAL is not entirely thread safe and I'm not sure about the others but I'm assuming it was a thread safety issue. A: UPDATE 8 FEB 2017 Previously my wsgi.conf was only using one process: WSGIDaemonProcess wsgi processes=1 threads=15 display-name=%{GROUP} I upped the processes to something more reasonable and haven't had any issues: WSGIDaemonProcess wsgi processes=6 threads=15 display-name=%{GROUP} This change along with the original addition of WSGIApplicationGroup %{GLOBAL} seems to have done the trick. UPDATE 17 September 2015 I'm still occasionally running in to this issue. Usually, redeploying via eb deploy fixes the issue. It's hard to say what the underlying issue is. Original Answer I eventually got the project working but then tried creating an image to use for new instances, which reopened the problem. I'm not sure why it worked then stopped working but I rebuilt my custom AMI from scratch and then repushed my project. Turns out it was an issue in wsgi.py. The version I posted was actually the different from what was being deployed. For some reason another developer had put this in wsgi.py: path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if path not in sys.path: sys.path.append(path) I removed this and it fixed the problem. My advice for anyone having Script timed out before returning headers: wsgi.py is to check you wsgi.py file. A: It certainly does seem like an issue with WSGI and Apache like you mentioned. One thing to double check is the .ebextensions file in your source directory. There should be a config in there that specifies the WSGI information like the location of the application. You might also want to check your Django settings and run it locally with an Apache setup using WSGI. You've probably already read the official documentation for WSGI and Django, but this might catch some simplistic things that you might have missed: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Python_django.html#create_deploy_Python_django_update A: Just my 2 cents on a similar issue I faced. I had a similar problem. It turned out to be that the script (which makes a DB insert/update/delete call) being executed from django application was waiting in a deadlock state for the lock on the table to be released. Once it was released, the code went through without this error. I never had to re-deploy my EB application. Make sure that you are not connected to the database through any other SQL client. If yes, query for any active locks. (In my case, I was connecting to redshift. Querying STV_LOCKS table lists the active locks). Check who is holding the locks. (In my case, it was my SQL client, connected to redshift, which executed a CUD operation, and since COMMIT was not issued, it was holding a pending write lock on the table). I issued a commit from my SQL client, and the lock was released. My EB code went through and there was no Script timed out error any more.
{ "pile_set_name": "StackExchange" }
Q: How I can send a mail with PDF File I want to send a pdf file with a mail in C#. I know how I can send a mail but I don't know how I can send a mail with pdf file :( For example I have a pdf file in the folder C:\test.pdf Here is my code: private void SendEmail(string pdfpath,string firstname, string lastname, string title, string company, string mailfrom,string mailto) { try { MailMessage m = new MailMessage(); System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(); m.From = new System.Net.Mail.MailAddress(mailfrom); m.To.Add(mailto); m.Subject = "Company Gastzugang (" + lastname + ", " + firstname + ")"; // what I must do for sending a pdf with this email m.Body = "Gastzugangdaten sind im Anhang enthalten"; sc.Host = SMTPSERVER; // here is the smt path sc.Send(m); } catch (Exception ex) { error.Visible = true; lblErrorMessage.Text = "Folgender Fehler ist aufgetreten: " + ex.Message; } } A: You can do like this : var filename = @"c:\test.pdf"; m.Attachments.Add(new Attachment(filename));
{ "pile_set_name": "StackExchange" }
Q: Do I need two nunchucks for 2 player mode in Skylanders on the Wii? I have just bought Skylanders for my son's birthday tomorrow. Just been informed he's got a friend coming around, and they are likely to want to play Skylanders in 2 player mode. I have two Wii plus controllers, but only one nunchuck. Do both players need a nunchuck, or can I get away with just one? I'm guessing I need two, but a quick answer may save me a midnight trip to the local supermarket. A: The game requires a Nunchuk for each player, you cannot play it with Wii remote alone, sorry...
{ "pile_set_name": "StackExchange" }
Q: Simple division function in IA32 assembly I am working on an assignment for my class. My C++ code calls the _Divide function to take in 2 values to divide and return into 'Result'. To start I move -1 into eax. Once I'm done with the process, my eax keeps returning '-1' as the value. What could I be doing wrong? Here's my assem code: public _Divide .386 .model flat .code _Divide proc mov eax, -1 mov ebx, 1 cdq idiv ebx ret _Divide endp end Here's my C++ code #include <iostream> using namespace std; extern "C" long Divide (long, long, long *); void main () { long Result; long Remainder; long Dividend; long Divisor; do { cout << "Enter Dividend" << endl; cin >> Dividend; cout << "Enter Divisor" << endl; cin >> Divisor; Result = Divide (Dividend, Divisor, &Remainder); cout << "Result is " << Result << " and Remainder is " << Remainder << endl; } while ((Result >= 0) || (Remainder != 0)); Result = Divide (Dividend, Divisor, 0); cout << "Result is " << Result << " and Remainder is not used" << endl; } Thanks. A: Your code divides -1 by 1. The answer is -1, so that's what you return. Let's break down the code (I'll just put inline comments): mov eax, -1 ; Put -1 in eax mov ebx, 1 ; put 1 in ebx cdq ; sign extend eax -> edx:eax = -1 idiv ebx ; divide edx:eax (-1) by ebx (1) ; result goes in eax, so now eax = -1 ret ; return eax (-1) to caller If you want to divide arguments passed to this function, you need to access them somehow. You didn't show us the C++ function signature, so I can't help you with any more details than that. Hint: If you're writing IA32 code, which it looks like you're doing, the arguments will be on the stack.
{ "pile_set_name": "StackExchange" }
Q: Xcode always says ‘FBSDKShareKit/FBSDKShareKit’.h file not found No matter what I do (I may be doing it wrong) When I try to build my unity IOS app for testing, Xcode always says ‘FBSDKShareKit/FBSDKShareKit’.h file not found. I’ve added the Facebook SDK indicated in the Quick Start for iOS in the Xcode Project. From the Facebook SDK folder, dragged the folder FBSDKCoreKit.Framework, FBSDKLoginKit.Framework, FBSDKShareKit.Framework into your Xcode Projects Framework folder. Then configured info.plist as stated and of course supplied the bundle identifier. And it gives the same problem. Honestly I have spent more than 6 weeks on this single issue. I’m in the verge of mental and physical collapse and close to be fired. Please give some kind of advice. I’ve tried all the other answers in this same page but non work. Please help!! A: I had this problem with XCode 10!!! Sorted in this way: Select Libraries > RCTFBSDK.xcodeproj Select Build Settings > Framework Search Paths Replace the ~/Documents/FacebookSDK to $(HOME)/Documents/FacebookSDK (with parentheses!) Believe it or not, now it works! A: If you're here because you're trying to use facebook/react-native-fbsdk, then you only need to add the following line to your Podfile: pod 'FBSDKShareKit' Then pod install Build and run! A: I got the same issue and solve problem.<> My solution : 1. follow the steps from https://developers.facebook.com/docs/react-native/getting-started-ios 2. check the xcode proj -> Library, find and open file RCTFBSDK.xcodeproj then update fb sdk path in build setting->Framework search path. It works. I guess that sometime the RCTFBSDK.xcodeproj in Library can not update the framework search path from main xcodeproj so we need done manually. Hopefully my solution can help you, Thanks.
{ "pile_set_name": "StackExchange" }
Q: Splitting a list into two seperate lists, by every other item in python Hello I have a quick question I cant seem to solve. I have a list: a = [item1, item2, item3, item4, item5, item6] And I want to split this list into two seperate ones by everything other item such that: b = [item1, item3, item5] c = [item2, item4, item6] A: Use slicing, specifying a step: b,c = a[::2], a[1::2]
{ "pile_set_name": "StackExchange" }
Q: Prism: RegisterViewWithRegion does not find public contructor I have some trouble with the regionManager.RegisterViewWithRegion methode. I use Prism.Unity and Prism.Wpf (both v7.2.0.1367) When I want to register the View ShowStringView(I created this View just for getting started with prism...) in the UIModule.cs, I always get Set property 'Prism.Mvvm.ViewModelLocator.AutoWireViewModel' threw an exception.' Line number '7' and line position '14'. inside of the ShowStringView.xaml. When I swap the construtor in ShowStringViewModel.cs, which has the IDBInteraction as parameter, with an constructor without parameters it works. (see below) I'm sure that there's something I don't think of or I use it the wrong way... Would be super nice if someone could help me. Thanks in advance! Update 1 DBInteraction.cs had some problem (see solution) My code DBInteraction.cs (Update 1) public class DBInteraction : IDBInteraction { LinqToTaskPlanSqlDataContext dataContext; public DBInteraction() { string connectionString = ConfigurationManager.ConnectionStrings["TaskPlanConnectionString"].ConnectionString; dataContext = new LinqToTaskPlanSqlDataContext(connectionString); } } Shell.xaml <Window x:Class="TP.Client.Shell" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:TP.Client" xmlns:prism="http://prismlibrary.com/" xmlns:region="clr-namespace:TP.Common;assembly=TP.Common" mc:Ignorable="d" Title="Shell" Height="450" Width="800"> <Grid> <ContentControl prism:RegionManager.RegionName="{x:Static region:RegionNames.ShowStringRegion}" /> </Grid> </Window> App.xaml.cs public partial class App { protected override Window CreateShell() { return Container.Resolve<Shell>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { } protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) { moduleCatalog.AddModule<DataServiceModule>(); moduleCatalog.AddModule<UIModule>(); } } DataServiceModule.cs public class DataServiceModule : IModule { public DataServiceModule() { } public void OnInitialized(IContainerProvider containerProvider) { } public void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterSingleton<IDBInteraction, DBInteraction>(typeof(DBInteraction).FullName); } } UIModule.cs public class UIModule : IModule { IRegionManager _regionManager; public UIModule(IRegionManager regionManager) { _regionManager = regionManager; } public void OnInitialized(IContainerProvider containerProvider) { _regionManager.RegisterViewWithRegion(RegionNames.ShowStringRegion, typeof(ShowStringView)); } public void RegisterTypes(IContainerRegistry containerRegistry) { ViewModelLocationProvider.Register<ShowStringView, ShowStringViewModel>(); } } ShowStringView.xaml <UserControl x:Class="TP.UI.View.ShowStringView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:TP.UI.View" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True" mc:Ignorable="d"> <Grid> <TextBox Text="{Binding Content}" Height="20" Width="150" BorderBrush="Black"/> </Grid> ShowStringViewModel public class ShowStringViewModel : BindableBase { IDBInteraction _dBInteraction; public ShowStringViewModel() { Content = "Hallo"; } // It works when this ctor is comment-out public ShowStringViewModel(IDBInteraction dBInteraction) { _dBInteraction = dBInteraction; Content = "Hallo"; } private string _content; public string Content { get => _content; set => SetProperty(ref _content, value); } } A: See Update1 Inside of the DBInteraction constructor I do read the connectionString from the app.config file. The problem was that this file was not in my Startup-Project, it was in an ClassLibrary-Project. I just moved the app.config file from ClassLibrary to Startup (drag&drop in MSVS Solution Explorer) and everything worked. That's why the DBInteraction just could not be created -> there always was an exception inside the constructor. app.config file in wrong place
{ "pile_set_name": "StackExchange" }
Q: Laravel route to controller not working I'm trying to add a new controller to an existing laravel project. The application already has some pages at /users and I am trying to add a RESTful API which works separately to this. I would like the API to be available at api/users. I have created the controller using PHP artisan: php artisan controller:make ApiUsersController I have added the following to my routes: Route::controller('api/users', 'ApiUsersController'); However when I hit the URL I just receive the site's 'Page could not be found' message. Is there something I have missed? A: It looks like the issue you're having is that you've used Route::controller rather than Route::resource. Route::resource maps routes to the seven RESTful methods that the controller generator creates by default. Route::controller maps them to methods that you add yourself that have the HTTP method as part of their name, in your case if you had a method called getIndex it would be called on a GET request to /api/users/index or if you had one called postStore it would be called on a POST request to /api/users/store. In order to add the API prefix to the route you could use the following: Route::group(['prefix' => 'api'], function() { Route::resource('users', 'ControllerName'); }); You could also add any other controllers in the API within the same callback.
{ "pile_set_name": "StackExchange" }
Q: I can't add cuts to a plane There are three planes in this scene. I believe each one of them is composed of only 4 vertexes. I had no problem selecting the one on the bottom and adding cuts to it. But when I select the one on top left, I can't add cuts. The bottom text line tells me there are cuts being added, but I cannot see them and obviously this is a bug... ? A: Pick a direction The operation you are trying to perform is called "Loop cuts and slide": basically recognize on the mesh faces a certain flow of polygons (loop) and allow the user to subdivide the interested faces by adding a given amount of edges. What the command need to run is just the direction of the path. Quad faces can in fact be subdivided in two different directions. Till the cursor does't approach one of the edges, you'll not see the pink edges (the future loop cuts).
{ "pile_set_name": "StackExchange" }
Q: If you think I'm lanky now If you think I'm lanky now, I used to be even more sinewy. They took away a part of me. Not wanting to lose more, I became an even bigger skinflint. Then they cut out my right eye—what am I now? The unkindest cut of all. I escaped, but found that while I'd once been swift, I'd lost a second. But I could still be an idol. Alone, I searched for answers; I only found myself endlessly. It's enough to burn anyone up (a little). Eventually I found something new, though the ferry ride cost me $1000. But what a wave! I left the terminal behind. What I did next was very wrong; in my pride, I cannot even speak of it. I'm afraid I lost my head. But at last I was no longer on the outside. But forget about all that is behind me. I am with you now, at the end. What was I at the start of my saga? What significant changes did I endure? Word set source: http://www.snopes.com/language/puzzlers/9letters.asp A: You started out: STRINGIER - "lanky" Your changes were: STINGIER - "took away a part of me" (-R), now "an even bigger skinflint" STINGER - "cut out my right eye" (-I), now "unkindest cut" SINGER - "lost a second" (-T), now "an idol" SINGE - "endlessly" (-R), now can "burn ... a little" SINE - "cost me $1000" (-G), now "a wave" SIN - "left the terminal behind" (-E), now "did ... wrong" IN - "lost my head" (-S), now "no longer ... outside" I - "forget about all that is behind me" (-N), now "I am with you now, at the end"
{ "pile_set_name": "StackExchange" }
Q: List of free TCP ports in C++ without using bind() with port=0 I need to create a set of dynamic ffmpeg instances that listens to a port that is available within a C++ program. The ffmpeg instances are created using a command identified as ffmpeg -i tcp://ip:port?listen ..., where the port number should be an available free port. Then ffmpeg command is executed using execv() within a c++ program. Therefore, I need to find a free port which is currently available without using bind() with port=0. As I understand, the bind() will bind the port when trying to check if the port is available. Please let me know if there is a way to implement this within C++. Thanks. A: You can use bind() with a port of 0 first yourself, this will automatically bind to a free and unused port. Then, use getsockname() to find out which port you were bound to. Then close the socket, and execute your ffmpeg listener, pointing it to the port your just closed. Of course, between the time you close the socket and ffmpeg starts up, anything else can come in and grab this port. But that's going to be true no matter how you figure out which port is available. With a little bit more work, you could make this a more reliable process: go ahead and tell ffmpeg to bind to port 0. Assuming it works, after it created its socket you can look in /proc/<pid>/fd to find its socket, then look in /proc/net/tcp to figure out which port it bound to.
{ "pile_set_name": "StackExchange" }
Q: sql server 2008: should i be running differential or transactional logs or both HELP! i have two databases: this one was set up by a third party and they do not allow us to change the database to full recovery. so it is my understanding that if a database is in simple mode, then the only option for backup is the FULL BACKUP? we need to be able to recover it in 15 min increments. would this be possible without doing a full backup every 15min? the other database we have full control over and we would like to be able to recover in 15min intervals. how do i set this up in sql server 2008? should we be doing transactional or differential or both? how do i change a DB from simple to full recovery mode? A: so it is my understanding that if a database is in simple mode, then the only option for backup is the FULL BACKUP? Yes. we need to be able to recover it in 15 min increments. would this be possible without doing a full backup every 15min? Ah - yes. That said, it is simply not practical. What setup is that? It makes NO sense to not allow this change. Like zero. It is actually gross negelct, totally voiding any way to make backups. I never heard of THAT requirement. THere are a lot of bad requirements out, but not allowing the transaction log to work is something I never heard of. how do i set this up in sql server 2008? should we be doing transactional or differential or both? Ever thought of transaction log backups? There is a third option. Basically, you can do full backup weekly, differential daily, tx log every 15 minutes and use log file hipping to move stuff off your database RIGHT NOW (in near real time) automatically. 3.how do i change a DB from simple to full recovery mode? THIS is a RTFM question. Check the properties of the database, there you will find the setting. Change it, press ok, done.
{ "pile_set_name": "StackExchange" }
Q: jquery shows wrong date I want to show the current date in my invoice. To do this, im using the following method: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> Datum: <p id="date"></p> <script> var today = new Date(); var day = today.getDay(); var month = today.getMonth(); var year = today.getYear(); document.getElementById('date').innerHTML = day + "." + month + "." + year; </script> A: You should check the manual: getDay - method returns the day of the week for the specified date according to local time, where 0 represents Sunday getMonth - An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. getYear - A number representing the year of the given date, according to local time, minus 1900 What you are actually looking for is: <p id="date"></p> <script> var today = new Date(); var day = today.getDate(); var month = today.getMonth() + 1; var year = today.getFullYear(); document.getElementById('date').innerHTML = day + "." + month + "." + year; </script> </html> And it has nothing to do wth jQuery :) it's pure javascript.
{ "pile_set_name": "StackExchange" }
Q: Overlaying Images in MATLAB with different color channel I have three binary images (generated with zeros(height, width)) created by MATLAB with R, G and B channel respectively. Now I want to overlap them together to form a color image. What command can be used for generating the overlapped images with apply different channels together? Thank you. A: In MATLAB, an RGB image is saved as m by n by 3 array, where m and n are the height and width of the image. The image parts are thus: rgbImage(:,:,1) = redImage; rgbImage(:,:,2) = greenImage; rgbImage(:,:,3) = blueImage; Of course you should pre-allocate the image first to improve performance. A trick you can do for such arrays is to create it by rgbImage(:,:,3) = blueImage; rgbImage(:,:,2) = greenImage; rgbImage(:,:,1) = redImage; That way, a m by n by 3 array is allocated in the first step and the array doesn't have to be extended in the next steps.
{ "pile_set_name": "StackExchange" }
Q: Advice for cutting car chase SFX Hi. I’m cutting SFX for a car chase scene. Very stoked-my first time. I’ve been doing some reading about techniques and such… Chris Assells has some solid tips on the 5th page of this recent interview in Mix Magazine: http://mixonline.com/post/features/movie_sound_effects/index4.html What have you come across online (or in a part of a book perhaps) that you found helpful? I always like to record some audio assets for a project. Unfortunately, I don’t have the opportunity to this time and will be using library SFX. In a perfect scenario, what sounds would like to record for use cutting a car chase scene? Do you have any particular libraries that you like to use for car chases? I’ve intently watched the Bourne trilogy’s car chase scenes and admire the job that the sound department did. There are many others for inspiration, what car chase scenes do you think sound awesome? [youtube]HPI5-TSdC9w[/youtube] This experience is going to be great for growing in knowledge. I appreciate your input. Thanks. Peace! Edit Summary- Guess I can't embed video in comments(?). Anyway... As mentioned in the thread, I too really dig the opening chase in Quantum- [youtube]BsBd9tPK4uE[/youtube] A: To borrow from John Cage (thanks, @tim prebble): RULE FOUR: CONSIDER EVERYTHING AN EXPERIMENT There is no right way to cut a car chase. Every car chase is different and every editor has their own methods and tricks. Sometimes there needs to be more emphasis on the muscular sound of the engines vs. the squealing of the tires; other times you'll be focused on the dynamic parts of the chase, ie. the gear shifts, pedal stomps, object pass bys, etc. And don't forget about music and score - everything you create has to work with what the composer is bringing to the table (unless you have a sound effects-only car chase scene, which totally rocks!) With that said, let me explain how I usually begin. My standard approach, if I'm not given any other direction, is to start with the engines first. Unless you are fortunate enough to have an entire car set custom recorded for the show or in your library, you'll probably piece each vehicle together from a variety of sources. For example, if you're working on a strong-sounding Camaro, you may end up using Mustangs, Corvettes, Plymouths, etc. Some pitch shifting here and EQing there, and viola, you have your muscle car! This takes practice, imagination and lots of experimenting, so don't give up. Once I get the engines dialed in and feeling right, then I'll add in skids, suspension, tire roll, etc. These sounds function not only as emotional cues but also as the glue that holds all your engine parts together. Also, as a rule of thumb, I've found that complex jobs such as this require you to constantly revisit and revise. Rarely do I "get it right" the first time! As with most of sound design, you should play your scene back for everyone, soliciting opinions and collaborating with your peers. BTW, great chases to reference would include: The French Connection Bullitt Mr. and Mrs. Smith all the Bourne films (as you mentioned) Bad Boys The Terminator (original, 1984)
{ "pile_set_name": "StackExchange" }
Q: Writing a "Bean Counter" for Eloquent JavaScript Task In this task from Eloquent JavaScript, you are asked to write two functions. One to count the number of ""'s in a string input. The next function must take two inputs; one string to search and one string to identify the target character to search for. I have errors in both. In the first function, my count is always returned as 1. In the second one, it simply returns undefined. Can someone help me find my mistake? function countBs(str) { var count = 0; for (var i = 0; i < str.length; i++) { if (str.charAt(i) === "B") { count++; } return (count); } } console.log(countBs("BBBBBBBBC")); function countChar(str, char) { var count = 0; for (var i = 0; i < str.length; i++) { if (str.charAt(i) === "char") { count++; return (count); } } } console.log(countChar("kakkerlak", "k")); A: The problem is you are returning the count within the for loop, so it returns after it searches the first character. In the second function you are also using the string "char" instead of the variable char for comparing. If you want to do it your way, here's the correct code: function countBs(str) { var count = 0; for (var i = 0; i < str.length; i++) { if (str.charAt(i) === "B") { count++; } } return (count); // return outside of for loop } console.log(countBs("BBBBBBBBC")); function countChar(str, char) { var count = 0; for (var i = 0; i < str.length; i++) { if (str.charAt(i) === char) { // use the variable char instead of the string "char" count++; } } return (count); // return outside of the for loop } console.log(countChar("kakkerlak", "k")); Here's another way to do what you want. (using regular expressions) function countBs(str) { var length1 = str.length; var length2 = str.replace(/B/g,"").length; return length1 - length2; } console.log(countBs("BBBBBBBBC")); function countChar(str, char) { var length1 = str.length; var regexp = new RegExp(char, "g"); var length2 = str.replace(regexp,"").length; return length1 - length2; } console.log(countChar("kakkerlak", "k")); A: You've got two small errors that require the following changes: don't quote your char variable in the if statement return after the loop is complete, not after the first match Full code for countChar(): function countChar(str, char) { var count = 0; for (var i = 0; i < str.length; i++) { if (str.charAt(i) === char) { count++; } } return (count); } //test alert(countChar("kakkerlak", "k"));
{ "pile_set_name": "StackExchange" }
Q: Something it is wrong in implementation of Strategy Pattern in c# I am trying implement a Strategy pattern with nested classes. public class Restriction { protected SpecificRestriction _specificRestriction; public void SetGreaterRestriction(decimal value) { Greater greaterRestriction = new Greater(); greaterRestriction.GreaterValue = value; _specificRestriction = greaterRestriction; } public void SetLessRestriction(decimal value) { Less lessRestriction = new Less(); lessRestriction.LessValue = value; _specificRestriction = lessRestriction; } public void SetRangeRestriction(decimal lessValue, decimal greaterValue) { Range r = new Range(); r.GreaterValue= greaterValue; r.LessValue= lessValue; _specificRestriction = r; } public bool Eval(decimal Value2) { return _specificRestriction.Eval(Value2); } /* Nested strategies classes */ protected abstract class SpecificRestriction { public abstract bool Eval(decimal Value); } protected class Less : SpecificRestriction { public decimal LessValue { get; set; } public override bool Eval(decimal lessValue) { return lessValue < LessValue ; } } protected class Greater : SpecificRestriction { public decimal GreaterValue { get; set; } public override bool Eval(decimal greaterValue) { return greaterValue > GreaterValue; } } protected class Range : SpecificRestriction { public decimal LessValue { get; set; } public decimal GreaterValue { get; set; } public override bool Eval(decimal mediumValue) { return LessValue <= mediumValue && mediumValue <= GreaterValue; } } } Testing: Restriction r = new Restriction(); r.SetLessRestriction(12); r.Eval(13) // Return false <- Works! r.Eval(11) // Return True <- Works! r.SetGreaterRestriction(12); r.Eval(13) // Return True <- Works! r.Eval(11) // Return False <- Works! r.SetRangeRestriction(12, 15); r.Eval(13) // Return false <- It does not works r.Eval(11) // Return false <- Works! r.Eval(16) // Return false <- Works! Why Range it does not works? Am I doing something wrong in Range class? A: There is some change required in Restriction Class and it works public class Restriction { protected SpecificRestriction _specificRestriction; public void SetGreaterRestriction(decimal value) { Greater greaterRestriction = new Greater(); greaterRestriction.GreaterValue = value; _specificRestriction = greaterRestriction; } public void SetLessRestriction(decimal value) { Less lessRestriction = new Less(); lessRestriction.LessValue = value; _specificRestriction = lessRestriction; } public void SetRangeRestriction(decimal lessValue, decimal greaterValue) { Range r = new Range(); r.GreaterValue = greaterValue; r.LessValue = lessValue; _specificRestriction = r; } public bool Eval(decimal Value2) { return _specificRestriction.Eval(Value2); } /* Nested strategies classes */ protected abstract class SpecificRestriction { public abstract bool Eval(decimal Value); } protected class Less : SpecificRestriction { public decimal LessValue { get; set; } public override bool Eval(decimal lessValue) { return lessValue < LessValue; } } protected class Greater : SpecificRestriction { public decimal GreaterValue { get; set; } public override bool Eval(decimal greaterValue) { return greaterValue > GreaterValue; } } protected class Range : SpecificRestriction { public decimal LessValue { get; set; } public decimal GreaterValue { get; set; } public override bool Eval(decimal mediumValue) { return LessValue <= mediumValue && mediumValue <= GreaterValue; } } }
{ "pile_set_name": "StackExchange" }
Q: AWS DMS - InvalidParameterValueException) when calling the CreateReplicationTask operation: Replication Task Settings document error: Invalid json I am trying to create a DMS replication task using the AWS DMS cli. I am trying to pass the task settings using a json file like this: aws dms create-replication-task --replication-task-identifier dms-cli-test-replication-task-1 --source-endpoint-arn arn --target-endpoint-arn arn --replication-instance-arn arn --migration-type full-load-and-cdc --table-mappings ./table_mappings.json --replication-task-settings ./task_settings.json --region us-east-1 when I run this command, the below error is being thrown: An error occurred (InvalidParameterValueException) when calling the CreateReplicationTask operation: Replication Task Settings document error: Invalid json Below is the content of my task_settings.json file: { "TargetMetadata": { "TargetSchema": "", "SupportLobs": true, "FullLobMode": true, "LobChunkSize": 64, "LimitedSizeLobMode": false, "LobMaxSize": 0, "InlineLobMaxSize": 0, "LoadMaxFileSize": 0, "ParallelLoadThreads": 0, "ParallelLoadBufferSize": 0, "BatchApplyEnabled": false, "TaskRecoveryTableEnabled": false }, "FullLoadSettings": { "TargetTablePrepMode": "DO_NOTHING", "CreatePkAfterFullLoad": false, "StopTaskCachedChangesApplied": false, "StopTaskCachedChangesNotApplied": false, "MaxFullLoadSubTasks": 8, "TransactionConsistencyTimeout": 600, "CommitRate": 10000 }, "Logging": { "EnableLogging": true, "LogComponents": [ { "Id": "SOURCE_UNLOAD", "Severity": "LOGGER_SEVERITY_DEFAULT" }, { "Id": "SOURCE_CAPTURE", "Severity": "LOGGER_SEVERITY_DEFAULT" }, { "Id": "TARGET_LOAD", "Severity": "LOGGER_SEVERITY_DEFAULT" }, { "Id": "TARGET_APPLY", "Severity": "LOGGER_SEVERITY_DEFAULT" }, { "Id": "TASK_MANAGER", "Severity": "LOGGER_SEVERITY_DEFAULT" } ] }, "ControlTablesSettings": { "historyTimeslotInMinutes": 5, "ControlSchema": "", "HistoryTimeslotInMinutes": 5, "HistoryTableEnabled": true, "SuspendedTablesTableEnabled": true, "StatusTableEnabled": true }, "StreamBufferSettings": { "StreamBufferCount": 3, "StreamBufferSizeInMB": 8, "CtrlStreamBufferSizeInMB": 5 }, "ChangeProcessingDdlHandlingPolicy": { "HandleSourceTableDropped": true, "HandleSourceTableTruncated": true, "HandleSourceTableAltered": true }, "ErrorBehavior": { "DataErrorPolicy": "LOG_ERROR", "DataTruncationErrorPolicy": "LOG_ERROR", "DataErrorEscalationPolicy": "SUSPEND_TABLE", "DataErrorEscalationCount": 0, "TableErrorPolicy": "SUSPEND_TABLE", "TableErrorEscalationPolicy": "STOP_TASK", "TableErrorEscalationCount": 0, "RecoverableErrorCount": -1, "RecoverableErrorInterval": 5, "RecoverableErrorThrottling": true, "RecoverableErrorThrottlingMax": 1800, "ApplyErrorDeletePolicy": "IGNORE_RECORD", "ApplyErrorInsertPolicy": "LOG_ERROR", "ApplyErrorUpdatePolicy": "LOG_ERROR", "ApplyErrorEscalationPolicy": "LOG_ERROR", "ApplyErrorEscalationCount": 0, "ApplyErrorFailOnTruncationDdl": false, "FullLoadIgnoreConflicts": true, "FailOnTransactionConsistencyBreached": false, "FailOnNoTablesCaptured": false }, "ChangeProcessingTuning": { "BatchApplyPreserveTransaction": true, "BatchApplyTimeoutMin": 1, "BatchApplyTimeoutMax": 30, "BatchApplyMemoryLimit": 500, "BatchSplitSize": 0, "MinTransactionSize": 1000, "CommitTimeout": 1, "MemoryLimitTotal": 1024, "MemoryKeepTime": 60, "StatementCacheSize": 50 }, "ValidationSettings": { "EnableValidation": true, "ValidationMode": "ROW_LEVEL", "ThreadCount": 5, "PartitionSize": 10000, "FailureMaxCount": 10000, "RecordFailureDelayInMinutes": 5, "RecordSuspendDelayInMinutes": 30, "MaxKeyColumnSize": 8096, "TableFailureMaxCount": 1000, "ValidationOnly": false, "HandleCollationDiff": false, "RecordFailureDelayLimitInMinutes": 0 }, "PostProcessingRules": null, "CharacterSetSettings": null } I don't see any issues with the formatting of my json. I don't understand why it says invalid json. any advice is appreciated. Thank you. A: This is not actually you pass setting document or any document to aws-cli. It usually precedes the path with "file://" while passing JSON file to any parameter of cli. Try using below command: aws dms create-replication-task --replication-task-identifier dms-cli-test-replication-task-1 --source-endpoint-arn arn --target-endpoint-arn arn --replication-instance-arn arn --migration-type full-load-and-cdc --table-mappings file://table_mappings.json --replication-task-settings file://task_settings.json --region us-east-1 However, I can't see this particular parameter takes json document as a setting file. But I think you should try. Check below snippet from the doc. --replication-task-identifier (string) The replication task identifier. Constraints: Must contain from 1 to 255 alphanumeric characters or hyphens. First character must be a letter. Cannot end with a hyphen or contain two consecutive hyphens.
{ "pile_set_name": "StackExchange" }
Q: How to continuously scroll with JScrollPane I'm using a JScrollPane to encompass a large JPanel. When the mouse is not within the bounds of the JScrollPane, I would like it to scroll in that direction. For example, if the top of the JScrollPane is at (100, 100) and the mouse is above the top of the component, I would like it to scroll upwards. So far I found this: private Point origin; in the constructor... addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { origin = new Point(e.getPoint()); } }); addMouseMotionListener(new MouseAdapter() { public void mouseDragged(MouseEvent e) { if (origin != null) { JViewport viewPort = (JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, Assets.adder.viewer); if (viewPort != null) { Rectangle view = viewPort.getViewRect(); if (e.getX() < view.x) view.x -= 2; if (e.getY() < view.y) view.y -= 2; if (view.x < 0) view.x = 0; if (view.y < 0) view.y = 0; if (e.getX() > view.x + view.getWidth()) view.x += 2; if (e.getY() > view.y + view.getHeight()) view.y += 2; scrollRectToVisible(view); } } } }); This works, but it only works when the mouse is in motion, otherwise it does not. How can I make it work while the mouse is outside of the JScrollPane, but also not moving? A: Check out the setAutoScrolls(...) method of the JComponent class. You can just use: panel.setAutoScrolls( true ); And then you use the following MouseMotionListener: MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1); ((JPanel)e.getSource()).scrollRectToVisible(r); } }; panel.addMouseMotionListener(doScrollRectToVisible); This concept is demonstrated in the ScollDemo example found in the Swing tutorial on How to Use Scroll Panes.
{ "pile_set_name": "StackExchange" }
Q: OpenCV IOS real-time template matching I'd like to create an app (on iPhone) which does this: I have a template image (a logo or any object) and I'd like to find that in camera view and put a layer on the place of where it is found and tracking it! It is a markless AR with OpenCV! I read some docs and books and Q&A-s here, but sadly actually i'd like to create something like this or something like this. If anyone can send to me some source code or a really useful tutorial (step by step) i'd really be happy!!! Thank you! A: Implementing this is not trivial - it involves Augmented Reality combined with template matching and 3D rendering. A rough outline: Use some sort of stable feature extraction to obtain features from the input video stream. (eg. see FAST in OpenCV). Combine these features and back-project to estimate the camera parameters and pose. (See Camera Calibration for a discussion, but note that these usually require calibration pattern such as a checkerboard.) Use template matching to scan the image for patches of your target image, then use the features and camera parameters to determine the pose of the object. Apply the camera and object transforms forward and render the replacement image into the scene. Implementing all this will require much research and hard work! There are a few articles on the web you might find useful: Simple Augmented Reality for OpenCV A minimal library for Augmented Reality AR with NyartToolkit You might like to investigate some of the AR libraries and frameworks available. Wikipedia has a good list: AR Software Notable is Qualcomm's toolkit, which is not FLOSS but appears highly capable.
{ "pile_set_name": "StackExchange" }
Q: Icons in start menu are gone My system is Windows 7 64bit. I start my PC today, and noticed that most of the icons of the applications in the start menu are gone...but the applications are still working. How can I get the icons back? A: I figured out...there's no fix for this kind of issue. What I did was...I deleted the original installation files that installer copied to my computer. I think these installation are useless. I have a copy of them and stored in somewhere safe. Why I need another copy on my computer? But Microsoft does not agree :( They make a copy of the installation file on your computer, and pointing some resources to these copies.
{ "pile_set_name": "StackExchange" }
Q: Corollary of Gauss's Lemma (polynomials) I am trying to prove the following result. I have outlined my attempt at a proof but I get stuck. Any help would be welcome! Theorem: Let $R$ be a UFD and let $K$ be its field of fractions. Suppose that $f \in R[X]$ is a monic polynomial. If $f=gh$ where $g,h \in K[X]$ and $g$ is monic, then $g \in R[X].$ Proof Attempt: Clearly we have $gh=(\lambda \cdot g_0)(\mu\cdot h_0)$ for some $\lambda,\mu \in K$ and $f_0, g_0 \in R[X]$ primitive. Write $\lambda=a/b$ and $\mu=c/d$ for some $a,b,c,d \in R$. Clearing denominators yields $(bd)\cdot f = (ac)\cdot g_0f_0$ where both sides belong to $R[X]$. By Gauss's lemma $g_0f_0$ is primitive and so taking contents yields $\lambda\mu=1$. This proves that $f=g_0h_0$ is a factorization in $R[X]$ but not necessarily that $g \in R[X]$. I can't seem to get any further than this - any help greatly appreciated? A: The leading term of $f$ is the product of the leading terms of $g_0$ and $h_0$, hence these are units. Hence the factor $\lambda$ by which $g_0$ differs from $g$ is a unit.
{ "pile_set_name": "StackExchange" }
Q: Esperar un tiempo en una function Tengo esta function function cambiosIngenieria(){ var devuelto = vm.productosGridOptions.dataSource.data(); var idDetallelinea; devuelto.forEach(function (lineaDevuelto) { if (lineaDevuelto.RevisionIngenieria == "Devuelto") { console.log("Es para devolver"); idDetallelinea = lineaDevuelto.Id; var _revisionIngenieria = { __metadata: { 'type': 'SP.Data.DetalleLineasListItem' }, } _revisionIngenieria.RevisionIngenieria = "Pendiente" var context = getContext("../lists/DetalleLineas"); var resultFecha = updateItem("../_api/web/Lists/GetByTitle('DetalleLineas')/getItemById(" + idDetallelinea + ")", context, _revisionIngenieria); //vm.productosGridOptions.dataSource.read() } }); vm.productosGridOptions.dataSource.read() } Lo que hace es traerme un array de un grid de Kendo UI y actualizar un dato en una lista de sharepoint. Ahora lo que necesito realizar en la function cambiosIngenieria esperar 5 segundos mientras vm.productosGridOptions.dataSource.read() termina de actualizar el grid y luego seguir con el proceso. Alguna forma de realizarlo. A: Segun la documentacion de read() lo retornado es una promesa. Asi que puedes seguir ejecutando tu codigo cuando esta finaliza, como lo ponen en el ejemplo: dataSource.read().then(function() { var view = dataSource.view(); console.log(view[0].ProductName); // displays "Chai" });
{ "pile_set_name": "StackExchange" }
Q: Python: How to invoke a new thread based on the running time of an existing thread? Python: How do I poll the time run by each child thread to the parent thread? So that after specific time frame I can invoke a new thread. A: The standard way to communicate between parallel processes (such as threads) is a queue. Each thread can remember the (wall clock) time of its own start. When it finishes, it can measure its run duration and post it to the queue. It can also post a progress message periodically (e.g. once it completes fetching an URL from a list), also with a timestamp and a duration. The main thread can periodically poll the queue and see how other threads are doing.
{ "pile_set_name": "StackExchange" }
Q: How to send the email which is sleeping in my queue list? When i send email it sleep in my queue list. How can i send them out? (Fedora 15 distro). # mailq /var/spool/mqueue (2 requests) -----Q-ID----- --Size-- -----Q-Time----- ------------Sender/Recipient----------- pBMNMDA1009288* 2100 Fri Dec 23 00:22 <apache@example> <[email protected]> pBMNIjU5009236 2100 Fri Dec 23 00:18 <apache@example> (Deferred: Connection timed out with aspmx3.googlemail.com.) <[email protected]> A: Whenever sendmail has to deliver mails to other hosts which cannot be reached at that time, the messages are kept in the queue and are marked as “Deferred: Connection timed out”. Although the other hosts could be reached again and you want to tell sendmail to flush the mail queue, the command sendmail -q -v does not really try to reconnect to these hosts and still assumes that the connection timed out. The reason is that the hoststatus is cached, per default for a period of 30 minutes. Using sendmail -OTimeout.hoststatus=0m -q -v you can re-run the mail queue and force sendmail to reconnect to the hosts. Alternatively, if you want to do a selective flush on perticular domain or user or recepitience mail to delete, use this command sendmail -qS -v apache # it will delete all mail from *@apache sendmail -qR -v a.com # it will delete all mail destined for recepient at user of a.com
{ "pile_set_name": "StackExchange" }
Q: VB write ´╗┐ | ́╗┐'java is not recognized as an internal or external command I have created a programm... this programm need to write in a .bat file This is the code My.Computer.FileSystem.WriteAllText("C:\Server\Minecraft\Start.bat", "java -Xincgc -XX:PermSize=128m -Xmx" + TextBox1.Text + "m -Xms" + TextBox1.Text + "m -jar " + TextBox3.Text + " nogui", True) But the result when i start the "Start.bat" file is: ́╗┐'java is not recognized as an internal or external command How i resolve this problem? Thanks bye A: You are probably writing the file in such a way that there is a BOM at the start of the file. Batch files cannot have a BOM at the start. You will have to find out how to write a file without including a BOM.
{ "pile_set_name": "StackExchange" }
Q: How to adapt my unit tests to cmake and ctest? Until now, I've used an improvised unit testing procedure - basically a whole load of unit test programs run automatically by a batch file. Although a lot of these explicitly check their results, a lot more cheat - they dump out results to text files which are versioned. Any change in the test results gets flagged by subversion and I can easily identify what the change was. Many of the tests output dot files or some other form that allows me to get a visual representation of the output. The trouble is that I'm switching to using cmake. Going with the cmake flow means using out-of-source builds, which means that convenience of dumping results out in a shared source/build folder and versioning them along with the source doesn't really work. As a replacement, what I'd like to do is to tell the unit test tool where to find files of expected results (in the source tree) and get it to do the comparison. On failure, it should provide the actual results and diff listings. Is this possible, or should I take a completely different approach? Obviously, I could ignore ctest and just adapt what I've always done to out-of-source builds. I could version my folder-where-all-the-builds-live, for instance (with liberal use of 'ignore' of course). Is that sane? Probably not, as each build would end up with a separate copy of the expected results. Also, any advice on the recommended way to do unit testing with cmake/ctest gratefuly received. I wasted a fair bit of time with cmake, not because it's bad, but because I didn't understand how best to work with it. EDIT In the end, I decided to keep the cmake/ctest side of the unit testing as simple as possible. To test actual against expected results, I found a home for the following function in my library... bool Check_Results (std::ostream &p_Stream , const char *p_Title , const char **p_Expected, const std::ostringstream &p_Actual ) { std::ostringstream l_Expected_Stream; while (*p_Expected != 0) { l_Expected_Stream << (*p_Expected) << std::endl; p_Expected++; } std::string l_Expected (l_Expected_Stream.str ()); std::string l_Actual (p_Actual.str ()); bool l_Pass = (l_Actual == l_Expected); p_Stream << "Test: " << p_Title << " : "; if (l_Pass) { p_Stream << "Pass" << std::endl; } else { p_Stream << "*** FAIL ***" << std::endl; p_Stream << "===============================================================================" << std::endl; p_Stream << "Expected Results For: " << p_Title << std::endl; p_Stream << "-------------------------------------------------------------------------------" << std::endl; p_Stream << l_Expected; p_Stream << "===============================================================================" << std::endl; p_Stream << "Actual Results For: " << p_Title << std::endl; p_Stream << "-------------------------------------------------------------------------------" << std::endl; p_Stream << l_Actual; p_Stream << "===============================================================================" << std::endl; } return l_Pass; } A typical unit test now looks something like... bool Test0001 () { std::ostringstream l_Actual; const char* l_Expected [] = { "Some", "Expected", "Results", 0 }; l_Actual << "Some" << std::endl << "Actual" << std::endl << "Results" << std::endl; return Check_Results (std::cout, "0001 - not a sane test", l_Expected, l_Actual); } Where I need a re-usable data-dumping function, it takes a parameter of type std::ostream&, so it can dump to an actual-results stream. A: I'd use CMake's standalone scripting mode to run the tests and compare the outputs. Normally for a unit test program, you would write add_test(testname testexecutable), but you may run any command as a test. If you write a script "runtest.cmake" and execute your unit test program via this, then the runtest.cmake script can do anything it likes - including using the cmake -E compare_files utility. You want something like the following in your CMakeLists.txt file: enable_testing() add_executable(testprog main.c) add_test(NAME runtestprog COMMAND ${CMAKE_COMMAND} -DTEST_PROG=$<TARGET_FILE:testprog> -DSOURCEDIR=${CMAKE_CURRENT_SOURCE_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/runtest.cmake) This runs a script (cmake -P runtest.cmake) and defines 2 variables: TEST_PROG, set to the path of the test executable, and SOURCEDIR, set to the current source directory. You need the first to know which program to run, the second to know where to find the expected test result files. The contents of runtest.cmake would be: execute_process(COMMAND ${TEST_PROG} RESULT_VARIABLE HAD_ERROR) if(HAD_ERROR) message(FATAL_ERROR "Test failed") endif() execute_process(COMMAND ${CMAKE_COMMAND} -E compare_files output.txt ${SOURCEDIR}/expected.txt RESULT_VARIABLE DIFFERENT) if(DIFFERENT) message(FATAL_ERROR "Test failed - files differ") endif() The first execute_process runs the test program, which will write out "output.txt". If that works, then the next execute_process effectively runs cmake -E compare_files output.txt expected.txt. The file "expected.txt" is the known good result in your source tree. If there are differences, it errors out so you can see the failed test. What this doesn't do is print out the differences; CMake doesn't have a full "diff" implementation hidden away within it. At the moment you use Subversion to see what lines have changed, so an obvious solution is to change the last part to: if(DIFFERENT) configure_file(output.txt ${SOURCEDIR}/expected.txt COPYONLY) execute_process(COMMAND svn diff ${SOURCEDIR}/expected.txt) message(FATAL_ERROR "Test failed - files differ") endif() This overwrites the source tree with the build output on failure then runs svn diff on it. The problem is that you shouldn't really go changing the source tree in this way. When you run the test a second time, it passes! A better way is to install some visual diff tool and run that on your output and expected file.
{ "pile_set_name": "StackExchange" }
Q: Can not see table items in SWT Table I am trying to create the following dialog: I have tried this: import java.util.HashSet; import java.util.Set; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; public class CorrelationDlg extends Dialog { private final GridLayout composite; private Spinner spinner; private Button button; private final Table ancestors; private final Table descendants; public CorrelationDlg(Shell shell) { super(shell); composite = new GridLayout(4, false); shell.setLayout(composite); spinner = new Spinner(shell, SWT.FILL); spinner.setMinimum(0); spinner.setMaximum(7); spinner.setIncrement(1); GridData spinnerData = new GridData(SWT.FILL, SWT.BEGINNING, true, false); spinnerData.horizontalSpan = 3; spinner.setLayoutData(spinnerData); spinner.pack(); button = new Button(shell, SWT.CHECK); button.setText("Self:"); GridData buttonData = new GridData(SWT.FILL, SWT.BEGINNING, true, false); buttonData.horizontalSpan = 3; button.setLayoutData(buttonData); button.pack(); ancestors = new Table(shell, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); final TableColumn ancestorsColumn = new TableColumn(ancestors, SWT.NONE); ancestorsColumn .setText("Ancestors"); ancestors.setHeaderVisible(true); GridData ancestorsData = new GridData(GridData.FILL_BOTH, SWT.BEGINNING, true, false); ancestorsData.horizontalSpan = 3; ancestors.setLayoutData(ancestorsData); descendants = new Table(shell, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); final TableColumn descendantsColumn = new TableColumn(descendants, SWT.NONE); descendantsColumn.setText("Descendants"); descendants.setHeaderVisible(true); GridData descendantsData = new GridData(GridData.FILL_BOTH, SWT.BEGINNING, true, false); descendantsData.horizontalSpan = 1; descendants.setLayoutData(descendantsData); } public void addAncestors(Set<String> resourceKinds) { for(final String resourceKind: resourceKinds) { final TableItem item = new TableItem(ancestors, SWT.NONE); item.setText(resourceKind); } ancestors.pack(); } public void addDescendants(Set<String> resourceKinds) { for(final String resourceKind: resourceKinds) { final TableItem item = new TableItem(descendants, SWT.NONE); item.setText(resourceKind); } descendants.pack(); } public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); CorrelationDlg dlg = new CorrelationDlg(shell); Set<String> ancestors = new HashSet<>(); ancestors.add("A1"); ancestors.add("A2"); dlg.addAncestors(ancestors); Set<String> ds = new HashSet<>(); ds.add("A1"); ds.add("A2"); dlg.addDescendants(ds); shell.setSize(200, 200); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } } But currently I am unable to see table items. Could you please point out what is the problem with this? A: You didn't set the columns width and didn't correctly pack() them, so their width is 0. You can set the width using setWidth, for example: ancestorsColumn.setWidth(100); or "pack" them with their pack() method, for example in addAncestor you could add this: ancestors.getColumn(0).pack();
{ "pile_set_name": "StackExchange" }
Q: What all models/controllers are needed for building a counter I want to create a counter example where in the variable increments when ever the user presses a button on the webpage(view) I have created the ruby program for the counter like this: def counter(x = 0) x+=1 puts "The current value is #{x}" end I have saved this as counter.rb. Then for the view I created another file called counter.erb But I dont know where to call this rb file and should I use <%= %> embedded ruby tags? Totally confused. Another thing is the method counter's parameter should be linked to the button clicks. Please guide me Thanks, A: Ok this is basic and you should be knowing this but still, I will tell you. The question is also vague so I will assume that you have a counter which is a number and a name for the counter. This is how you update any column from scratch.So first create rails generate scaffold counter count:integer name:string After this step. def update @counter = Counter.find(params[:id]) if @counter.update_attributes(params[:counter]) redirect_to @counter, :flash => { :success => "Profile updated." } end end After this create a view in edit.html.erb under views: <%= form_for(@counter) do |f| %> <div class="field"> <%= f.label :name %><br /> <%= f.text_field :name %> </div> <div class="field"> <%= f.label :count %><br /> <%= f.text_field :count %> </div> <div class="actions"> <%= f.submit "Update" %> </div> <% end %> Go to counter.rb model and do the following: class Counter < ActiveRecord::Base attr_accessible :count, :name end You dont have to add anything in the routes file because it already has the update resource. Now open the browser and if you say localhost:3000/counter/1/update after creating the first counter value then you can update stuff from there. This is how you updating can be done in ruby on rails. If you need more explanation regarding your code you should check the api documentation for rails it is a good start. I am a beginner too.
{ "pile_set_name": "StackExchange" }
Q: Create different template class according to the basic type of the template I will try to explain my problem with a simple example: class Runnable { protected: virtual bool Run() { return true; }; }; class MyRunnable : Runnable { protected: bool Run() { //... return true; } }; class NotRunnable { }; class FakeRunnable { protected: bool Run() { //... return true; } }; //RUNNABLE must derive from Runnable template<class RUNNABLE> class Task : public RUNNABLE { public: template<class ...Args> Task(Args... args) : RUNNABLE(forward<Args>(args)...) { } void Start() { if(Run()) { //... } } }; typedef function<bool()> Run; template<> class Task<Run> { public: Task(Run run) : run(run) { } void Start() { if(run()) { //... } } private: Run run; }; main.cpp Task<MyRunnable>(); //OK: compile Task<Run>([]() { return true; }); //OK: compile Task<NotRunnable>(); //OK: not compile Task<FakeRunnable>(); //Wrong: because compile Task<Runnable>(); //Wrong: because compile In summary, if the T template derive from the Runnable class, I want the class Task : public RUNNABLE class to be used. If the template T is of the Run type I want the class Task<Run> class to be used, and in all other cases the program does not have to compile. How can I do? A: You might static_assert your condition (with traits std::is_base_of): template<class RUNNABLE> class Task : public RUNNABLE { public: static_assert(std::is_base_of<Runnable, RUNNABLE>::value && !std::is_same<Runnable , RUNNABLE>::value); // ... }; Demo
{ "pile_set_name": "StackExchange" }
Q: Reload List after Closing Modal I have a list of brands: <script type="text/ng-template" id="list.brands"> <table class="table table-striped table-bordered bootstrap-datatable datatable dataTable" id="DataTables_Table_0" aria-describedby="DataTables_Table_0_info" ng-controller="BrandsCtrl"> <input type="text" ng-model="searchBox"> <thead> <tr> <th><tags:label text="brandid"/></th> <th><tags:label text="name"/></th> <th><tags:label text="isactive"/></th> <th></th> </tr> </thead> <tbody> <tr id="actionresult{{$index + 1}}" ng-repeat="brand in brands | filter:searchBox"> <td>{{brand.brandid}}</td> <td>{{brand.name}}</td> <td>{{brand.isactive}}</td> <td> <a class="btn btn-ext-darkblue btn-ext-darkblue savestockbtn" ng-click="open(brand.brandid)"><tags:label text="edit"/></a> <a class="btn btn-ext-darkblue btn-modal-trigger btn-ext-darkblue savestockbtn" href="/admin.brands/deleteConfirm?brandid={{brand.brandid}}" data-toggle="modal" ><tags:label text="delete"/></a> </td> </tr> </tbody> </table> </script> This list has brands line with 2 button; edit and delete. Edit button opens a modal of brand edit form: <%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib tagdir="/WEB-INF/tags" prefix="tags"%> <%@taglib uri="/WEB-INF/tlds/fields.tld" prefix="fields"%> <div class="row-fluid sortable"> <div class="box span12"> <div class="box-content"> <form class="form-horizontal" name="brandform" action='/admin.brands/update' data-toggle="validate" method="post"> <fields:form formName="brand.id.form"> <input type="hidden" ng-model="item.brandid" name="brandid"/> </fields:form> <fields:form formName="brand.form"> <div class="section-heading"></div> <div class="control-group"> <label class="control-label" for="selectError"><tags:label text="name"/> *</label> <div class="controls"> <input name="name" ng-model="item.name" required/> </div> </div> <div class="control-group"> <label class="control-label" for="selectError"><tags:label text="isactive"/> </label> <div class="controls"> <input type="checkbox" ng-model="item.isactive" ng-checked="item.isactive" name="isactive" value="1"/> </div> </div> </fields:form> <div class="form-actions"> <a ng-click="cancel()" class="btn btn-ext-lightblue"><tags:label text="close"/></a> <a ng-click="ok()" class="btn btn-ext-darkblue btn-disable-on-submit" ><tags:label text="save"/></a> </div> </form> </div> </div> </div> In modal, save button saves modifications and closes the modal. I want to reload the list after closing. How can I do it ? Controllers of list and modal is different. How can I reload background of modal after close it ? A: You can broadcast a method to communicate try like this In modal controller where close button is triggered $rootScope.$broadcast('updateList'); If you wanna to pass data from modal $rootScope.$broadcast('updateList',{data : 'passing'}); // pass object in {} if you wanna to pass anything In data Controller $scope.$on("updateList",function(){ // Post your code }); If you passed data from modal $scope.$on("updateList",function(e,a){ // Post your code console.log(a.data); }); A: If you are using angular UI $modal Service, then its pretty simple. The open() method of $modal service returns a promise on close and cancel of the modal. Lets say var myModal = $modal.open({ animation: true, templateUrl: 'editForm.html', backdrop: 'static', keyboard: false, scope: $scope }); myModal.result.then(function(){ //Call function to reload the list }); As you are calling $modal.open from list controller itself, you have got access to `promise' in list controller only and from there you can easily call your function to reload the list.
{ "pile_set_name": "StackExchange" }
Q: Video freezes when watching videos When i watch videos on youtube using firefox or Epiphany the video freezes when i do nothing for a few minutes and i have to move the mouse so that the video continues it's a very annoying problem if you know the solution your answer is appreciated. I think this person is having the same problem video freezing when do nothing for a few minutes and this person Videos in Epiphany problem this person is using loki so this problem is in loki and juno as far as i know. A: I had the same issues on two different computers, one with Intel HD4400 and one with Intel HD620 CPU/GPU. This is how I resolve the problem: Install Updated Open Graphics Drivers PPA sudo add-apt-repository ppa:oibaf/graphics-drivers sudo apt update This will update your Mesa graphics drivers but most importantly your xserver-xorg-video-* driver. A note of caution: It's been known for these drivers to have some issues so I would suggest that after the update, if everything works, remove this PPA from your sources list. Create /etc/X11/xorg.conf.d/20-intel.conf file with this content: Section "Device" Identifier "Intel Graphics" Driver "intel" Option "AccelMethod" "sna" Option "DRI" "3" Option "TearFree" "true" Option "Backlight" "intel_backlight" EndSection Install mpv Media Player. Not gnome-mpv but mpv. Use this for playing your local videos. The 1. and 2. did manage to remove all my video-in-browser troubles, I even get to have hardware acceleration in Google Chrome without any issues. Number 3. helped me with the local video files. There is a good reading on this here: IntelQuickSyncVideo In case you don't have the command add-apt-repository Run: sudo apt install software-properties-common and then redo the previous command who contains add-apt-repository
{ "pile_set_name": "StackExchange" }
Q: Wix custom action is failed to load the dll file? I am trying to do a custom action at the time of msi installation. But the dll required for my custom action is depends on other dlls. At the time of installtion it is giving the error like "a dll required for this install to complete could not run".How can I load the dependent dll files for this custom action to run properly. The code that I am using is <CustomAction Id='CheckingPID' BinaryKey='CheckPID' DllEntry='ValidateKey' /> <Binary Id ='CheckPID' SourceFile='$(sys.CURRENTDIR)\LicenseKeyClient_32d.dll'/> <Binary Id ='CheckPID2' SourceFile='$(sys.CURRENTDIR)\curllib.dll'/> <Binary Id ='CheckPID3' SourceFile='$(sys.CURRENTDIR)\libsasl.dll'/> <Binary Id ='CheckPID4' SourceFile='$(sys.CURRENTDIR)\openldap.dll'/> A: The files that you add in binary table usually get extracted with temporary names during the installation, so your DLL will not be able to locate the other DLLs you add next to it. A workaround is to add those DLLs as normal files in the Temp system folder and delete them when the installation ends. This has the limitation that you need to set your custom action as deferred, so it executes after the files are installed, thus your DLLs get copied to Temp folder. I don't know if wix has a support for temporary files, similar with the one present in Advanced Installer, but if not you could try to write a custom action to simulate it. Basically what Advanced Installer does is to extract those files in the Temp folder the moment the MSI is launched, and also deletes them when the installation is complete. This has the advantage that you can use the temporary files and in immediate custom actions, i.e. well before the files from your package are installed.
{ "pile_set_name": "StackExchange" }
Q: Создание системы распознавания голоса Решил сделать что то умное и полезное, а именно систему для распознавания речи. Хочется сделать качественно, так что прошу советов: На каком языке писать что бы, в дальнейшем можно было бы легко перенести под *NIX и мобильные оси? Что бы была хорошая библиотека для работы с аудио, а именно она должна: - Работать со всеми распространёнными аудио форматами - Работать с микрофоном - С помощью нее можно было отфильтровать только голос A: Я бы разделил работу на два этапа: рисёрч и, собственно, реализация. Рисёрч я бы делал на чём-то вроде Java или C#, так как это очень сильно ускоряет разработку. Вы сможете сравнительно быстро реализовывать свои идеи и проверять их. В случае, если удастся найти правильные решения, можно уже браться за проектирование реализации. И вот тут-то я бы советова взяться за C++, так как он действительно хорошо переносится. Разве что с iOS не уверен, что там у них. "- С помощью нее можно было отфильтровать только голос" - если вы ставите такое условие к библиотеке дял работы со звуком, то это значит, что вы ещё ОЧЕНЬ далеки от темы. Ваша система должна уметь самостоятельно опознавать и отсеивать шумы. Никакая библиотека не может сделать это за вас. Единственное, что она могла бы сделать - это выделить определённый частотный диапазон, что, в общем, не гарантирует, что это обязательно голос. Работать с микрофоном и читать разные форматы.. в Java для рисёрча есть всё необходимое. Уверен, что в C# тоже должно быть. Чтобы читать что-то сложнее, чем WAV, могут понадобиться кодеки. Это всё можно нарыть. К сожалению, с кодеками могут начаться сложности в тот момент, когда речь пойдёт уже о финальной реализации и о всяких лицензиях. Стоит проявить осторожность в этом вопросе. UPD Напомнило старую шутку из абсурдопедии. В категории "как правильно" была старая статья про то, как найти чёрную кошку в тёмной комнате. Среди вариантов, есть способ, использующий нейронные сети: Обучаем нейронную сеть путём показа кошек, пойманных другими методами. Обученная нейронная сеть будет способна ловить кошек без вмешательства человека непостижимым для него способом. Остаётся разместить сеть в тёмной комнате.
{ "pile_set_name": "StackExchange" }
Q: Edit drop down but not showing selected value from mysql data base in php I am new to php, i created drop down which calling data from mysql data base, user selects option and its save to data base. Problem Arises in edit form in which its do not showing selected value. Drop Down code is below: $query = 'SELECT name FROM owner'; $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error()); //create selection list echo "<select name='owner'>\name"; while($row = mysql_fetch_row($result)) { $heading = $row[0]; echo "<option value='$heading'>$heading\n"; } echo "</select>" Please advise solution for the edit form. Thanks in Advance A: you must close <option> tag: echo "<option value='$heading'>$heading</option>"; A: $query = 'SELECT name FROM owner'; $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error()); //create selection list echo "<select name='owner'>\name"; while($row = mysql_fetch_row($result)) { $heading = $row[0]; ?> <option <?php if($heading=="SOMETHING") { echo "selected='selected'"; } ?> value="SOMETHING">SOMETHING</option> <option <?php if($heading=="SOMETHING2") { echo "selected='selected'"; } ?> value="SOMETHING2">SOMETHING2</option> <option <?php if($heading=="SOMETHING3") { echo "selected='selected'"; } ?> value="SOMETHING3">SOMETHING3</option> <?php } echo "</select>"
{ "pile_set_name": "StackExchange" }
Q: How to capture just words in a string line I am trying to capture only proper words from a string line using regex (i.e. points, commas, parenthesis, etc... are not desired). For example, if the input line is: So she was considering in her own mind (as well as she could), I would like to capture: So she was considering in .... Does anybody knows a way to do this? I'm new to regex unfortunately :S Cheers! A: This is the regex you need: \b[a-zA-Z]+\b See demo. Explanation \b is a word boundary that matches a position where one side is a letter, and the other side is not a letter (for instance a space character, or the beginning of the string) The character class [a-zA-Z] matches one character in the ranges a-z and A-Z The + quantifier says that we must match what precedes one or more times The \b boundary ensures that our word is finished. Together the two boundaries ensure we have a complete word. In Java In the comments, you mentioned that you'd like to see a list. You can use this: List<String> matchList = new ArrayList<String>(); Pattern regex = Pattern.compile("\\b[a-z]+\\b", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); Matcher regexMatcher = regex.matcher(subjectString); while (regexMatcher.find()) { matchList.add(regexMatcher.group()); } Note that I made the pattern case-insensitive.
{ "pile_set_name": "StackExchange" }
Q: Distribution of Current in Kirchoff's Junction Law I know that Kirchoff's law says that the incoming current is equal to outgoing current. But I want to understand his: suppose we have 4 wires like the one in diagram. So let us consider current i1, comes to the junction and gets split into three direction towards i2, i3, i4 and similar is the case with current i2 but then why we imagine only the current i3 and i4 as outgoing current whereas current is also going to i1 and i2. May be I am missing something but I am stuck on this problem for very long. A: It's just an example. You may imagine a different case or example if you want. Any of those current may be inflowing or outflowing, as long as total current inflowing equals total current outflowing. Also, currents inflow or outflow depending of the conditions in other nodes. If there is a negative voltage difference with respect to another node and an impedance low enough (i.e., finite) to it, then there will be an inflow of current.
{ "pile_set_name": "StackExchange" }
Q: css image in not showing in safari? the following code is not work in safari, but properly work in IE. <style> .my { background:url("../../myproject/images/add.gif"); width:100%; height:22px; background-repeat: no-repeat; } </style> <span class="my"> </span> A: By default a span element is display: inline so the height and width properties do not apply to it. Since it has no explicit dimensions, and no content, it is rendered as being 0 by 0. This doesn't leave any room for it to have a visible background. Use a different element (one which is block by default), or change the display property to one that height and width apply to to get this to work. That said, if you are just creating a box with no content, there is a very good chance you should just be using an img element in the first place. A: use backgound-image: url("../../myproject/images/add.gif"); or else use the background shortcut starting with a color:background:transparent url(...) no-repeat; And adding display:block; would allow you to set the height and width of the span element, but it will no longer line with other text.
{ "pile_set_name": "StackExchange" }
Q: Way to change icon of accessory type in UITableviewcell I have table view which is showing list of files to download. When I tap the accessory button it will download the selected file. I want to change image of detail disclosure button. Is it possible....? And If I use Button with image in accessory view. Is there any table delegate method for this... A: Answer2: You can make your own method and call that in that case. int row=indexPath.row; UIButton *trackImageOnMap=[[UIButton alloc] initWithFrame:CGRectMake(420, 9, 40, 50)]; [trackImageOnMap setImage:[UIImage imageNamed:@"track_map_icon.png"] forState:UIControlStateNormal]; int iId=[[self.imageId objectAtIndex:row] intValue]; NSLog(@"iId=%d",iId); [trackImageOnMap setTag:iId]; [trackImageOnMap addTarget:self action:@selector(trackImageOnMapButtonTouched:)forControlEvents:UIControlEventTouchDown]; [trackImageOnMap setContentMode:UIViewContentModeScaleToFill]; //[cell setAccessoryView:trackImageOnMap]; [cell addSubview:trackImageOnMap]; A: You could create a UIImageView and assign it to the UITableViewCell's accessoryView. UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"accessoryIcon"]] autorelease]; cell.accessoryView = imageView; If you want a button for the accessoryView it's basically the same: UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setImage:[UIImage imageNamed:@"buttonImage"] forState:UIControlStateNormal]; [button addTarget:self action:@selector(someAction:) forControlEvents:UIControlEventTouchUpInside]; button.tag = cell.indexPath; cell.accessoryView = button;
{ "pile_set_name": "StackExchange" }
Q: controlling the android status bar icon I am trying to exercise a little control over the state of an icon in the status bar. I want to be able to do the following: Keep the icon visible in the status bar, as long as the app is running, EVEN IF the user chooses to clear the status bar. Clear the icon from the status bar if the app is exited, even (especially) if it is killed? I realize I can remove it when the app is exited explicitly, but I want to make sure it goes away if the app is killed. I have to admit I have not tried this yet. I have not been able to get some good info on this, although I have seen apps that appear to be doing this. A: 1) Take a look at the developer docs page on status bar notifications. Also note that you'll want to look at the FLAG_NO_CLEAR constant, which should cover your condition. 2) Keeping the icon isn't necessarily a bad thing in the case where the app is killed, and somewhat depends on the purpose of the app. In particular, if your app goes into the background and then gets killed, leaving the icon has actually been noted to be expected behavior by one of Google's engineers: Correct, onDestroy() is not called when it is killed. This is the same as activity -- the kernel kills processes when needed, not waiting for the app. The status bar is correctly keeping the icon. The service will later be restarted; it has not been stopped. It is normal for background services to be killed regularly. This is intentional, because generally background services are not something the user is directly aware of, and restarting their processes every now and then avoids issues with such services consuming increasing amounts of RAM. If your service is something the user is actually aware of (such as music playback), consider Service.startForeground(). That being said, the icon should probably disappear anyway. Other apps with persistent icons (Meebo comes to mind) will clear away if you kill them with a task manager. I'm not certain if this happens in all cases, though. If your app gets killed while in the background by the OOM, then you most likely won't want to clear it anyway.
{ "pile_set_name": "StackExchange" }
Q: Django admin.site.register throws TypeError for models class This is a follow-on question to this question. I would like to automate the import of classes from a django models.py file and then register each with admin.site.register(). Here is my code: from django.contrib import admin import inspect from . import models for name, obj in inspect.getmembers(models): if inspect.isclass(obj): admin.site.register(obj) This code throws a TypeError: 'type' object is not iterable. The OP marked this question as answered and I've found several other examples where this code is presented. I've also reviewed the documentation here and didn't see anything that would indicate that this is wrong. Full Traceback: Bills-MacBook-Pro:Pro billarmstrong$ python manage.py runserver/anaconda3/lib/python3.6/site-packages/django/db/models/base.py:309:RuntimeWarning: Model 'ProWP.p_item' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models. new_class._meta.apps.register_model(new_class._meta.app_label, new_class)/anaconda3/lib/python3.6/site-packages/django/db/models/base.py:309:RuntimeWarning: Model 'ProWP.p_item' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models. new_class._meta.apps.register_model(new_class._meta.app_label, new_class) Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x108f1dea0> Traceback (most recent call last): File "/anaconda3/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/anaconda3/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/anaconda3/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/anaconda3/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/anaconda3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/anaconda3/lib/python3.6/site-packages/django/apps/registry.py", line 120, in populate app_config.ready() File "/anaconda3/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/anaconda3/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/anaconda3/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/billarmstrong/Documents/GitHub/Core/WebDataCollect/Pro/ProWP/admin.py", line 7, in <module> admin.site.register(obj) File "/anaconda3/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 102, in register for model in model_or_iterable: TypeError: 'type' object is not iterable After runserver a second time there is a new warning - but that wasn't part of the original error. I included everything for reference. The p_item is a class object in models.py Final Edit The warning noted above was a result of a sloppy cut/paste that duplicated a class. It is irrelevant to the original question or the answer below. A: At a guess, there are not only django.db.models.Model classes imported. Probably, your local models module contains a few more items, including other classes (which makes the if inspect.isclass pass). You may want to perform an additional issubclass(obj, django.models.Model) or similar check. The fact that it works in the linked question, suggests you have additional code in your local models.py module, possibly through from imports (making it hard to notice). But an additional check to see that obj is an actual Django model (as mentioned above), is probably safer than trying to remove that extra code. All in all, try the following (untested): from django.contrib import admin from django.db.models import Model import inspect from . import models for name, obj in inspect.getmembers(models): if inspect.isclass(obj) and issubclass(obj, Model): admin.site.register(obj)
{ "pile_set_name": "StackExchange" }
Q: Passing data between segue with Swift 2.0 I seem to be following tutorials to the tee yet I can't get my data to pass to my second view controller without being nil. I am new to Swift so I'm probably also not using optionals correctly. Here is how I have my code set up. import UIKit class DetailsViewController: UIViewController { var book : PLBook? override func viewDidLoad() { super.viewDidLoad() //View Did Load print(self.book) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } } Then this is how I am presenting the second view controller and preparing for segue. override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("toDetailVC", sender:self) } //MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "toDetailVC"){ //prepare for segue to the details view controller if let detailsVC = sender?.destinationViewController as? DetailsViewController { let indexPath = self.tableView.indexPathForSelectedRow detailsVC.book = self.books[indexPath!.row] } } } In the second view controller, the book var is always nil. Any ideas how I can get the data to pass? A: Try This: override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "toDetailVC") { //prepare for segue to the details view controller let detailsVC = segue.destinationViewController as! DetailsViewController let indexPath = self.tableView.indexPathForSelectedRow detailsVC.book = self.books[indexPath!.row] } A: You should be using segue.destinationViewController, not sender?.destinationViewController.
{ "pile_set_name": "StackExchange" }
Q: Why can't I report a bad answer on Super User? I saw a bad answer here. I understand why, as a new user, I can't do certain things like comment. But reporting is something I should be able to do. What reason is there for limiting new users from reporting bad answers, like this one? Edit: Just as I posted this, someone deleted the bad answer. My question still stands, however. A: Flagging requires reputation because we do not want every newly registered user to be able to flag. As @rene says, it takes a while to know what needs to be flagged and what not (even 15 reputation is rather low). Lowering the reputation threshold will make reporting easier but lead to more noise, which makes flag handling (by the community in the review queues, and by ♦ moderators) a lot less efficient. Note that an exception has been made (as part of the Welcoming initiative) for flagging comments on your own posts; for that, no reputation is required. If you're feeling harassed, which hopefully doesn't come up too often, you should be able to do something about it (other than replying, which often makes matters worse). Another exception is flagging your own post, e.g. when it was deleted and you've edited into better shape. You can then use a flag to ask the ♦ moderators to undelete it. In your case, on another person's question, there's not much you can do about it without a bit of reputation. But don't worry; we have a lot of active users who will notice it too, and know how to use their flags.
{ "pile_set_name": "StackExchange" }
Q: Akka - StackOverflowError during object serialization I'm with a problem that extends for more than 2 days. When I'm exchanging messages between actors, is accusing the JVM stack overflow. My message is an object with many links (10000+ child objects linked together in a linked list). Namely, an object with Neo4J relationships. The error is this: java.lang.StackOverflowError at java.io.Bits.putLong(Bits.java:108) at java.io.ObjectOutputStream$BlockDataOutputStream.writeLong(ObjectOutputStream.java:1928) at java.io.ObjectOutputStream.writeLong(ObjectOutputStream.java:788) at java.util.Date.writeObject(Date.java:1303) at sun.reflect.GeneratedMethodAccessor41.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1469) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400) Does anyone have any solution for this? thanks A: Are you using java.util.LinkedList, or a custom linked list of your own? If the latter, you need to write a custom writeObject() method for it that avoids the recursion that would happen if you didn't have one.
{ "pile_set_name": "StackExchange" }
Q: Using JavaScript for Google geocoding I wrote the script below, based on Google documentation: https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingAddressTypes However, the script doesn't work. I ran the original google script at the link above, it works. I can not figure out which part of the code has error. Thanks <!DOCTYPE html> <html> <body> <script> var geocode_file_path = "C:\\Hello.txt"; createFile(geocode_file_path); var geocoder; initialize(); geocodeAddress(geocoder); function initialize() { geocoder = new google.maps.Geocoder(); } function geocodeAddress(geocoder) { var addresses = ['121 Dartmouth Street, Boston, MA', 'Boston, USA']; var arrayLength = addresses.length; for (var i = 0; i < arrayLength; i++) { var address = addresses[i]; geocoder.geocode({'address': address}, function (results, status) { alert('ok') if (status === google.maps.GeocoderStatus.OK) { var result = results[0].geometry.location; var name = results[0].formatted_address; alert(result) writeFile(geocode_file_path, name + ': ' + result.toString()); } else { alert('Geocode was not successful for the following reason: ' + status); } }); } } function createFile(afile) { var fso = new ActiveXObject("Scripting.FileSystemObject"); var outFile = fso.CreateTextFile(afile, true); outFile.WriteLine('Geocoded Locations:'); outFile.Close(); } function writeFile(afile, str) { var fso = new ActiveXObject("Scripting.FileSystemObject"); var outFile = fso.OpenTextFile(afile, 8, true); outFile.WriteLine(str); outFile.Close(); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=Mykey"> </script> </body> </html> A: You should call the external Google maps script first. Also remove the async and defer attributes from the script tag because the API script is a direct dependency of your script and you want it to be executed in order. <!DOCTYPE html> <html> <body> <script src="https://maps.googleapis.com/maps/api/js?key=Mykey"></script> <script> var geocode_file_path = "C:\\Hello.txt"; createFile(geocode_file_path); var geocoder; initialize(); geocodeAddress(geocoder); function initialize() { geocoder = new google.maps.Geocoder(); } function geocodeAddress(geocoder) { var addresses = ['121 Dartmouth Street, Boston, MA', 'Boston, USA']; var arrayLength = addresses.length; for (var i = 0; i < arrayLength; i++) { var address = addresses[i]; geocoder.geocode({'address': address}, function (results, status) { alert('ok') if (status === google.maps.GeocoderStatus.OK) { var result = results[0].geometry.location; var name = results[0].formatted_address; alert(result) writeFile(geocode_file_path, name + ': ' + result.toString()); } else { alert('Geocode was not successful for the following reason: ' + status); } }); } } function createFile(afile) { var fso = new ActiveXObject("Scripting.FileSystemObject"); var outFile = fso.CreateTextFile(afile, true); outFile.WriteLine('Geocoded Locations:'); outFile.Close(); } function writeFile(afile, str) { var fso = new ActiveXObject("Scripting.FileSystemObject"); var outFile = fso.OpenTextFile(afile, 8, true); outFile.WriteLine(str); outFile.Close(); } </script> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: rust borrow check looks very smart , it can check and flat reads and writes of loop. but how can I bypass it? rust borrow check looks very smart , it can check and flat reads and writes of loop. but how can I bypass it? Following code works well: fn main() { let mut lines = [ vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9], ]; for i in 0 .. lines.len() { let line = &lines[i]; for item in line { // if found odd number, push zero! if item % 2 == 1 { lines[i].push(0); break; // works fine! if comment it, will error! } } } dbg!(lines); } When comment the "break" line, will got: error[E0502]: cannot borrow `lines[_]` as mutable because it is also borrowed as immutable --> src/main.rs:13:17 | 10 | let line = &lines[i]; | --------- immutable borrow occurs here 11 | for &item in line { | ---- immutable borrow later used here 12 | if item == 5 { 13 | lines[1].push(55); | ^^^^^^^^^^^^^^^^^ mutable borrow occurs here error: aborting due to previous error A: You don't bypass the borrow checker. You consider what it tells you and reconsider your program to match. Here it tells you that you can't modify something you're currently iterating on (r^w principle), so don't do that. If you want to add as many zeroes as there are odd number in each line, do that: count the number of odds in the line, then add that many zeroes: use std::iter::repeat; fn main() { let mut lines = [ vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9], ]; for line in lines.iter_mut() { let odds = line.iter().filter(|it| *it % 2 == 0).count(); line.extend(repeat(0).take(odds)); } dbg!(lines); }
{ "pile_set_name": "StackExchange" }
Q: select and update based on a child objects property minimum value using Linq I have a Type Supplier that has a property SupplierId and a another property NearestLocation which is a of Type SupplierLocation, the SupplierLocation consists of properties SupplierId and DistanceFromDevice class Supplier { public int SupplierId { get; set; } public SupplierLocation NearestLocation { get; set; } } class SupplierLocation { public int SupplierId { get; set; } public decimal DistanceFromDevice { get; set; } public double Longitude { get; set; } public double Latitude {get; set;} } I have a List of all my Supplierlocations a supplier can have a n number of locations. I have also calculated the DistanceFromDevice property for each location. I have a List whose id's can be found in the SupplierLocations List. What I would like to do using linq is to join my supplier to the SupplierLocation by the SupplierId and populate the NearestLocation Property of the Supplier class with the the Location that has the least DistanceFromDevice value of all the locations for that particular supplier. Hope this makes sense. Can this be done using linq. Many thanks in advance. Paul A: Here is a working example in LINQPad void Main() { var suppliers = new List<Supplier> { new Supplier() {SupplierId = 1}, new Supplier() {SupplierId = 2}, new Supplier() {SupplierId = 5} }; var locations = new List<SupplierLocation> { new SupplierLocation {SupplierId = 1, DistanceFromDevice = 10, Latitude = 1, Longitude = 2}, new SupplierLocation {SupplierId = 1, DistanceFromDevice = 20, Latitude = 1, Longitude = 3}, new SupplierLocation {SupplierId = 1, DistanceFromDevice = 30, Latitude = 1, Longitude = 4}, new SupplierLocation {SupplierId = 1, DistanceFromDevice = 40, Latitude = 1, Longitude = 5}, new SupplierLocation {SupplierId = 2, DistanceFromDevice = 10, Latitude = 2, Longitude = 2}, new SupplierLocation {SupplierId = 2, DistanceFromDevice = 20, Latitude = 2, Longitude = 3}, new SupplierLocation {SupplierId = 3, DistanceFromDevice = 10, Latitude = 3, Longitude = 2} }; var result = from s in suppliers join l in locations on s.SupplierId equals l.SupplierId into grp where grp.Count() > 0 select new Supplier() { SupplierId = s.SupplierId, NearestLocation = grp.OrderBy (g => g.DistanceFromDevice).First()}; result.Dump(); } class Supplier { public int SupplierId { get; set; } public SupplierLocation NearestLocation{ get; set; } } class SupplierLocation { public int SupplierId { get ;set; } public decimal DistanceFromDevice { get; set; } public double Longitude { get; set; } public double Latitude {get; set;} }
{ "pile_set_name": "StackExchange" }
Q: Angular Constant Best Practice I have an angular constant which defines webservice end point angular.module('myModule').constant('mywebservice_url', 'http://192.168.1.100') The problem is that for dev I have a different end point while staging and production its different. Every time I try to check in to git I have to manually reset this file. Is there any way git permenantly ignore this file but checks out the file while clone or checkout? Is there any way I can make angular pickup file dynamically from something like environment variable. NOTE: I don't want to depend on server to do this, ie I don't want to use apach SSI or any of those technologies as it will work only one set of servers. A: Delaying the injection via backend processing. I usually just create a global object on html page called pageSettings which values like this is getting injected from the backend, i.e. environment variables, etc. and just pass that global pageSettings object into that angular constant or value. Build system injection. If you don't have a backend, i.e. pure SPA... maybe you can put this inside your build system, i.e. create multiple task for building the different environments in gulp or grunt and replace that value during the build process.
{ "pile_set_name": "StackExchange" }
Q: HTML form doesn't submit input data into URL I have an HTML form with the following code: <form action="search/" method="get"> <input type="search" value="search for..." id="search" /> </form> When I hit the ENTER key, it submits to the specified page in the action attribute, BUT it doesn't ADD the input value to the URL. I would like someone searching for "politician" keyword GOING to something like "kereso/politician" I'm using HTACCESS to manage SEO friendly URLs with the following code. RewriteEngine On RewriteCond %{HTTP_HOST} ^haromszekirmdsz.ro RewriteRule (.*) http://www.haromszekirmdsz.ro/$1 [R=301,L] RewriteCond %{SCRIPT_FILENAME} !-f RewriteCond %{SCRIPT_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 php_flag magic_quotes_gpc Off A: You are not giving the name attribute in the input field <input name="url" .......... /> A: You need to add a name attribute to the input field. <input type="search" value="search for..." name="search" />
{ "pile_set_name": "StackExchange" }
Q: A error about 800700c1 When I run a C# example from sterling website.It appeared an error 'Retrieving the COM class factory for component with CLSID {B9A792C1-9922-4DF7-B4AC-994EC261D92C} component failed due to the following error: 800700c1.'.The error code is private SterlingLib.STIOrderMaint stiMaint = new SterlingLib.STIOrderMaint(); A: I used Sterling ActiveX API in my code before. Maybe you should log in to Sterling before executing your program. Without login, instances of some interfaces can't be created.
{ "pile_set_name": "StackExchange" }
Q: Manage User Roles based on Projects in rails and mongoid I am using rails and MongoId. I have 3 models - User, Project and Role. I want to manage user roles based on projects. For example: user1 has assigned to 2 projects, for project1 user1 may be admin, for project2 user1 may be a Quality Analyst. How I can achieve this when using mongoid in rails. Thanks in Advance. A: You can use rolify and add multiple roles to user and in Project model filter if a user has a specified role and manage it.
{ "pile_set_name": "StackExchange" }
Q: static stylesheets gets reloaded with each post request Every time there is a post from page the entire bunch of css gets reloaded. Is it possible to tell them not to come in again and again. There is a series of GET that get fired. Can we optimize in some way or is it normal behavior? The environment is google apps in python. A: Check out Using Static Files and Handlers for Static Files. Since the latter link refer to cache duration of static files, I believe the the caching functionality is possible. Unlike a traditional web hosting environment, Google App Engine does not serve files directly out of your application's source directory unless configured to do so. We named our template file index.html, but this does not automatically make the file available at the URL /index.html. But there are many cases where you want to serve static files directly to the web browser. Images, CSS stylesheets, JavaScript code, movies and Flash animations are all typically stored with a web application and served directly to the browser. You can tell App Engine to serve specific files directly without your having to code your own handler.
{ "pile_set_name": "StackExchange" }
Q: How do I convert a string containing a hexadecimal pair to a byte? I have a string containing a hexadecimal value. Now I need the content of this string containing the hexadecimal as a byte variable. How should I do this without changing the hexadecimal value? A: An alternative to the options posted so far: byte b = Convert.ToByte(text, 16); Note that this will return 0 if text is null; that may or may not be the result you want.
{ "pile_set_name": "StackExchange" }
Q: Create Dynamic Func from Object I have a criteria object in which I was to turn each property into a func, if it's value isn't null. public class TestClassCriteria { public bool? ColumnA { get; set; } public bool? ColumnB { get; set; } } This is what I have thus far, but I am pretty sure I am not defining the lambda correct. This is what I trying to achieve. funcs.Add(x => x.ColumnA == criteria.ColumnA). var properties = criteria.GetType().GetProperties(); var funcs = new List<Func<dynamic, bool>>(); foreach (var property in properties) { var propertyName = property.Name; funcs.Add(x => x.GetType().GetProperty(propertyName).Name == criteria.GetType().GetProperty(propertyName).Name); } It's not crashing or causing any error, it just isn't working. Any help you can provide would be greatly appreciated. A: Do you want something like this? static List<Func<TEntity, TCriteria, bool>> GetCriteriaFunctions<TEntity, TCriteria>() { var criteriaFunctions = new List<Func<TEntity, TCriteria, bool>>(); // searching for nullable properties of criteria var criteriaProperties = typeof(TCriteria) .GetProperties() .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)); foreach (var property in criteriaProperties) { // this is entity parameter var entityParameterExpression = Expression.Parameter(typeof(TEntity)); // this is criteria parameter var criteriaParameterExpression = Expression.Parameter(typeof(TCriteria)); // this is criteria property access: "criteria.SomeProperty" var criteriaPropertyExpression = Expression.Property(criteriaParameterExpression, property); // this is testing for equality between criteria property and entity property; // note, that criteria property should be converted first; // also, this code makes assumption, that entity and criteria properties have the same names var testingForEqualityExpression = Expression.Equal( Expression.Convert(criteriaPropertyExpression, property.PropertyType.GetGenericArguments()[0]), Expression.Property(entityParameterExpression, property.Name)); // criteria.SomeProperty == null ? true : ((EntityPropertyType)criteria.SomeProperty == entity.SomeProperty) var body = Expression.Condition( Expression.Equal(criteriaPropertyExpression, Expression.Constant(null)), Expression.Constant(true), testingForEqualityExpression); // let's compile lambda to method var criteriaFunction = Expression.Lambda<Func<TEntity, TCriteria, bool>>(body, entityParameterExpression, criteriaParameterExpression).Compile(); criteriaFunctions.Add(criteriaFunction); } return criteriaFunctions; } Sample entity and sample criteria: class CustomerCriteria { public int? Age { get; set; } public bool? IsNew { get; set; } } class Customer { public string Name { get; set; } public int Age { get; set; } public bool IsNew { get; set; } } Usage: var criteriaFunctions = GetCriteriaFunctions<Customer, CustomerCriteria>(); var customer1 = new Customer { Name = "John", Age = 35, IsNew = false }; var customer2 = new Customer { Name = "Mary", Age = 27, IsNew = true }; var criteria1 = new CustomerCriteria { Age = 35 }; var criteria2 = new CustomerCriteria { IsNew = true }; Console.WriteLine("Is match: {0}", criteriaFunctions.All(f => f(customer1, criteria1))); Console.WriteLine("Is match: {0}", criteriaFunctions.All(f => f(customer2, criteria1))); Console.WriteLine("Is match: {0}", criteriaFunctions.All(f => f(customer1, criteria2))); Console.WriteLine("Is match: {0}", criteriaFunctions.All(f => f(customer2, criteria2))); Instead of your code with dynamics, this code uses strongly typed member access, so, you could cache list of criteria for each pair "Entity - Criteria" and test instances form matching faster.
{ "pile_set_name": "StackExchange" }
Q: what is this C++ deserialization idiom? calling a file-reader function with an integer ID variable as `reinterpret_cast(&id)?` I'm reading through the internals SeqAn library (which handles biology-specific file formats and data structures) and I'm coming across what must be a c++ idiom which I don't quite understand. There's a unique id variable record.rID that is an __int32. A pointer to it gets passed to another function that reads a bunch of data from a file and mutates the id. Here's the call: res = streamReadBlock(reinterpret_cast<char *>(&record.rID), stream, 4); Here's the function implementation: inline size_t streamReadBlock(char * target, Stream<Bgzf> & stream, size_t maxLen) { if (!(stream._openMode & OPEN_RDONLY)) return 0; // File not open for reading. // Memoize number of read bytes and pointer into the buffer target. size_t bytesRead = 0; char * destPtr = target; // Read at most maxLen characters, each loop iteration corresponds to reading the end of the first, the beginning of // the last or the whole "middle" buffers. Of course, the first and only iteration can also only read parts of the // first buffer. while (bytesRead < maxLen) { // If there are no more bytes left in the current block then read and decompress the next block. int available = stream._blockLength - stream._blockOffset; if (available <= 0) { if (_bgzfReadBlock(stream) != 0) return -1; // Could not read next block. available = stream._blockLength - stream._blockOffset; if (available <= 0) break; } // Copy out the number of bytes to be read or the number of available bytes in the next buffer, whichever number // is smaller. int copyLength = std::min(static_cast<int>(maxLen - bytesRead), available); char * buffer = &stream._uncompressedBlock[0]; memcpy(destPtr, buffer + stream._blockOffset, copyLength); // Advance to next block. stream._blockOffset += copyLength; destPtr += copyLength; bytesRead += copyLength; } // If we read to the end of the block above then switch the block address to the next block and mark it as unread. if (stream._blockOffset == stream._blockLength) { stream._blockPosition = tell(stream._file); stream._blockOffset = 0; stream._blockLength = 0; } return bytesRead; } Doing a bit of tracing, I can see that record.rID is getting assigned in there, I guess where that memcpy(destPtr, buffer + stream._blockOffset, copyLength); occurs, but I don't quite understand what's going on and how a meaningful record id is getting assigned (but then I don't have too much experience dealing with this kind of deserialization code). A: It's a clever way of writing to an int. By casting the address of record.rID as a pointer to a char, you may directly write bytes to it with memcpy.
{ "pile_set_name": "StackExchange" }
Q: Energy gap in Parent hamiltonian of MPS Given a block injective matrix product state (MPS) with D blocks, how does the energy gap of corresponding parent hamiltonian scale with D? And is there a good reference which gives an analysis of this? Thanks. A: The gap of the parent Hamiltonian does not depend on the number $D$ of blocks (at least not directly). The spectral gap of the parent Hamiltonian in the block-injective case is analyzed and a lower bound is given in B. Nachtergaele, Commun. Math. Phys. 175, 565 (1996), arXiv:cond-mat/9410110.
{ "pile_set_name": "StackExchange" }
Q: DB2 SQL Optimization suggestion Please help me check the sql, is there any problem? can it be optimized? It will take long time to execute, but not always. SELECT count(*) FROM DB2INST3.VWQueue1_119 WHERE inbasketName is not null AND userid1 is not null AND nItemIndex is not null AND string1 is not null AND (F_BoundUser = ? OR F_BoundUser = ? ) AND (F_Locked < 2) AND ((inbasketName='PSIQUEUE1Index') AND (inbasketName='PSIQUEUE1Index')) Got the snapshot as: Number of executions = 12942 Number of compilations = 1 Worst preparation time (ms) = 6 Best preparation time (ms) = 6 Internal rows deleted = 0 Internal rows inserted = 0 Rows read = 1399262666 Total execution time (sec.microsec)= 3600.704315 Total user cpu time (sec.microsec) = 2538.101110 Total system cpu time (sec.microsec)= 0.191321 A: Here is a simplification of your query: SELECT count(*) FROM DB2INST3.VWQueue1_119 WHERE userid1 is not null and nItemIndex is not null and string1 is not null and (F_BoundUser in (?, ?) and (F_Locked < 2) and (inbasketName = 'PSIQUEUE1Index') Here are the changes: The condition inbasketName='PSIQUEUE1Index' is mentioned twice. Npt necessary. The condition inbasketName is not null is redundant, because the value is being compared to a string. The only index that would most help is: VWQueue1_119(inbasketName, F_BoundUser, F_Locked). If there is a large amount of other columns in the table, then adding userid1, nItemIndex, and string1 would create a covering index so the original data pages are not touched.
{ "pile_set_name": "StackExchange" }
Q: JavaScript function for retrieving multiple querystring values This function works only for a parameter. function getQueryStringValue(key) { debugger; return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1")); }; Please I need a JavaScript function that can retrieve more than one querystring parameter, I need to pass the name of the parameter as key to the function. Thank you The function in the link Alex shared is as below function getParameterByName(name, url) { if (!url) { url = window.location.href; } name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); }; With my url as this: var url= 'search-results.html?param1=unth?param2=lagos'; And I pass this to the function : var param1 = getParameterByName('param1'); var param2 = getParameterByName('param2'); It return param1 as : luth?param2=lagos instead of luth. This is the same issue with the function I shared. My question is a JavaScript Function that retrieves multiple querystring parameter but the function works only for one parameter A: Your URL should be: var url= 'search-results.html?param1=unth&param2=lagos'; In this case function will work. var param1 = getParameterByName('param1'); //return unth var param2 = getParameterByName('param2'); //return lagos
{ "pile_set_name": "StackExchange" }
Q: Store multiple json object in to a text file iOS When there is no internet connection on device, i am storing the json in to a text file. But the problem is, if i do again it is getting replaced. Here is what i am doing for store into a text file. How to store multiple json object in a text file.When i get connection i need to post json to server. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docDir = [paths objectAtIndex:0]; NSString *filePath = [docDir stringByAppendingPathComponent:@"File.json"]; [jsonString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error]; Please advice. A: That's not so straight forward as concatenating multiple JSON files does not result in a valid JSON file. To do this properly requires you to read and parse the existing JSON file, which will give you an NSArray or NSDictionary top-level object, then append the data from the new JSON file and write the whole thing out. That is inefficient as you are processing old data. Therefore I would suggest you write new data to a new file, using the current date/time for the filename, and when it's time to upload, read each of the files and upload them individually, one-at-a-time. Then delete each file as it's uploaded.
{ "pile_set_name": "StackExchange" }
Q: Microsoft Moles not creating moles for several methods I am having a problem getting a couple of the static methods in my class to be moled, as well as getting the Diagnostics attribute in the .moles file to be recognized. My environment: Visual Studio 2008 Pex/Moles version 0.94.51023.0 The signature of the one method in particular that I need and can't get a moled reference to: private static List<MaxBet> GetByPaytableDenom(int? paytableDenomId, int? paytableId, int? denomId, int? instanceId) I have even tried changing it to public static or private (not static) and recompiled and can't get it to show up at all. It is one of 5 overloaded signatures of the same method. This one and one other aren't getting moled. So I then tried turning on Diagnostics and Verbosity in my .mole file: <Moles xmlns="http://schemas.microsoft.com/moles/2010/" Diagnostic="true" Verbosity="Noisy"> And when I check the Output window and select the drop-down box to go to the Moles output, I am only getting this: -- Moles vs build action build started adding 2 assemblies adding C:\WMS_2008\Development 4.X\BugFixes\Main 4.X\SourceNG\TestProjects\UnitTestProjects\BusinessLayerUnitTests\MolesAssemblies\WMS.NG.SSG.BusinessLayer.Moles.dll adding C:\WMS_2008\Development 4.X\BugFixes\Main 4.X\SourceNG\TestProjects\UnitTestProjects\BusinessLayerUnitTests\MolesAssemblies\WMS.NG.SSG.DataLayer.Moles.dll -- Moles update finished What gives? I can't seem to figure this one out. Cindy A: I know now that the non-static methods show up in the AllInstances property of the moled class. Thanks, Cindy
{ "pile_set_name": "StackExchange" }