title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
Upload JAR to Nexus OSS 3
<p>I have just installed Nexus OSS 3.0.1-01 on my server and I don't know how to upload artifacts to my maven repository. I need to upload JDBC and other dependencies to it, but I cannot find how!</p> <p>It seems there is no section "Upload artifacts" as Nexus 2.</p>
2
Calling UWP C# code from UWP c++/cx
<p>I have an UWP C++/cx application and UWP C# class library.<br> How can i use classes from c# library in c++ project?</p> <ul> <li>C++/CLI not supported by UWP apps so i cant make c++/cli wrapper. </li> <li>Im not sure but looks like COM wrapping isnt an option in UWP world. </li> <li>Reverse P/Invoke is not an option as host application is c++ </li> <li>Windows Runtime Component also will require kind of callback from C# code, but it can be instantiated in c++ code only. </li> </ul> <p>Any suggestions?</p> <p>P.S.<br> I cannot have "c# proxy app", my app is of type c++/cx.</p>
2
How can I assign a css style to an on the fly created element?
<p>I'm creating a rectangle in code and placing it inside a <code>HBox</code> created in scenebuilder. I then apply an already existing css style to it. The rectangle doesn't even show unless I specify a height and width when creating it (even though the css style already specifies height and width). However when I do manage to get it to show, the css style is not applied. I have no idea why this is happening and am hoping that someone can help me! Thanks</p> <pre><code>Rectangle rect = new Rectangle(); timesheetSlots.getChildren().addAll(rect); rect.getStyleClass().add("timesheetSlot"); </code></pre> <pre class="lang-css prettyprint-override"><code>.timesheetSlot{ -fx-background-color: #ff6600; -fx-width: 20; -fx-height: 25; -fx-cursor: hand; } .timesheetSlot:hover{ -fx-background-color: #ffffff; } .timesheetSlotSelected{ -fx-background-color: #1Eff00; -fx-max-height: 25; -fx-max-width: 20; -fx-cursor: hand; } </code></pre>
2
excel vba make a cell flash/blink
<p>I am trying to get a cell to flash for a finite time. The code I have so far (with help from another member) is:</p> <pre><code>Option Explicit Dim waitTime As Date, stopTime As Date Function startFlash(x As String) Beep stopTime = Now + TimeSerial(0, 2, 0) 'Debug.Print stopTime Call sflash MsgBox "done" End Function Sub sflash() Sheet1.Range("c8").Font.ColorIndex = 3 Do While waitTime &lt;= stopTime With Sheet1.Range("c8").Font If .ColorIndex = 3 Then .ColorIndex = 5 Else .ColorIndex = 3 End If End With waitTime = Now + TimeSerial(0, 0, 5) 'Debug.Print Now; waitTime; stopTime Do While Now &lt; waitTime: DoEvents: Loop Loop End Sub </code></pre> <p>This procedure is called from a cell in a worksheet with the following code:</p> <pre><code>=if(C8&gt;25,"yup",startFlash(C8)) </code></pre> <p>And C8 has a number placed into it.</p> <p>When it runs it successfully and properly goes through the loops and the colorIndex value does change with every iteration. However, cell C8 does not change color until I hit ok after the message "done" pops up. </p> <p>I have tried it with and without </p> <pre><code>application.screenupdating = false/true </code></pre> <p>before and after 'with'/'end with'.</p> <p>I cannot find a solution to make the cell change color when the ColorIndex changes i.e. make the cell flash/blink. Any help would be appreciated.</p>
2
Hibernate Lazy Loading Issue
<p>I mapped this entity in Hibernate 5</p> <pre><code>class A { private String code; private B child; @LazyToOne(LazyToOneOption.PROXY) @ManyToOne(fetch=FetchType.LAZY) @NotFound(action=NotFoundAction.IGNORE) @JoinColumns({...}) public B getChild() { ... } } </code></pre> <p>And my query to load <strong>only A</strong> is:</p> <pre><code>from A where a.code like :q </code></pre> <p>With this configuration Hibernate makes a select on A and on B entities. I don't want it to load B but only A</p> <p>What am I missing? </p>
2
Why can I update TableView from a non-UI thread but not ListView?
<p>I have encountered something odd in JavaFX (java version 1.8.0_91). It was my understanding that if one wants to update the UI from a separate thread, one must either use <code>Platform.runLater(taskThatUpdates)</code> or one of the tools in the <code>javafx.concurrent</code> package. </p> <p>However, if I have a <code>TableView</code> on which I call <code>.setItems(someObservableList)</code>, I can update <code>someObservableList</code> from a separate thread and see the corresponding changes to my <code>TableView</code> without the expected <code>Exception in thread "X" java.lang.IllegalStateException: Not on FX application thread; currentThread = X</code> error.</p> <p>If I replace <code>TableView</code> with <code>ListView</code>, the expected error occurs.</p> <p>Example code for situation #1: updating a <code>TableView</code> from a different thread, with no call to <code>Platform.runLater()</code>--and no error.</p> <pre><code>public class Test extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) throws Exception { // Create a table of integers with one column to display TableView&lt;Integer&gt; data = new TableView&lt;&gt;(); TableColumn&lt;Integer, Integer&gt; num = new TableColumn&lt;&gt;("Number"); num.setCellValueFactory(v -&gt; new ReadOnlyObjectWrapper(v.getValue())); data.getColumns().add(num); // Create a window &amp; add the table VBox root = new VBox(); Scene scene = new Scene(root); root.getChildren().addAll(data); stage.setScene(scene); stage.show(); // Create a list of numbers &amp; bind the table to it ObservableList&lt;Integer&gt; someNumbers = FXCollections.observableArrayList(); data.setItems(someNumbers); // Add a new number every second from a different thread new Thread( () -&gt; { for (;;) { try { Thread.sleep(1000); someNumbers.add((int) (Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } </code></pre> <p>Example code for situation #2: updating a <code>ListView</code> from a different thread, with no call to <code>Platform.runLater()</code>--produces an error.</p> <pre><code>public class Test extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) throws Exception { // Create a list of integers (instead of a table) ListView&lt;Integer&gt; data = new ListView&lt;&gt;(); // Create a window &amp; add the table VBox root = new VBox(); Scene scene = new Scene(root); root.getChildren().addAll(data); stage.setScene(scene); stage.show(); // Create a list of numbers &amp; bind the table to it ObservableList&lt;Integer&gt; someNumbers = FXCollections.observableArrayList(); data.setItems(someNumbers); // Add a new number every second from a different thread new Thread( () -&gt; { for (;;) { try { Thread.sleep(1000); someNumbers.add((int) (Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } </code></pre> <p>Note that the only difference is the instantiation of <code>data</code> as a <code>ListView&lt;Integer&gt;</code> rather than a <code>TableView&lt;Integer&gt;</code>. </p> <p>So what gives here? Is this happening because of the call to <code>TableColumn::setCellValueFactory()</code> in the first example?--that's my intuition. I would like to know why one does not cause an error and the other does, and more specifically what the rules are for how the <code>.setItems</code> call binds data to the view. </p>
2
Truncated incorrect DOUBLE value using IN on my WHERE
<p>I haven't been able to find an answer to this thus far... Maybe someone here can help. </p> <p>I'm getting the following error: Error running query... ::::Error: ER_TRUNCATED_WRONG_VALUE: Truncated incorrect DOUBLE value: '2,4'</p> <p>This happens when a query is run using the mysql module in nodejs. The query is as follows: </p> <pre><code> selectQ = "UPDATE usr SET pass = ?, last_updator = ?, last_update = NOW() WHERE id IN (?);" </code></pre> <p>I am calling it like this:</p> <pre><code>con.query(selectQ,[hash,lupdator,usrs], function (err, rows) {...}); </code></pre> <p>This works fine as long as I only have one number in the usrs variable, but when I have a list of numbers (in a joined string which looks like "2,4") I get the truncation error above. </p> <p>Any ideas? Thanks!</p> <p><strong>End Result:</strong> </p> <p>Per the answer marked correct, using the prepared statement for my "IN" didn't work. I believe it would work fine if I passed a list of single-quoted strings to look up a text based datatype, but the query is instead passing the escaped INTs as text character types. </p> <p>Anyhoo... I am simply verifying that all of the items within my array are numeric, and if they are I'm joining the array and passing it into the prepared query. I don't believe this leaves me exposed to injection, but feel free to correct me if I'm wrong. Here's my code:</p> <pre><code>for(i = 0; i &lt; usr.length; i++){ if(!IsNumeric(usr[i])){ callback("Password hash failed, server side issue.",null); return; } } var usrs = usr.join(','); selectQ = "UPDATE usr SET pass = ?, last_updator = ?, last_update = NOW() WHERE id IN ("+usrs+");" </code></pre>
2
Sikuli: I am not able to click on an Element present in a PopUp window
<p>I am new to the Sikuli API and I am using the Sikuli-java-jar file. I want to successfully click on a desktop element using the screen and pattern classes.</p> <p>So I was trying to create an automation script to install software. I am able to successfully launch the installer but not able to click on the Next Button present in the pop-up window.</p> <p>I am not getting any error, it is just that clicking on the image fails.</p> <p><a href="https://i.stack.imgur.com/bltb7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bltb7.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/Z1bWE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z1bWE.png" alt="enter image description here"></a></p> <pre><code>appInstaller("E:\\Sikulimages\\tc.png"); appInstallers("E:\\Sikulimages\\next.png"); public static void appInstaller(String path) throws FindFailed{ s=new Screen(); img=new Pattern(path); s.exists(path); s.wait(img,2000); s.doubleClick(img); } public static void appInstallers(String path) throws FindFailed, InterruptedException{ s=new Screen(); img=new Pattern(path); s.click(img); } </code></pre>
2
count the number of days in a given date range in months, days using momentjs
<p>How do i get the exact number of days from a given date range? ex. given the following:</p> <pre><code>today = moment("2016-06-29") due = moment("2016-05-13") days_left = today.diff(due, 'days'); // returns 47 </code></pre> <p>but i want it to display 1 month and 16 days ?</p>
2
SSL Error on nginx based ssl terminator
<p>I receive the following nginx log frequently and unable to get any suitable answer from google search. My nginx is having a valid SSL certificate.</p> <blockquote> <p>Jul 15 08:21:58 web-lb01 WEB_LB01_443: 2016/07/15 08:21:58 [info] 5753#0: *7101 SSL_do_handshake() failed (SSL: error:140943F2:SSL routines:SSL3_READ_BYTES:sslv3 alert unexpected message:SSL alert number 10) while SSL handshaking, client: x.x.x.x, server: 0.0.0.0:443</p> </blockquote>
2
LinqToTwitter Async not working / 'The name 'await' does not exist in the current context' and other pains
<p>I have been playing with Linq to twitter and, after much pain, have finally got some results coming back. This code is working...</p> <pre><code> public IList&lt;ITweet&gt; BuildForAuthor(string author) { var result = new List&lt;ITweet&gt;(); context = context != null ? context : new TwitterContext(_auth); var tweets = (from tweet in context.Status where tweet.Type == StatusType.User &amp;&amp; tweet.ScreenName == author select tweet).Take(4).ToList(); if (tweets != null) { foreach (var tweet in tweets) { if (!tweet.Retweeted) { result.Add(new Tweet { Author = tweet.ScreenName, Text = tweet.Text }); } else { result.Add(new Tweet { Author = tweet.RetweetedStatus.User.ScreenNameResponse, Text = tweet.RetweetedStatus.Text, Retweet = true, RetweetedBy = tweet.ScreenName }); } } } return result; } </code></pre> <p>The problem I have with this is that it's not asynchronous (and it needs error handling). I am a little at sea with async as it's completely new to me (been doing it in JavaScript for years so the concept is understood). The documentation for LinqToTwitter insists it must be async but all the async examples just don't run for me.</p> <p>This is just plain wrong...</p> <pre><code> public IList&lt;ITweet&gt; BuildForAuthor(string author) { var result = new List&lt;ITweet&gt;(); context = context != null ? context : new TwitterContext(_auth); // This is the example as given in the LinqToTwitter documentation, but the 'await' command doesn't work - I see an error 'The name 'await' does not exist in the current context' - errr... var tweets = await (from tweet in context.Status where tweet.Type == StatusType.User &amp;&amp; tweet.ScreenName == author select tweet).ToListAsync(); // This code is completely wrong - I'm not sure what to do here - In JS I'd be looking at a callback, but C# seems to just continue after from the examples I've looked at, however 'tweets' is no longer a list, it's a 'Task' so not much use to me here. if (tweets != null) { foreach (var tweet in tweets) { if (!tweet.Retweeted) { result.Add(new Tweet { Author = tweet.ScreenName, Text = tweet.Text }); } else { result.Add(new Tweet { Author = tweet.RetweetedStatus.User.ScreenNameResponse, Text = tweet.RetweetedStatus.Text, Retweet = true, RetweetedBy = tweet.ScreenName }); } } } </code></pre> <p>Any advice here would be most welcome. I've been hunting through google articles and example code for several hours and the examples are so far away from mine when I'm looking at translations that I can't see where to begin - I don't think it's helped by the weird 'await' error that I'm getting, so I'm concerned I'm barking up the wrong tree somewhere.</p> <h2>DAY 2</h2> <p>After much more reading I now have something more like this...</p> <pre><code> var tweets = (from tweet in context.Status where tweet.Type == StatusType.User &amp;&amp; tweet.ScreenName == author select tweet).Take(4).ToListAsync(); tweets.Wait(); if (tweets != null) { foreach (var tweet in tweets.Result) { ... </code></pre> <p>(above excerpted from the second code block) - This seems to work fine with a manual call to the Wait() method on the tweets task but still doesn't answer the question as to why the 'await' keyword doesn't work.</p>
2
How to parse log file with different types of messages
<p>I have a log file which contains complicated message types. Here is an example:</p> <pre><code>2016-07-07 13:30:02 [Main] *** Program start *** 2016-07-07 13:30:02 [UnzipFile] Before file collection 2016-07-07 13:30:02 [GetZipCol] Start get sorted zip file collection 2016-07-07 13:30:02 [GetZipCol] End get sorted zip file collection 2016-07-07 13:30:02 [Main] [ERROR] No unzip file 2016-07-07 13:30:03 [Main] *** Program end *** </code></pre> <p>The following grok pattern is only suitable for first 4 lines but not the 5th line. </p> <pre><code>grok{ match =&gt; {"message" =&gt; ['%{Date:Date}%{SPACE}%{Time:Time}%{SPACE}%{WORD:Job}%{SPACE}%{GREEDYDATA:Message}']} } </code></pre> <p>I would like to know how should I modify the grok pattern as to capture<code>[ERROR]</code> from the last message. Is there anyone know how the way to do this?</p> <p>This is my output part in conf</p> <pre><code>if [Message] == "*** Program start ***" { elasticsearch { hosts =&gt; ["localhost:9200"] index =&gt; "log-%{+YYYY.MM.dd}" template =&gt; "C:/logstash/log.json" template_overwrite =&gt; true } } if [Message] == "*** Program end ***" { elasticsearch { hosts =&gt; ["localhost:9200"] index =&gt; "log-%{+YYYY.MM.dd}" template =&gt; "C:/logstash/log.json" template_overwrite =&gt; true } } if [Level] =~ /.+/ { elasticsearch { hosts =&gt; ["localhost:9200"] index =&gt; "log-%{+YYYY.MM.dd}" template =&gt; "C:/logstash/log.json" template_overwrite =&gt; true } } </code></pre> <p>If I only want to grasp the event when the Program starts and ends and also the events with errors while the other events can be dropped. However, according to what I have written. I can only grasp the data with [Error]. How should I also grasp the other data? And will there be a simpler way of doing that instead of typing 3 if conditional statements? Thanks.</p> <p>Thanks.</p>
2
Convert a Python (3.5.2) File into an exe?
<p>is there any surefire way to convert a Python (3.5.2) File into an exe? I have seen Pyinstaller, py2exe and cx_Freeze. cx_Freeze does not have a Python 3.5 version, only 3.4 so it isnt compatible. Py2exe works only for Python 2 and while I had some success with Pyinstaller, it returned an error relating to 9130 WARNING: hidden import "pygame._view" not found! (the only one as I can see). </p> <p>The exe. file was created but malfunctioned and stopped working.</p> <p>Any advice?</p>
2
Vuforia SDK Examples Not Running - Android
<p>I'm trying to run Vuforia SDK samples from <a href="https://developer.vuforia.com/downloads/samples" rel="nofollow">here</a> on Android:</p> <p>I have already downloaded the main SDK and put those sample files in the sample folder. I have added the Vuforia.jar as a library and dependency to my project. The app runs on my Samsung S4 and shows the Menu but when I click Start on any of the examples it sends me back to the main menu rather than opening the camera. It doesn't show any crash error in the logs. </p> <p>I'm wondering if anyone has experienced this problem and has managed to fix it?</p>
2
How to make files that get zipped read only
<p>I have a list of files that I need to zip and I am using ZipOutputStream. </p> <p>When I get the files I set each to read only. (I have tried with file.setWritable(false) and file.setReadOnly()) </p> <p>The original file gets changed but the one that get saved inside the zip is not ready only. I'm guessing this is because I have to use FileInputStream to add each file into the zip. </p> <p>For testing I am using example code I found online. </p> <pre><code>import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class TestZip { public static void main(String[] args) { byte[] buffer = new byte[1024]; try { File zipFile = new File("C:\\Users\\thop\\Desktop\\Test\\test.txt"); zipFile.setWritable(false); FileOutputStream fos = new FileOutputStream("C:\\Users\\thop\\Desktop\\Test\\MyFile.zip"); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry ze = new ZipEntry(zipFile.getAbsolutePath()); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(zipFile.getAbsolutePath()); int len; while ((len = in.read(buffer)) &gt; 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); zos.close(); System.out.println("Done"); } catch (IOException ex) { ex.printStackTrace(); } } } </code></pre> <p>Is there a way to make the file that gets zipped read only?</p> <p>Example: The file I am saving gets set to read only. <a href="https://i.stack.imgur.com/s0tzm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s0tzm.png" alt="File that gets zipped"></a></p> <p>When I save the test.txt in a zip file and extract it in the MyFile folder it isn't read only anymore. <a href="https://i.stack.imgur.com/mMpbt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mMpbt.png" alt="Explanation"></a></p>
2
Matplotlib does not work because of Tkinter callback
<p>I recently reinstalled Python using Anaconda (Python 2.7) package, as a result I could not use Matplotlib anymore. I am using the Jupyter notebook 4.2.1 and also tried to run the code in Spyder 2.3.9.</p> <p>In both cases I get the same result when I type the following command:</p> <pre><code>import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() </code></pre> <blockquote> <p>Exception in Tkinter callback Traceback (most recent call last):<br> File "/Users/Anatoly/anaconda/lib/python2.7/lib-tk/Tkinter.py", line 1537, in <strong>call</strong> return self.func(*args) File "/Users/Anatoly/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 283, in resize self.show() File "/Users/Anatoly/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 355, in draw tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2) File "/Users/Anatoly/anaconda/lib/python2.7/site-packages/matplotlib/backends/tkagg.py", line 30, in blit id(data), colormode, id(bbox_array)) TclError</p> </blockquote> <p>Could you help me to figure out what is going on? I already reinstalled Matplotlib and it did not help.</p>
2
Java 8 reduce list to linkedlist
<p>My problem basically boils down to reducing a <code>List</code> into a linked list, but the inferred types from the reduce function don't seem right.</p> <p>My list will look like this</p> <pre><code>[0, 1, 2] </code></pre> <p>I expect the reduce function to do this at each reduce step</p> <pre><code>null // identity (a Node) Node(0, null) // Node a = null, int b = 0 Node(1, Node(0, null)) // Node a = Node(0, null), int b = 1 Node(2, Node(1, Node(0, null))) // Node a = Node(1, Node(0, null)), int b = 2 </code></pre> <p>However, the reduce function seems to think that this won't work because I guess it doesn't think the identity is a Node.</p> <p>Here is my code.</p> <pre><code>import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Example { static class Node { int value; Node next; public Node(int value, Node next) { this.value = value; this.next = next; } } static Node reverse(List&lt;Integer&gt; list) { return list.stream() .reduce(null, (a, b) -&gt; new Node(b, a)); // error: thinks a is an integer } void run() { List&lt;Integer&gt; list = IntStream.range(0, 3) .boxed() .collect(Collectors.toList()); Node reversed = reverse(list); } public static void main(String[] args) { new Example().run(); } } </code></pre> <p>What am I doing wrong?</p> <p><strong>EDIT</strong> After the accepted answer, my code looks like this:</p> <pre><code>import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Example { static class Node { int value; Node next; public Node(int value, Node next) { this.value = value; this.next = next; } @Override public String toString() { return "Node{" + "value=" + value + ", next=" + next + '}'; } } static Node reverse(List&lt;Integer&gt; list) { return list.stream() .reduce(null, (n, i) -&gt; { System.out.println("Will happen"); // to demonstrate that this is called return new Node(i, n); }, (n1, n2) -&gt; { System.out.println("Won't happen"); // and this never is return new Node(n1.value, n2); }); } void run() { List&lt;Integer&gt; list = IntStream.range(0, 3) .boxed() .collect(Collectors.toList()); Node reversed = reverse(list); System.out.println(reversed); } public static void main(String[] args) { new Example().run(); } } </code></pre> <p>And it now prints</p> <pre class="lang-none prettyprint-override"><code>Will happen Will happen Will happen Node{value=2, next=Node{value=1, next=Node{value=0, next=null}}} </code></pre> <p>I still don't know why Java can't tell that third argument to the reduce function is unnecessary and it will never get called, but that's a question for another day.</p> <p><strong>Second Edit</strong></p> <p>It's possible to just create a new method for reduce operations like this because the third argument to reduce can just be a function that does nothing.</p> <pre><code>static &lt;T, U&gt; U reduce(Stream&lt;T&gt; stream, U identity, BiFunction&lt;U, ? super T, U&gt; accumulator) { return stream.reduce(identity, accumulator, (a, b) -&gt; null); } static Node reverse(List&lt;Integer&gt; list) { return reduce(list.stream(), null, (n, i) -&gt; new Node(i, n)); } </code></pre>
2
raspberry pi spi communication
<p>I am trying to communicate between a raspberry pi 3 and pic 18F series micro controller through spi. The sending and receiving of data through spi in the 18F controller is working perfectly as the data is displayed on LCD. However the spi interface on the raspberry pi is not working - the code is printing only 0 values not matter what data is sent and only 0 values are executed.</p> <p>I am using the following program:</p> <pre><code>import spidev import time #import spi.max_speed_hz = 50000000 spi = spidev.SpiDev() spi.open(0,1) counter = 0 while True: try: print "writing data" #hello spi (ASCII) data = [104, 101, 108, 111, 32] #resp = spi.xfer2(data) print "&gt;&gt;&gt;" + str(spi.xfer2(data)) time.sleep(1) counter += 1 if counter &gt; 4: break time.sleep(1) except(keyboardInterrupt, SystemExit): spi.close() raise spi.close() print "done" </code></pre> <p>Output:</p> <pre><code>writing data &gt;&gt;&gt;[0, 0, 0, 0, 0] writing data &gt;&gt;&gt;[0, 0, 0, 0, 0] writing data &gt;&gt;&gt;[0, 0, 0, 0, 0] writing data &gt;&gt;&gt;[0, 0, 0, 0, 0] writing data &gt;&gt;&gt;[0, 0, 0, 0, 0] done </code></pre> <p>Whatever program I run I am getting only 0 values and not the data what i send. Kindly please help.</p>
2
android GoogleAuthUtil.getTokenWithNotification Intent callback not triggering
<p>I have a background service that calls <code>GoogleAuthUtl.getTokenWithNotification</code> and it works properly but I'm trying to implement the callback portion of this function and that isn't working properly.</p> <p>I've implemented a broadcast receiver and added it to the manifest, I also have an activity in my app. Below are the relevant pieces of code.</p> <p><strong>GoogleAuthUtil.getTokenWithNotification</strong></p> <pre><code>GoogleAuthUtil.getTokenWithNotification(this.getContext(), account, "oauth2:" + GmailScopes.GMAIL_SEND, null, new Intent(AuthReceiver.AUTH_INTENT)); </code></pre> <p><strong>AuthReceiver</strong></p> <pre><code>public class AuthReceiver extends BroadcastReceiver { public final static String AUTH_INTENT = "com.testoauth.AUTH_INTENT"; public AuthReceiver() { } @Override public void onReceive(Context context, Intent intent) { Log.d("RECEIVER", "Received Auth broadcast."); NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancelAll(); } } </code></pre> <p><strong>AndroidManifest</strong></p> <pre><code>&lt;receiver android:name=".AuthReceiver" android:enabled="true" android:exported="true"&gt; &lt;intent-filter&gt; &lt;action android:name="com.testoauth.AUTH_INTENT" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; </code></pre> <p>I have no clue why it is not receiving the broadcast. I don't see any exceptions in the logs and no indication that the receiver was called at all, it won't even break on a breakpoint when debugging. Am I doing something incorrectly?</p> <p><strong>EDIT</strong></p> <p>I'm using min sdk 16 and target sdk 25</p> <p>From the <a href="https://developers.google.com/android/reference/com/google/android/gms/auth/GoogleAuthUtil.html#getTokenWithNotification(android.content.Context,%20android.accounts.Account,%20java.lang.String,%20android.os.Bundle,%20android.content.Intent)" rel="noreferrer">GoogleAuthUtil.getTokenWithNotification</a> API documentation:</p> <blockquote> <p>This method is specifically provided for background tasks. In the event of an error that needs user intervention, this method takes care of pushing relevant notification. After the user addresses the notification, the callback is broadcasted. If the user cancels then the callback is not fired.</p> </blockquote> <p>The callback is not fired regardless of the user canceling or not. Aside from the <code>ActivityManager</code> saying the notification has been displayed (<code>Displayed com.google.android.gms/.auth.uiflows.gettoken.GetTokenActivity</code>), there is no indication that the specified broadcast intent (in this case <code>com.testoauth.AUTH_INTENT</code>) has been sent in the logs. The "Received Auth broadcast." message is also absent from the logs.</p> <p>The included SDK example of this functionality (<code>&lt;android-sdk&gt;/extras/google/google_play_services/samples/auth/gau</code>) doesn't even work.</p>
2
Can I detect with JavaScript where we are percentage wise in a CSS Keyframe animation
<p>I was thinking. I know I can detect when a CSS animation has started, finished or is repeated by listening for the animationstart, animationiteration, animationend events (obviously we are missing browser prefixes there), for example:</p> <pre><code>document.getElementById('identifier') .addEventListener("animationstart", function(){ // do something... }); </code></pre> <p>but I was wondering, is it possible to determine where we are are running a CSS animation, how for example with the following could I listen for when we are at 50% of the keyframe animation:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; #animateDiv { width: 100px; height: 100px; background-color: red; position: relative; animation-name: example; animation-duration: 4s; } @keyframes example { 0% {background-color:red; left:0px; top:0px;} 25% {background-color:yellow; left:200px; top:0px;} 50% {background-color:blue; left:200px; top:200px;} 75% {background-color:green; left:0px; top:200px;} 100% {background-color:red; left:0px; top:0px;} } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="animateDiv"&gt;&lt;/div&gt; &lt;script&gt; // what do I do here? How do I listen for the 50% event of the keyframes? document.getElementById('animateDiv').addEventListener('animation at 50%?', function() { console.log('got it'); }) &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
2
Trying getting json from online api.fixer.io
<p>I am trying to make a converter EUR-USD using ajax requests and jquery and getting values from an online API: </p> <pre><code> http://api.fixer.io/latest?base=EUR </code></pre> <p>Now I only try to see if the call is done and it returns succesfully the JSON from the link. My code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> $(document).ready(function() { $("#idButton").click(function() { $.ajax({ type: "GET", url: "http://api.fixer.io/latest?base=EUR", data: {}, succes: function(result) { data = JSON.parse(result); //$("#idUsd").val(); console.log(data); }, error: console.log("dsfhg") }); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background-color: #808080; } .myEuro { display: block; margin-bottom: 10px; padding: 10px; } #idButton { color: #fff; border: none; background-color: #483D8B; padding: 10px; font-size: 15px; } .classTF { display: block; margin-bottom: 10px; padding: 10px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Demo 2&lt;/title&gt; &lt;script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form class="myForm" id="form"&gt; &lt;input type="text" name="from" placeholder="Euro/s" class="classTF"&gt; &lt;input type="text" name="to" placeholder="USD" class="classTF" id="idUsd"&gt; &lt;button type="submit" name="button" id="idButton"&gt;Convert into USD&lt;/button&gt; &lt;/form&gt; &lt;script type="text/javascript"&gt; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>In my console it's printed </p> <pre><code> dsfhg </code></pre> <p>meaning I got an error. But I don't know what I did wrong. Can anyone help me?</p>
2
Hive query cli works, same via hue fails
<p>I have a weird issue with hue (version 3.10).</p> <p>I have a very simple hive query:</p> <pre><code>drop table if exists csv_dump; create table csv_dump row format delimited fields terminated by ',' lines terminated by '\n' location '/user/oozie/export' as select * from sample; </code></pre> <ul> <li>running this query in the hive editor works</li> <li>running this query as an oozie workflow command line works</li> <li>running this query command line with beeline works</li> <li>running this query via an oozie workflow from hive fails</li> </ul> <p>Fail in that case means:</p> <ul> <li>drop and create are not run, or at least do not have any effect</li> <li>a prepare action in the workflow will be executed</li> <li>the hive2 step in the workflow still says succeeded</li> <li>a following step will be executed.</li> </ul> <p>Now I did try with different users (oozie and ambari, adapting the location as relevant), with exactly the same success/failure cases.</p> <p>I cannot find any relevant logs, except maybe from hue:</p> <pre><code>------------------------ Beeline command arguments : -u jdbc:hive2://ip-10-0-0-139.eu-west-1.compute.internal:10000/default -n oozie -p DUMMY -d org.apache.hive.jdbc.HiveDriver -f s.q -a delegationToken --hiveconf mapreduce.job.tags=oozie-e686d7aaef4a29c020059e150d36db98 Fetching child yarn jobs tag id : oozie-e686d7aaef4a29c020059e150d36db98 Child yarn jobs are found - ================================================================= &gt;&gt;&gt; Invoking Beeline command line now &gt;&gt;&gt; 0: jdbc:hive2://ip-10-0-0-139.eu-west-1.compu&gt; drop table if exists csv_dump; cr eate table csv_dump0 row format delimited fields terminated by ',' lines termina ted by '\n' location '/user/ambari/export' as select * from sample; &lt;&lt;&lt; Invocation of Beeline command completed &lt;&lt;&lt; Hadoop Job IDs executed by Beeline: &lt;&lt;&lt; Invocation of Main class completed &lt;&lt;&lt; Oozie Launcher, capturing output data: ======================= # #Thu Jul 07 13:12:39 UTC 2016 hadoopJobs= ======================= Oozie Launcher, uploading action data to HDFS sequence file: hdfs://ip-10-0-0-139.eu-west-1.compute.internal:8020/user/oozie/oozie-oozi/0000011-160707062514560-oozie-oozi-W/hive2-f2c9--hive2/action-data.seq Oozie Launcher ends </code></pre> <p>Where I see that beeline is started, but I do not see any mapper allocated as I do command line.</p> <p>Would anybody have any idea of what could go wrong?</p> <p>Thanks, Guillaume</p>
2
How to change Exomedia's default video control bar's color?
<pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:EMVideoView="http://schemas.android.com/apk/res-auto" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="@color/MUVCastleRock"&gt; &lt;com.devbrackets.android.exomedia.ui.widget.EMVideoView android:id="@+id/video_view" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" EMVideoView:useDefaultControls="true" /&gt; </code></pre> <p>    </p> <p>How do I change the color of the default controls (where you would see the play button)? I don't want to change the background behind the video, but instead the play bar. This is because my background is grey and so I want to change the color so that the bar is more visible.</p> <p>EDIT: <a href="https://i.stack.imgur.com/D8JeB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D8JeB.jpg" alt="enter image description here"></a></p>
2
invalid operands to binary expression ('struct node ' and 'struct node ')
<p>I have made a header file in which I have declared a <code>struct node</code> and made an object as <code>List</code> of that struct. Here is my header file <strong>link.h</strong>:</p> <pre><code>struct node { void *data; //Generic data struct node *next; }List; </code></pre> <p><strong>Driver.c</strong>: </p> <pre><code>#include "link.h" int main() { List list1; return 0; } </code></pre> <p>When I am trying to write a statement like</p> <pre><code>List list1; //in the driver file </code></pre> <p>It throws up an error saying:</p> <blockquote> <p>invalid operands to binary expression ('struct node' and 'struct node')</p> <p>use of undeclared identifier 'list1'; did you mean 'List'?</p> </blockquote> <p>What could be causing this?</p>
2
How to find out duplicate arguments in shell script
<p>I'm supporting below arguments to the script. I want to find out duplicate arguments when its passed and throw an error. Can you please help me. </p> <pre><code>#! /bin/sh VCFile= gCFFile= PW=xyzzy while test $# -gt 0 do option=$(echo $1 | tr a-z A-Z) case $option in (-VO) shift VCfile=$1 ;; (-CON) shift gCFFile=$1 ;; (-PASSWORD) shift PW=$1 ;; (*) print "\nerror -The command line argument $1 is invalid\n" print "Testscript has aborted.\n" exit 2 ;; esac shift done ./Install.sh -VO abc.txt -CON tt.txt - pass ./Install.sh -VO abc.txt -CON tt.txt -ss error -The command line argument -ss is invalid Testscript has aborted. </code></pre> <p>if running with dup parameters like below</p> <pre><code>./Install.sh -VO abc.txt -CON tt.txt -CON ta.txt -PASSWORD ABC -PASSWORD non </code></pre> <p>--doesn't fail , Here I want to throw an error as duplicate options are entered.</p>
2
Gstreamer videomixer Very low framerate
<p>I am trying to composite three streams coming from three Rapsberry PI. </p> <p>As soon as I join two streams together using the videomixer plugin, I get a message ending with: </p> <p><strong>Pipeline:pipeline0/GstOSXVideoSink:osxvideosink0: There may be a timestamping problem, or this computer is too slow.</strong></p> <p>Strangely, my task monitor only indicates about 15%CPU usage for gst</p> <p>With the three streams, the framerate becomes unusable. I would expect my I7 macbook to be able to handle this without problem.... </p> <p>Here is the code I am using for the mixing, in this case just one stream(/sink?). Can anyone tell me whether there is an obvious mistake ? Or where I should look for the bottleneck and improve it ? Thanks ! </p> <pre><code>gst-launch-1.0 videomixer name=m sink_1::xpos=400 sink_2::ypos=300 ! autovideosink \ -v udpsrc port=9000 caps='application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264'! rtph264depay ! video/x-h264,width=400,height=300,framerate=30/1 ! h264parse ! avdec_h264 ! videoconvert ! m. \ -v udpsrc port=9001 caps='application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264' ! rtph264depay ! video/x-h264,width=400,height=300,framerate=30/1 ! h264parse ! avdec_h264 ! videoconvert ! m. \ -v udpsrc port=9002 caps='application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264' ! rtph264depay ! video/x-h264,width=400,height=300,framerate=30/1 ! h264parse ! avdec_h264 ! videoconvert ! m. </code></pre> <p>Here is the code I use to send the streams from the RPI Camera.</p> <pre><code>raspivid -n -w 640 -h 480 -t 0 -o - \ | gst-launch-1.0 -v fdsrc ! h264parse ! rtph264pay \ config-interval=10 pt=96 ! udpsink host=192.168.1.3 port=9000 </code></pre>
2
What username and password is needed for JavaMail API?
<p>I'm trying to learn how to send an email using a Netbeans application. Whenever I run the application, I keep getting the following error:</p> <p><code>javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted.</code></p> <p>I got code from two different sources (specified below) and both give the exact same error. I used the correct <code>.jar</code> files, and the code was copied exactly as shown in the tutorials, but neither works. I also tried using my proper Gmail credentials (made sure they were 100% correct) and I still get the error. </p> <p>What I want to know is:</p> <p>What do I use as username and password? (are there predefined ones I need to obtain or do I need to create them, and if so how?)</p> <p><strong>Sources:</strong></p> <p>This one does not specify a password anywhere at all: <a href="https://www.youtube.com/watch?v=01MWjRVBjzI" rel="nofollow">Email: How to send email using java Netbeans [Tutorial] - YouTube</a></p> <p>This one specifies a password as <code>String pass = "****";</code> which I changed to <code>String pass = "pass123";</code>: <a href="https://www.youtube.com/watch?v=Z4rWdPvNI4Q" rel="nofollow">Send email using Java (in NetBeans)</a></p>
2
Angular ng-table not able to default sort on variable value
<p>I am trying to sort a table using angularjs ng-table, however i am not able to do that. Below is the code which i am using for sorting.</p> <pre><code>var sortKey = $scope.fieldName; $scope.releasedTable = new ngTableParams({ page : 1, count : $scope.defaultpageSize, sorting : { sortKey : 'desc' } }); </code></pre> <p>If I am passing the dynamically variable such as sortKey above it is not working. However my below code works because of static variable fName in it. </p> <pre><code>$scope.releasedTable = new ngTableParams({ page : 1, count : $scope.defaultpageSize, sorting : { fName : 'desc' } }); </code></pre> <p>html :</p> <pre><code> &lt;table id="action-pending-table" ng-table="releasedTable" class="table table-striped"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th ng-repeat="column in columns" ng-class="{'sort-asc': releasedTable.isSortBy(column.fieldName, 'asc'), 'sort-desc': releasedTable.isSortBy(column.fieldName, 'desc')}" ng-click="releasedTable.sorting(column.fieldName, releasedTable.isSortBy(column.fieldName, 'asc') ? 'desc' : 'asc'); changeIcon(icon)" ng-if="column.display"&gt; {{column.displayName}} &lt;icon-change icon="icon"&gt;&lt;/icon-change&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr ng-repeat="record in records"&gt; &lt;td ng-repeat="column in columns"&gt; &lt;span ng-if="isNeededLink(column.fieldName)"&gt;&gt;{{record[column.fieldName]}} &lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>Please suggest how can I resolve this.</p>
2
Access the UIImageView of the background image of a UIButton
<p>I have a UIButton, and I would like to access the UIImageView of its background image so that I can make the image circular. I know that I can affect the image itself but I would prefer to do this more elegantly. I also know that I can use the <code>button.currentBackgroundImage</code> property to get the UIImage in the background, but I want the view itself. Once I have the view I intend to use this code:</p> <pre><code>buttonImageView.layer.cornerRadius = buttonImageView.frame.size.width / 2; buttonImageView.clipsToBounds = YES; </code></pre> <p>How can I access the buttonImageView?</p> <p>EDIT: Due to @vhristoskov's suggestions, I tried cropping the button itself with this code:</p> <pre><code>self.button.layer.cornerRadius = self.button.frame.size.width/2; self.button.clipsToBounds = YES; </code></pre> <p>And it made this shape:</p> <p><a href="https://i.stack.imgur.com/uty22.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uty22.png" alt="enter image description here"></a></p> <p>After debugging I found that frame.size.width was 46, when it should have been 100. So I tried this code instead:</p> <pre><code>self.button.layer.cornerRadius = self.button.currentBackgroundImage.size.width/2; self.button.clipsToBounds = YES; </code></pre> <p>And that produced this shape:</p> <p><a href="https://i.stack.imgur.com/fsToy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fsToy.png" alt="enter image description here"></a></p> <p>And this time, the <code>cornerRadius</code> was being set to 65. So it actually seems like my problem is that I don't have the correct width at the moment. Which property should I access to get the correct number?</p>
2
Using spring PseudoTransactionManager to move processed files
<p>This looks like a duplicate question, I have looked at <a href="https://stackoverflow.com/questions/30151642/how-to-move-processed-file-to-another-directory-using-spring-integration-ftp-inb">the question here about transaction managers</a>, and the referred documentation section, but have not been successful.</p> <p>The flow I have in mind is for processing xml files:</p> <p>Inbound Channel Adapter with Transaction Manager -> Channel -> Service-Activator</p> <p>The file is passed into my java program for processing just fine. I then want the transaction manager part to then move processed files into one folder and failed files into another. The latter part is my problem. I have this configuration:</p> <pre class="lang-xml prettyprint-override"><code>&lt;int-file:inbound-channel-adapter id="pgen-inbound" directory="file:D:/records/incoming/" auto-startup="true" filter="compositeFilter" channel="pgen-inchannel"&gt; &lt;int:poller fixed-rate="1000"&gt; &lt;int:transactional transaction-manager="transactionManager" synchronization-factory="fileSync"/&gt; &lt;/int:poller&gt; &lt;/int-file:inbound-channel-adapter&gt; &lt;bean id="transactionManager" class="org.springframework.integration.transaction.PseudoTransactionManager"/&gt; &lt;int:transaction-synchronization-factory id="fileSync"&gt; &lt;int:after-commit expression="payload.renameTo('./success/' + payload.name)" channel="nullChannel" /&gt; &lt;int:after-rollback expression="payload.renameTo('./failed/' + payload.name)" channel="nullChannel" /&gt; &lt;/int:transaction-synchronization-factory&gt; &lt;int:channel id="pgen-inchannel"/&gt; &lt;int:service-activator input-channel="pgen-inchannel" ref="recordProcessor" method="processInboundRecords"/&gt; &lt;bean id="recordProcessor" class="com.a.b.RecordFeeder"&gt; &lt;property name="username" value="pgenuser"/&gt; &lt;property name=".../&gt; ... &lt;/bean&gt; &lt;bean id="compositeFilter" class="org.springframework.integration.file.filters.CompositeFileListFilter"&gt; &lt;constructor-arg&gt; &lt;list&gt; &lt;bean class="org.springframework.integration.file.filters.SimplePatternFileListFilter"&gt; &lt;constructor-arg value="*.xml"/&gt; &lt;/bean&gt; &lt;/list&gt; &lt;/constructor-arg&gt; &lt;/bean&gt; </code></pre> <p>The directories all exist, but the file is not moved and there are no error messages, just logging:</p> <pre><code>INFO org.springframework.integration.file.FileReadingMessageSource- Created message: [GenericMessage [payload=D:\records\incoming\record2.xml, headers={id=f24b11e4-39ac-03e1-6b3c-cae7ff5b7615, timestamp=1468404043936}]] </code></pre> <p>My understanding is that I do not need channels onwards from the transaction-synchronisation-factory, as they would just be passed the outcomes of the payload.renameTo operations, ie. true or false, hence I used nullChannel there.</p> <p>I get this logging:</p> <pre><code>DEBUG org.springframework.integration.handler.ServiceActivatingHandler- handler 'ServiceActivator for [org.springframework.integration.handler.MethodInvokingMessageProcessor@1e05e138] (org.springframework.integration.config.ServiceActivatorFactoryBean#0)' produced no reply for request Message: GenericMessage [payload=D:\records\incoming\pgImpor2.xml, headers={id=4860011b-b6a3-9dbd-8572-90b12de88e9c, timestamp=1468423768506}] DEBUG org.springframework.integration.channel.DirectChannel- postSend (sent=true) on channel 'pgen-inbound', message: GenericMessage [payload=D:\records\incoming\pgImpor2.xml, headers={id=4860011b-b6a3-9dbd-8572-90b12de88e9c, timestamp=1468423768506}] DEBUG org.springframework.integration.transaction.ExpressionEvaluatingTransactionSynchronizationProcessor- Sending received message to org.springframework.integration.channel.NullChannel@4fc66eb8 as part of 'beforeCommit' transaction synchronization DEBUG org.springframework.integration.channel.NullChannel- message sent to null channel: GenericMessage [payload=D:\record\incoming\pgImpor2.xml, headers={id=4860011b-b6a3-9dbd-8572-90b12de88e9c, timestamp=1468423768506}] DEBUG org.springframework.orm.jpa.JpaTransactionManager- Initiating transaction commit DEBUG org.springframework.orm.jpa.JpaTransactionManager- Committing JPA transaction on EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@36411551] DEBUG org.springframework.orm.jpa.JpaTransactionManager- Found thread-bound EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@36411551] for JPA transaction DEBUG org.springframework.orm.jpa.JpaTransactionManager- Participating in existing transaction DEBUG org.springframework.orm.jpa.JpaTransactionManager- Found thread-bound EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@36411551] for JPA transaction DEBUG org.springframework.orm.jpa.JpaTransactionManager- Participating in existing transaction **DEBUG org.springframework.integration.transaction.ExpressionEvaluatingTransactionSynchronizationProcessor- Evaluating afterCommit expression: 'payload.renameTo('./success/' + payload.name)' on GenericMessage [payload=D:\record\incoming\pgImpor2.xml, headers={id=4860011b-b6a3-9dbd-8572-90b12de88e9c, timestamp=1468423768506}]** DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory- Returning cached instance of singleton bean 'integrationEvaluationContext' DEBUG org.springframework.integration.transaction.ExpressionEvaluatingTransactionSynchronizationProcessor- Sending expression result message to nullChannel as part of 'afterCommit' transaction synchronization DEBUG org.springframework.integration.channel.NullChannel- message sent to null channel: GenericMessage [payload=false, headers={id=339dda35-55cc-c6db-68e5-fc84fe32ff04, timestamp=1468423781333}] DEBUG org.springframework.orm.jpa.JpaTransactionManager- Closing JPA EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@36411551] after transaction DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils- Closing JPA EntityManager </code></pre> <p>So it evaluates the renameTo call for the success case.. but without any result as it is set up.</p>
2
Can CakePhp 2.x or 3.x be used to develop web app based on micro service architecture
<p>I was evaluating PHP based frameworks for development of highly available and scalable applications based on micro service architecture. </p> <p>I have not seen any documentation for using CakePhp 2.x or 3.0 for design and development of micro services. Where as Laravel ( which is another PHP MVC framework based on Symphony) seems to have these capabilities based on its Lumen modules or components.</p> <p>It appears that CakePhp frameworks are only suited for design and development of big gigantic monolithic app. </p> <p>Can anyone point me to a documentation or example about how to use CakePhp 2.x or 3.x for designing web apps based on Micro service architecture ? </p>
2
Rendering client side charts on the server
<p>The product I'm working on has some nice graphs on a HTML5 dashboard. The graphs are rendered in Javascript using <a href="http://www.flotcharts.org" rel="nofollow">Flot</a>. </p> <p>Users would like this Dashboard emailed to them daily as a PDF report, on a fixed schedule. So for example they want an email every day at 8am to be emailed to them.</p> <p>I've thought of using Python's <a href="http://docs.python-requests.org/en/master/" rel="nofollow">Requests</a> (i.e. do a <code>request.get</code>) to get the HTML5 source of the page and then convert the resulting HTML5 page to PDF using <a href="http://weasyprint.org" rel="nofollow">Weasyprint</a> but this is obviously not going to work.</p> <p>The Javascript charts are the biggest headache as they won't render unless viewed in a browser that has decent Javascript support, so the outlined approach won't render the Javascript graphs. </p> <p>What's the recommended way of converting a dynamically generated HTML5 page into PDF? How do other people do this?</p>
2
How to trigger mouse click event on react component to open date picker
<p>I am using reactjs and I have one button and one input date dom on my react component. I want to open the date picker when click on the button. The input date dom defined as below</p> <pre><code>&lt;input className='showSurgeryDate' type="date" onChange={this.setSurgeryDate.bind(this)} ref={(c) =&gt; this.datePicker = c }/&gt; </code></pre> <p>below is the onclick function defined on the button:</p> <pre><code>let event = document.createEvent('MouseEvents') let dom = ReactDom.findDOMNode(this.datePicker) event.initEvent('click', true, false) dom.dispatchEvent(event) </code></pre> <p>I use document.createEvent to create a click event. Then I call dispatchEvent on the dom but the date picker didn't popup. How can I let the date picker popup when user clicking on the button?</p>
2
can not import firebase into my swift project
<p><a href="https://i.stack.imgur.com/u3dhV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3dhV.jpg" alt="enter image description here"></a>I am using cocoapods to integrate Firebase SDK into my swift project . The problem that I face is based on the content of my pod file . </p> <p>when I install a pod file with the following content </p> <pre><code># Uncomment this line to define a global platform for your project platform :ios, "9.0" target "myProject" do pod 'Firebase' pod 'Firebase/Database' pod 'Firebase/Auth' pod 'Firebase/Core' end target "myProjectTests" do pod 'Firebase' pod 'Firebase/Database' pod 'Firebase/Auth' pod 'Firebase/Core' end target "myProjectUITests" do pod 'Firebase' pod 'Firebase/Database' pod 'Firebase/Auth' pod 'Firebase/Core' end </code></pre> <p>I can not import Firebase (no such module as Firebase ) but i am able to import firebaseAuth and ... .</p> <p>The second case is when I use the following pod file : # Uncomment this line to define a global platform for your project platform :ios, "9.0"</p> <pre><code>target "myProject" do use_frameworks! pod 'Firebase' pod 'Firebase/Database' pod 'Firebase/Auth' pod 'Firebase/Core' end target "myProjectTests" do use_frameworks! pod 'Firebase' pod 'Firebase/Database' pod 'Firebase/Auth' pod 'Firebase/Core' end target "myProjectUITests" do use_frameworks! pod 'Firebase' pod 'Firebase/Database' pod 'Firebase/Auth' pod 'Firebase/Core' end </code></pre> <p>and I get this error right a way in the terminal : </p> <pre><code> # from /Users/veronica/Desktop/myProject/Podfile:5 # ------------------------------------------- # target "myProject" do &gt; use_frameworks! # pod 'Firebase' # ------------------------------------------- </code></pre> <p>by the way I've gone through similar questions to mine and found some answers like : </p> <pre><code>platform :ios, "9.0" use_frameworks! target 'MyProject' do pod 'Firebase' end </code></pre> <p>but I still get an error just like my own second version Any help is strongly appreciated :) </p> <p><a href="https://i.stack.imgur.com/u3dhV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3dhV.jpg" alt="enter image description here"></a></p>
2
D3 javascript network: How to parametrize node size with the number of links?
<p>I want to create a network with d3.js. I have created one as you see below, but I want the node size to depend on the number of links each node has (the more links a node has, the bigger the size of the node, vice versa). Below is the JS I wrote for the nodes.</p> <p>How do I change the node size with the number of links?</p> <pre><code>var nodes = graph.nodes.slice(), links = [], bilinks = []; graph.links.forEach(function(link) { var s = nodes[link.source], t = nodes[link.target], i = {}; // intermediate node nodes.push(i); links.push({source: s, target: i}, {source: i, target: t}); bilinks.push([s, i, t]); }); var node = svg.selectAll(".node") .data(graph.nodes) .enter().append("circle") .attr("class", "node") .attr("r", 3) .style("fill", function(d) { return color(d.group); }) </code></pre> <p><a href="https://i.stack.imgur.com/fsrKX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fsrKX.png" alt="enter image description here"></a></p>
2
Django/Python: Import once, use everywhere
<p>I have the following structure for my <code>views</code> directory.</p> <pre><code>views |--__init__.py |--a_management.py |--b_management.py |--c_management.py |--d_management.py |--e_management.py </code></pre> <p>and <code>__init__.py</code> starts with the following:</p> <pre><code>from a_management import * from b_management import * from c_management import * from d_management import * from e_management import * ......... ...etc... ......... </code></pre> <p>In each of the files (<code>a_management.py</code>,<code>b_management.py</code>...) I need to write the same code importing modules:</p> <pre><code>import sys,os from django.shortcuts import render, redirect from django.http import HttpResponseRedirect ......... ...etc... ......... </code></pre> <p>Is it possible to perform all the module imports only in <code>__init__.py</code>? </p> <p>When I tried, it still seems like the imports are not found and I get errors like: <code>NameError: global name 'sys' is not defined</code></p>
2
What exactly is a Buddy Class and how do I use it to add Annotations to an existing class?
<p>I've seen the term "Buddy class" used as an 'answer' to questions like "how can I add annotations to a partial class in another file" but these answers assume I know what a Buddy Class <em>is</em>, and the code examples assume I understand how/why this works.</p> <p>I couldn't see a simple explanation of what a buddy class in C# is, and how/why it allows me to modify an existing class such as adding annotations to properties.</p>
2
d3 v4 zooming line without scaling up/down svg line elements
<p>I'm porting a D3 v3 graph widget that uses panning and zooming to v4 and got stuck on the zooming changes. The zooming API in v4 uses a different model where zooming is managed on the elements rather than a general zoom transform.</p> <p>I have a lot of datapoints that get plotted on a timescale that initially intentionally clumps the datapoints very close to each other, and the user can use zooming to drill deeper into the data for more detail. In v3 when zooming in the svg line automatically adjusted with the new scale however in v4 when applying zoom scaling on the svg line I get an increases the thickness of the svg line elements rather than resolving more detail (and keeping the line thickness constant). I have no problems with scaling the x or y axis.</p> <p>This behavior is expected with a scale function but not what I want. I've read the new API for zoom and can't work out what zoom function to use that would give me v3 behaviour where zooming in shows more detail in the line graph and doesn't scale up the line thickness.</p> <p>In v3 D3 would zoom the svg line with the following in the zoom event handler, however this won't work in v4.</p> <pre><code>chart.select("#seriesLine" + i).attr("d", series[i].d3Line(series[i].data)) </code></pre> <p>Its been a while since I wrote the original graphing widget so possibly I'm just not remembering how to setup D3 correctly, but I think I'm just not groking the new zoom function, and there are no similar zoom examples to learn from.</p> <p>Any tips?</p>
2
What is the joke behind "goto $"?
<p>I was on the phone with someone, when they were talking about prefering assembly to higher level languages. They mentioned liking the goto statement, to which I replied that it leads to spaghetti code. They replied with something like "goto $". I said that goto can give off code smell. They laughed, and said people don't normally get that joke.</p> <p>Well, I didn't get it. Does anyone know what that person was talking about, in regards to "goto $"? What was the joke there? I feel silly asking this, but my Google searches didn't turn up anything helpful.</p>
2
increment integer in python
<p>I wrote a simple function to read a file line by line, do some calculation and store the results in another file. However, when I output <code>count</code> in my function, instead of 0, 1, 2, 3; it becomes 6.21263888889e-05, 0.000141933611111, etc. I'm wondering what is the reason. </p> <pre><code>def CumulativePerSecond(input_file): # Record cumulative battery per second freq = 1000 # number of samples per second output_file = os.path.splitext(input_file)[0] + "_1s" + ".txt" output = open(output_file, 'a+') count = 0 for line2 in fileinput.input(input_file): count = count + 1 print count if count == freq: output.write(str(line2)) count = 0 output.close() </code></pre> <p>Parts of Output:</p> <pre><code>1.87317876361 1.87321708889 1.87325520083 1.87329356889 1.87333199389 1.87337076056 1.87340823167 1.87344365278 1.87347473167 1.87351439528 1.87354390806 1.87362505778 </code></pre>
2
Extract data-atribute from Current Active Tab
<p>How is it possible to extract the <code>tabid</code> data-attribute from the current active tab:</p> <p>HTML SAMPLE:</p> <pre><code>&lt;button class="tab-page tab-active" data-tabid="Tab1"&gt;Tab1&lt;/button&gt; </code></pre>
2
PHP Fatal error: Call to a member function bind_param() on boolean
<p>I'm fairly new to PHP and I know this is a well known problem, however I wasn't able to fix it though. According to the mysql log the connection to the database is established and immediately closed.</p> <p>I attached the code snipped below, thanks for any help. Btw, this error occurs only on the "real" server, using XAMPP I got no problems at all...</p> <pre><code>$stmt = $conn-&gt;prepare("SELECT UID FROM USERS WHERE username = ? and password = ?"); $stmt-&gt;bind_param("ss", $g_usernameSql, $g_pwSql); </code></pre>
2
How to assign value to a Lazy Loading object?
<p>I am new on lazy loading, but I want to be able to fill my lazy loading objects after it was created too. Is it possible?</p> <p>I am getting this error when I want to define a "Lazy loading list" as a normal list I created:</p> <p>Cannot implicitly convert type: 'System.Collections.Generic.List' to 'System.Lazy>' </p> <p>Here is the code: </p> <pre><code>List&lt;Currency&gt; currencyOfMids = new List&lt;Currency&gt;(); obj.Merchant.CurrencyOfMids = currencyOfMids; </code></pre> <p>I tried identifying my list as a Lazy list too, but this time I can't fill it with "Add" command:</p> <pre><code> foreach (ListItem currencyItem in selectedCurrencies) currencyOfMids.Add(new Currency() { Code = currencyItem.Text, Id = int.Parse(currencyItem.Value) }); </code></pre> <p>'Lazy>' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'Lazy>' could be found (are you missing a using directive or an assembly reference?) </p>
2
Add element in single/multiple lists in a vector of list
<p>I've already declared a vector of lists and 3 lists and added those 3 lists in the vector. Now I'd want to add some elements to 2 out of those 3 lists by using <strong>the vector only</strong>. How can I achieve this?<br> Here is my code so far:</p> <pre><code>#include&lt;iostream&gt; #include&lt;list&gt; #include&lt;vector&gt; using namespace std; #ifndef ILIST #define ILIST list&lt;int&gt; #endif #ifndef VLIST #define VLIST vector&lt;ILIST &gt; #endif int main(int argc, char const *argv[]) { ILIST l1(4,10), l2(4,20), l3(4,30); VLIST vec; vec.push_back(l1); vec.push_back(l2); vec.push_back(l3); //here I want to add 2 elements in l2 and 1 in l3 by using the vector only. return 0; } </code></pre>
2
Why does msgrcv returns ENOMSG
<p>System V message queue is created successfully, command <code>ipcs -q</code> outputs:</p> <pre><code> ------ Message Queues --------&lt; key msqid owner perms used-bytes messages 0x080b2fb4 0 hel 600 0 0 </code></pre> <p>But the program to receive the message returns: </p> <blockquote> <p>exit: msgrcv error, No message of desired type</p> </blockquote> <p>This is my code: </p> <pre><code>/* create key for message queue */ key = ftok("/home/hel/messageQueueSystemV", 8); if (key == -1) { printf("exit: ftok error, %s\n", strerror(errno)); // error exit(0); } /* open existed message queue */ mqFd = msgget(key, 0600); if (mqFd &lt; 0) { printf("exit: msgget error, %s\n", strerror(errno)); // error exit(0); } /* receive a message */ if (msgrcv(mqFd, &amp;buf, 1 + sizeof(short), 0, IPC_NOWAIT) &lt; 0) { // type is 0 printf("exit: msgrcv error, %s\n", strerror(errno)); // error exit(0); } </code></pre>
2
How to disable current week in jquery datepicker?
<p>I am trying to solve this problem. Still I have done this,</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { $( "#datepicker" ).datepicker({ dateFormat: 'yy-mm-dd', firstDay: 1, minDate:1 }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"&gt; &lt;script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"&gt;&lt;/script&gt; &lt;input type="text" id="datepicker"&gt;</code></pre> </div> </div> </p> <p>If you run this code you can see the calendar.</p> <p>I want to disable the full current week. The available dates will start from next week. As, Example, today is <code>18.07.2016</code>. So, if someone want to use this calendar then this full week become inactive. Next available date will start from <code>24.07.2016</code>.</p> <p>Thanks in advance for help.</p>
2
z-index position absolute vs fixed
<p>I have a tabular view whose thead is fixed and web's header and filter section is also fixed, so filter section contains a bootstrap dropdown whose z-index is 1000 &amp; thead's z-index is 1 but still that dropdown is going behind it, below is the screenshot:</p> <p><a href="https://i.stack.imgur.com/8Blyq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8Blyq.png" alt="enter image description here"></a></p> <p>Here sortby (<code>position: absolute; z-index:1000</code>) is going behind that fixed header (<code>position: fixed; z-index:1</code>)</p> <p>Edit: <a href="https://jsfiddle.net/s86dadmw/" rel="nofollow noreferrer">Fiddle</a></p>
2
Xamarin.Forms: ListView items are not displaying properly on Android Platform
<p>Good Day everyone. I'm creating a simple Xamarin.Forms (Portable) application that allows me to create record of an Employee and display it to a ListView.</p> <p>I was able to do it on the UWP platform and make it appear like this:</p> <p><a href="https://i.stack.imgur.com/q2OjN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q2OjN.png" alt="enter image description here"></a></p> <p>But when I'm trying to run it on Android Platform. It doesn't display any value instead I only have empty page like this one:</p> <p><a href="https://i.stack.imgur.com/B1XW5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B1XW5.jpg" alt="enter image description here"></a></p> <hr> <p>What do you think is the reason behind this? These are my codes for this page:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="XamarinFormsDemo.Views.ClientListPage" xmlns:ViewModels="clr-namespace:XamarinFormsDemo.ViewModels;assembly=XamarinFormsDemo" xmlns:controls="clr-namespace:ImageCircle.Forms.Plugin.Abstractions;assembly=ImageCircle.Forms.Plugin.Abstractions" BackgroundImage="bg3.jpg" Title="Customer List"&gt; &lt;ContentPage.BindingContext&gt; &lt;ViewModels:CustomerVM/&gt; &lt;/ContentPage.BindingContext&gt; &lt;StackLayout Orientation="Vertical"&gt; &lt;ListView ItemsSource="{Binding CustomerList}" HasUnevenRows="True"&gt; &lt;ListView.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;ViewCell&gt; &lt;Grid Padding="10" RowSpacing="10" ColumnSpacing="5"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;controls:CircleImage Source="icon.png" HeightRequest="66" HorizontalOptions="CenterAndExpand" Aspect="AspectFill" WidthRequest="66" Grid.RowSpan="2" /&gt; &lt;Label Grid.Column="1" Text="{Binding CUSTOMER_NAME}" TextColor="#24e97d" FontSize="24"/&gt; &lt;Label Grid.Column="1" Grid.Row="1" Text="{Binding CUSTOMER_CODE}" TextColor="White" FontSize="18" Opacity="0.6"/&gt; &lt;Label Grid.Column="1" Grid.Row="2" Text="{Binding CUSTOMER_CONTACT}" TextColor="White" FontSize="18" Opacity="0.6"/&gt; &lt;/Grid&gt; &lt;/ViewCell&gt; &lt;/DataTemplate&gt; &lt;/ListView.ItemTemplate&gt; &lt;/ListView&gt; &lt;StackLayout Orientation="Vertical" Padding="30,10,30,10" HeightRequest="20" BackgroundColor="#24e97d" VerticalOptions="Center" Opacity="0.5"&gt; &lt;Label Text="© Copyright 2016 SMESOFT.COM.PH All Rights Reserved " HorizontalTextAlignment="Center" VerticalOptions="Center" HorizontalOptions="Center" /&gt; &lt;/StackLayout&gt; &lt;/StackLayout&gt; &lt;/ContentPage&gt; </code></pre> <p>If you want to see more code, just please let me know. Thanks a lot.</p>
2
SQL server convert int field to bit
<p>I have a big database and I should to normalize it. One of the table contains field with type "integer" but it contains only 1 and 0 values. So it is good reason to convert this field to bit type. But when I try to save changes in SQL Server Management Studio it tells me that I can't do it. Also I have many field with values like <em>nvarchar</em> that should be converted to int or float that should be converted to int too. </p> <p>Moreover I should create migration scripts for all changes so I can update real database without loosing data. Maybe somebody knows useful utility for this?</p> <p><strong>EDIT:</strong> It tells me that I can't update unable without drop it. And I want to update table without losing any data. </p> <p>SQL version 2014</p>
2
Table missing from database in sqlite
<p>I have an sqlite database stored in <code>assets/databases/minitest.db</code> and I try to copy it to the local filesystem from the assets folder and then open it. </p> <p>When I open it I get a table not found exception. </p> <p>I am pretty sure it's not something wrong with the database itself because when I open it with an sqlite viewer it looks just fine. I've been googling this problem for about 2 hours now and I have seen a bunch of similar questions but none of their solutions seem to work so I really don't know what to do. </p> <p>Code:</p> <pre><code>mydatabase = new DataBaseHelper(c).myDataBase; Cursor mCursor = mydatabase.rawQuery("SELECT third FROM Trigrams WHERE first='" + first.toLowerCase() + "' AND second ='" + second.toLowerCase() + "' ORDER BY freq DESC LIMIT 0,3", null); </code></pre> <p>Complete DataBaseHelper:</p> <pre><code>class DataBaseHelper extends SQLiteOpenHelper { private Context mycontext; private static final String DB_NAME = "minitest.db"; private static final String DB_PATH = "/data/data/" + BuildConfig.APPLICATION_ID + "/databases/"; private static final int DB_VERSION = 3; public SQLiteDatabase myDataBase; public DataBaseHelper(Context context) throws IOException { super(context, DB_NAME, null, DB_VERSION); this.mycontext = context; boolean dbexist = checkdatabase(); if (dbexist) { System.out.println("Database exists"); opendatabase(); } else { System.out.println("Database doesn't exist"); createdatabase(); opendatabase(); } } public void createdatabase() throws IOException { boolean dbexist = checkdatabase(); if (dbexist) { System.out.println(" Database exists."); } else { this.getReadableDatabase(); try { copydatabase(); } catch (IOException e) { throw new Error("Error copying database"); } } } private boolean checkdatabase() { boolean checkdb = false; try { String myPath = DB_PATH + DB_NAME; File dbfile = new File(myPath); checkdb = dbfile.exists(); } catch (SQLiteException e) { System.out.println("Database doesn't exist"); } return checkdb; } private void copydatabase() throws IOException { //Open your local db as the input stream InputStream myinput = mycontext.getAssets().open("databases/" + DB_NAME); // Path to the just created empty db String outfilename = DB_PATH + DB_NAME; //Open the empty db as the output stream OutputStream myoutput = new FileOutputStream(outfilename); // transfer byte to inputfile to outputfile byte[] buffer = new byte[1024]; int length; while ((length = myinput.read(buffer)) &gt; 0) { myoutput.write(buffer, 0, length); } //Close the streams myoutput.flush(); myoutput.close(); myinput.close(); } public void opendatabase() throws SQLException { //Open the database String mypath = DB_PATH + DB_NAME; myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READONLY); } public synchronized void close() { if (myDataBase != null) { myDataBase.close(); } super.close(); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (newVersion &gt; oldVersion) try { copydatabase(); } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <p>Error log:</p> <pre><code>E/SQLiteLog: (1) no such table: Trigrams E/InputEventReceiver: Exception dispatching input event. E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback E/MessageQueue-JNI: android.database.sqlite.SQLiteException: no such table: Trigrams (code 1): , while compiling: SELECT third FROM Trigrams WHERE first='a' AND second ='baby' ORDER BY freq DESC LIMIT 0,3 at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) at android.database.sqlite.SQLiteProgram.&lt;init&gt;(SQLiteProgram.java:58) at android.database.sqlite.SQLiteQuery.&lt;init&gt;(SQLiteQuery.java:37) at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44) at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1355) at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1294) at com.chair49.sentimentkeyboard.analysis.NextWord.getNextWords(NextWord.java:38) at com.chair49.sentimentkeyboard.SimpleIME.onKey(SimpleIME.java:125) at android.inputmethodservice.KeyboardView.detectAndSendKey(KeyboardView.java:828) at android.inputmethodservice.KeyboardView.repeatKey(KeyboardView.java:1371) at android.inputmethodservice.KeyboardView.onModifiedTouchEvent(KeyboardView.java:1281) at android.inputmethodservice.KeyboardView.onTouchEvent(KeyboardView.java:1214) at android.view.View.dispatchTouchEvent(View.java:9337) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2198) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2198) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2198) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2198) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2554) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2198) at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2432) at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1746) at android.app.Dialog.dispatchTouchEvent(Dialog.java:787) at android.inputmethodservice.SoftInputWindow.dispatchTouchEvent(SoftInputWindow.java:93) at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2393) at android.view.View.dispatchPointerEvent(View.java:9557) at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4263) at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4102) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3644) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3697) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3663) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3789) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3671) at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3846) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3644) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3697) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3663) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3671) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3644) at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5955) at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5929) at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5890) at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6058) at android.view.InputEventReceiver.dispatchInputEvent(Inp 07-14 14:12:42.161 14083-14083/com.chair49.sentimentkeyboard E/AndroidRuntime: FATAL EXCEPTION: main </code></pre>
2
The program to stop working correctly windows will close and notify you if a solution is available
<p>I have a program in Visual Studio C#, when I run it in my pc , it always runs perfect, but when I run it in my client pc , it does not work correctly. shows a message box:</p> <blockquote> <p>A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available</p> </blockquote> <p>Server Form in C#</p> <pre><code>delegate void AddTextCallback(string text); public Form1() { InitializeComponent(); } private void ButtonConnected_Click(object sender, EventArgs e) { ThreadPool.QueueUserWorkItem(new WaitCallback(ServerHandler)); } private void ServerHandler(object state) { try { TcpListener _listner = new TcpListener(IPAddress.Parse(&quot;12.2.54.658&quot;), 145); _listner.Start(); AddText(&quot;Server started - Listening on port 145&quot;); Socket _sock = _listner.AcceptSocket(); while (_sock.Connected) { byte[] _Buffer = new byte[1024]; int _DataReceived = _sock.Receive(_Buffer); if (_DataReceived == 0) { break; } AddText(&quot;Message Received...&quot;); string _Message = Encoding.ASCII.GetString(_Buffer); AddText(_Message); } _sock.Close(); AddText(&quot;Client Disconnected.&quot;); _listner.Stop(); AddText(&quot;Server Stop.&quot;); catch (Exception ex) { ServerHandler(ex.ToString()); } } private void AddText(string text) { if (this.listBox1.InvokeRequired) { AddTextCallback d = new AddTextCallback(AddText); this.Invoke(d, new object[] { text }); } else { this.listBox1.Items.Add(text); } } </code></pre> <p>Getting error in client pc</p> <p><a href="https://i.stack.imgur.com/oUJCx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oUJCx.png" alt="enter image description here" /></a></p> <p>I'm trying to solve this for last 2 wks. But i didn't get any idea about it. Please Someone helps me to solve my problem.</p>
2
Code stopped working for no reason. Throwing up a Missing member Exception...why?
<p>My code stopped working out of nowhere. I am getting this error: </p> <p>An unhandled exception of type 'System.MissingMemberException' occurred in Microsoft.VisualBasic.dll</p> <p>Additional information: Public member 'replace' on type 'Double' not found. Errors out at this line "rCell.Value = rCell.Value.replace("PO", "")"</p> <p>Here is my Code: </p> <pre><code> Imports System.Data.Odbc Imports System.Data.SqlClient Imports System.IO.Directory 'Before you add this reference to your project, ' you need to install Microsoft Office and find last version of this file. Imports Microsoft.Office.Interop.word Imports Microsoft.Office.Interop Imports System.Text.RegularExpressions '=========================================================================ADDRESS FIXER=========================================================================== Public Class Form1 Public Address2Range As String Public PoBoxFirst As String Public NewAddress As String Public rCell As Excel.Range Public NewFirstHalf As String Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click '------------------------------------------------------------------------Browse to Data File-------------------------------------------------------- Dim eXe As String = "C:\WORK\CHRIS_DATA_NOTES\BadAdds\BadAdds.xlsx" '------------------------------------------------------------------Get the path they want to process 'Using tmpDlg As New OpenFileDialog ' tmpDlg.FileName = "C:\WORK\CHRIS_DATA_NOTES\BadAdds" ' While eXe Is Nothing ' If tmpDlg.ShowDialog = DialogResult.OK Then ' eXe = tmpDlg.FileName ' Else ' MsgBox("Please Select something.") ' Exit Sub ' End If ' End While 'End Using 'MsgBox(eXe) Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value xlApp = New Excel.Application xlWorkBook = xlApp.Workbooks.Add(eXe) xlWorkSheet = xlWorkBook.Sheets("sheet1") Dim eColumn As Excel.Range = xlWorkSheet.Range("E2:E1559") ' Dim rCell As Excel.Range '--------------------------------------------------------------Fixes PO Boxes------------------------------------------------------------- For Each rCell In eColumn If rCell.Value = "" Then 'Application.Exit() Else Dim PoBox Dim PoBoxSearch = {"PO BOX", "P.O.", "O Box", "P0", "PO", "P.O. BOX", "Pox", "P 0", "P O ", "Pob", "PO B", "PO 8", "P0 B", "P O B", "P0B", "PO8", "P0B", "P OB", "PX", "POX", "PBX", "P0X", "PBOX", "P0BX", "PU", "O B"} Dim PoList As List(Of String) = New List(Of String)(PoBoxSearch) PoBox = rCell.Value.ToString() PoBoxFirst = PoBox.Substring(0, 1) If PoBoxFirst &lt;&gt; "p" Then rCell.Value = rCell.Value.replace("Box", "") rCell.Value = rCell.Value.replace("PO", "") End If For Each value In PoList If PoBox.contains(value) Then Dim Address As String Address = rCell.Value.ToString() Dim arySpaceFinder() As String arySpaceFinder = Address.Split(" ") 'MsgBox(arySpaceFinder.Last()) If Char.IsLetter(arySpaceFinder.Last()) = True Then 'MsgBox("Has Letter") ' MsgBox(arySpaceFinder.Last()) rCell.Value = "PO Box " &amp; arySpaceFinder.Last().Replace("I", "1") rCell.Value = "PO Box " &amp; arySpaceFinder.Last().Replace("O", "0") rCell.Value = "PO Box " &amp; arySpaceFinder.Last().Replace("X", "") rCell.Value = "PO Box " &amp; arySpaceFinder.Last().Replace("U", "O") Else 'rCell.Value = "PO Box " &amp; Address.Replace("PO", "").Replace("Box", "") rCell.Value = "PO Box " &amp; arySpaceFinder(0) End If rCell.Value = "PO Box " &amp; arySpaceFinder.Last().Replace("I", "1").Replace("O", "0").Replace("X", "").Replace("Pob", "").Replace("U", "O") End If Next End If Next rCell xlWorkSheet.SaveAs("C:\WORK\CHRIS_DATA_NOTES\BadAdds\Box_NEW.xlsx") xlApp.Quit() 'Application.Exit() End Sub </code></pre>
2
Negative lookahead assertion in python
<p>I am having below two line of log, where I want to have separate regular expression for finding each of them. There is no problem to trigger on the second log line. But I have problem to design expression for the first line. The name <code>Reset Reason test</code> is just an example of test, number of words in it may vary therefore I cannot define here any, more specific pattern, then just <code>.*</code>.</p> <pre><code>12.07.2016 13:54:20 SCR_OUTPUT: #### TC_0006 Reset Reason test 12.07.2016 13:54:20 SCR_OUTPUT: #### TC_0006 Reset Reason test done. </code></pre> <p>I am having regular expression generally doing the thing I want it to do:</p> <pre><code>([0-9:. ]*) SCR_OUTPUT: #### (TC_[a-fA-F0-9]{4,5}[:0-9]{0,4}) .*[ ](?!done\.$) </code></pre> <p>And I have two cases that I want to differentiate: I based on example given here. <a href="https://docs.python.org/3/howto/regex.html#lookahead-assertions" rel="nofollow">https://docs.python.org/3/howto/regex.html#lookahead-assertions</a></p> <p>Everything work fine when it ends like this: (of course I have to modify my test strings)</p> <pre><code>[.](?!done$) </code></pre> <p>When I try it to be something that suits me more eg: ( my <code>done.</code> has dot at the end)</p> <pre><code>[.](?!done\.$) </code></pre> <p>Then it gets weird. Another adaptation. <code>done.</code> should be followed with space and not with dot and the result gets crazy. Each line is giving positive findings.</p> <pre><code>[.](?!done\.$) </code></pre> <p>I have been testing that on <a href="http://pythex.org/?regex=(%5B0-9%3A.%20%5D%7B19%7D)%20.*SCR_OUTPUT%3A%20%23%23%23%23%20(TC_%5Ba-fA-F0-9%5D%7B4%2C5%7D%5B%3A0-9%5D%7B0%2C4%7D)%20(.*)%5B%20%5D(%3F!done%5C.%24)&amp;test_string=12.07.2016%2013%3A26%3A11%20SCR_OUTPUT%3A%20%23%23%23%23%20TC_0006%20Reset%20Reason%20test%20sendmail.cf%0A12.07.2016%2013%3A26%3A11%20SCR_OUTPUT%3A%20%23%23%23%23%20TC_0006%20Reset%20Reason%20test%20%20autoexec%0A12.07.2016%2013%3A26%3A11%20SCR_OUTPUT%3A%20%23%23%23%23%20TC_0006%20Reset%20Reason%20test%20autoexec%20bat%0A12.07.2016%2013%3A26%3A11%20SCR_OUTPUT%3A%20%23%23%23%23%20TC_0006%20Reset%20Reason%20test%20foo.bar%0A12.07.2016%2013%3A26%3A11%20SCR_OUTPUT%3A%20%23%23%23%23%20TC_0006%20Reset%20Reason%20test%20first.run%0A12.07.2016%2013%3A26%3A11%20SCR_OUTPUT%3A%20%23%23%23%23%20TC_0006%20Reset%20Reason%20test%20%20run.exe%0A12.07.2016%2013%3A54%3A20%20SCR_OUTPUT%3A%20%23%23%23%23%20TC_0006%20Reset%20Reason%20test%20done%0A12.07.2016%2013%3A54%3A20%20SCR_OUTPUT%3A%20%23%23%23%23%20TC_0006%20Reset%20Reason%20test%20done.&amp;ignorecase=0&amp;multiline=1&amp;dotall=0&amp;verbose=0" rel="nofollow">pythex.org</a>. Under this link you can find latest version my experiment.</p> <p>Anyone knows where I am having a bug? Is it anyhow possible to trigger on such case? Maybe I should do it in two steps?</p>
2
How to create a new cell in UICollectionView when a new string is added to an array
<p>I have a <code>UICollectionView</code> with the cell count being equal to the number of strings in a certain array.</p> <p>When I append a new string to the array, I am expecting it to create a new cell, but it does not.</p> <pre><code>func addDateToArray(dateString: String) { Globals.datesArray.append(dateString) NSUserDefaults.standardUserDefaults().setObject(Globals.datesArray, forKey: "saveddates") } </code></pre> <p>I am appending from another view </p> <pre><code> @IBAction func SetDate(sender: AnyObject) { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let day = dateTimePicker.date let datestring = dateFormatter.stringFromDate(day) addDateToArray(datestring) </code></pre> <p>I don't know why this doesn't work. If I haven't been specific enough, let me know to provide more info.</p>
2
CakePHP 3: Error while passing an array in URL
<p>I am trying to pass <code>datetime</code> variables into my <code>exportcsv</code> method to generate <code>.csv</code> file with data from indicated time period. </p> <p>Both variables are associative arrays that look like this:</p> <pre><code>[ 'beginning' =&gt; [ 'year' =&gt; '2016', 'month' =&gt; '06', 'day' =&gt; '23', 'hour' =&gt; '11', 'minute' =&gt; '15' ], 'end' =&gt; [ 'year' =&gt; '2016', 'month' =&gt; '06', 'day' =&gt; '29', 'hour' =&gt; '11', 'minute' =&gt; '15' ] ] </code></pre> <p>When I try to pass variables I get an error with this message (yep, I've got the same two warnings):</p> <pre><code>Warning (2): rawurlencode() expects parameter 1 to be string, array given [CORE\src\Routing\Route\Route.php, line 574] Warning (2): rawurlencode() expects parameter 1 to be string, array given [CORE\src\Routing\Route\Route.php, line 574] </code></pre> <p><code>rawurlencode()</code> is a basic PHP function and this is the <code>line 574</code>: </p> <p><code>$pass = implode('/', array_map('rawurlencode', $pass));</code></p> <p>It looks like some problem with URL rewriting, but frankly I don't know how to fix it. Any ideas?</p> <p><strong><code>exportcsv</code> method in <code>EventsController</code></strong> </p> <pre><code>public function exportcsv($beginning = null, $end = null) { if ($this-&gt;request-&gt;is('post')) { $beginning = $this-&gt;request-&gt;data['Export']['beginning']; $end = $this-&gt;request-&gt;data['Export']['end']; return $this-&gt;redirect([$beginning, $end]); } if (!$beginning &amp;&amp; !$end) { return $this-&gt;render(); } $this-&gt;response-&gt;download('export.csv'); $data = $this-&gt;Events-&gt;find('all') -&gt;select([ 'title', 'created', 'description', 'ended', 'working_hours', 'price', 'username' =&gt; 'Users.name', 'statusname' =&gt; 'Statuses.name', 'employeename' =&gt; 'Employees.name' ]) -&gt;leftJoinWith('Statuses') -&gt;leftJoinWith('Users') -&gt;leftJoinWith('Employees') -&gt;where(["created BETWEEN " . $beginning . " AND " . $end]) -&gt;autoFields(true) -&gt;toArray(); $_serialize = 'data'; $_delimiter = chr(9); //tab $_extract = ['title', 'created', 'description', 'ended', 'working_hours', 'price', 'username', 'statusname', 'employeename']; $this-&gt;set(compact('data', '_serialize','_delimiter', '_extract')); $this-&gt;viewBuilder()-&gt;className('CsvView.Csv'); return; } </code></pre> <p></p> <p><strong><code>exportcsv.ctp</code> view:</strong> </p> <pre><code>&lt;div class="events form large-6 medium-4 columns content"&gt; &lt;?= $this-&gt;Form-&gt;create('Export'); ?&gt; &lt;?= $this-&gt;Form-&gt;input('beginning', array('type'=&gt;'datetime', 'interval' =&gt; 15, 'label' =&gt; 'Beginning:')); ?&gt; &lt;?= $this-&gt;Form-&gt;input('end', array('type'=&gt;'datetime', 'interval' =&gt; 15, 'label' =&gt; 'End:')); ?&gt; &lt;?= $this-&gt;Form-&gt;button(__('Add')) ?&gt; &lt;?= $this-&gt;Form-&gt;end() ?&gt; &lt;/div&gt; </code></pre>
2
How to use nuget packages not ready for ASP.NET Core 1.0
<p>I need to use some nuget packages that are not ready for ASP.NET Core 1.0 (final release). </p> <p>I have read about all possibles configurations... How can I use nuget packages in my project.json?</p> <pre><code>{ "userSecretsId": "aspnet-WebApplication1-84f1878e-a871-4f80-baca-de15b99a96d9", "dependencies": { "RestSharp": "105.2.3", "Microsoft.ApplicationInsights.AspNetCore": "1.0.0", "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0", "Microsoft.AspNetCore.Diagnostics": "1.0.0", "Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore": "1.0.0", "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0", "Microsoft.AspNetCore.Mvc": "1.0.0", "Microsoft.AspNetCore.Razor.Tools": { "version": "1.0.0-preview2-final" }, "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", "Microsoft.AspNetCore.StaticFiles": "1.0.0", "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0", "Microsoft.EntityFrameworkCore.Tools": { "version": "1.0.0-preview2-final" }, "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0", "Microsoft.Extensions.Configuration.Json": "1.0.0", "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0", "Microsoft.Extensions.Logging": "1.0.0", "Microsoft.Extensions.Logging.Console": "1.0.0", "Microsoft.Extensions.Logging.Debug": "1.0.0", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0", "Microsoft.VisualStudio.Web.CodeGeneration.Tools": { "version": "1.0.0-preview2-final", "type": "build" }, "Microsoft.VisualStudio.Web.CodeGenerators.Mvc": { "version": "1.0.0-preview2-final", "type": "build" } }, "tools": { "Microsoft.AspNetCore.Razor.Tools": { "version": "1.0.0-preview2-final", "imports": "portable-net45+win8+dnxcore50" }, "Microsoft.AspNetCore.Server.IISIntegration.Tools": { "version": "1.0.0-preview-final", "imports": "portable-net45+win8+dnxcore50" }, "Microsoft.EntityFrameworkCore.Tools": { "version": "1.0.0-preview2-final", "imports": [ "portable-net45+win8+dnxcore50", "portable-net45+win8" ] }, "Microsoft.Extensions.SecretManager.Tools": { "version": "1.0.0-preview2-final", "imports": "portable-net45+win8+dnxcore50" }, "Microsoft.VisualStudio.Web.CodeGeneration.Tools": { "version": "1.0.0-preview2-final", "imports": [ "portable-net45+win8+dnxcore50", "portable-net45+win8" ] } }, "frameworks": { "net451": { }, "netstandard1.6": { "imports": [ "dotnet5.6", "dnxcore50", "portable-net45+win8" ], "dependencies": { } } }, "buildOptions": { "emitEntryPoint": true, "preserveCompilationContext": true }, "runtimeOptions": { "gcServer": true }, "publishOptions": { "include": [ "wwwroot", "Views", "appsettings.json", "web.config" ] }, "scripts": { "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ], "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ] } } </code></pre> <p>I'm having some errors like this: </p> <blockquote> <p>Package Microsoft.DotNet.Cli.Utils 1.0.0-preview2-003121 is not compatible with netcoreapp1.0 (.NETCoreApp,Version=v1.0). Package Microsoft.DotNet.Cli.Utils 1.0.0-preview2-003121 supports: - net451 (.NETFramework,Version=v4.5.1) - netstandard1.6 (.NETStandard,Version=v1.6)</p> </blockquote> <p>I'm using Windows 10 and VS2015 Update 3. Thanks.</p>
2
"Is not a working copy" error when trying to commit SVN
<p>I'm so confused about this.. I think there's something missing in the error that could help, but I'm not sure.</p> <p>When trying to commit to an SVN repository, NetBeans is returning this error:</p> <blockquote> <p>org.apache.subversion.javahl.ClientException: E155007: {0} is not a working copy</p> </blockquote> <p>Upon reading up, I've tried several things, including Updating, Cleaning Up, and Checking out.. (checking out actually screwed things up a fair bit and duplicated my project).</p> <p>But all of them, still return the error. I believe the {0} part is meant to be showing a file that isn't under version control, is that correct?</p> <p>Not sure where to go from here, and I can't make any more commits. If possible, I don't want to have to just abandon, and create a new project and SVN repository from scratch.</p> <p>My Netbeans SVN properties shows this: <a href="https://i.stack.imgur.com/CodpI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CodpI.jpg" alt="enter image description here"></a></p>
2
Extract respective upper and lower triangle's elements of matrix in R
<p>Given square matrix <code>m</code> as follows (<code>nxn</code>):</p> <pre><code>m &lt;- matrix(1:5,ncol = 5,nrow = 5,byrow = F) [,1] [,2] [,3] [,4] [,5] [1,] 1 1 1 1 1 [2,] 2 2 2 2 2 [3,] 3 3 3 3 3 [4,] 4 4 4 4 4 [5,] 5 5 5 5 5 </code></pre> <p>I want to extract the respective upper and lower triangle's elements and take the relative frequency. </p> <p>We can naively do that via a loop like this (here <code>n=5</code>):</p> <pre><code>for (i in 1:(n-1)) for (j in (i+1):n){ x &lt;- m[i,j] y &lt;- m[j,i] m[i,j] &lt;- x/(x+y) m[j,i] &lt;- y/(x+y) } </code></pre> <p>Here is the desired output:</p> <pre><code> [,1] [,2] [,3] [,4] [,5] [1,] 1.0000000 0.3333333 0.2500000 0.2000000 0.1666667 [2,] 0.6666667 2.0000000 0.4000000 0.3333333 0.2857143 [3,] 0.7500000 0.6000000 3.0000000 0.4285714 0.3750000 [4,] 0.8000000 0.6666667 0.5714286 4.0000000 0.4444444 [5,] 0.8333333 0.7142857 0.6250000 0.5555556 5.0000000 </code></pre> <p>Can we generate this output more efficiently?</p> <p>P.S.</p> <p>I'm aware of <code>m[upper.tri(m)]</code> and <code>m[lower.tri(m)]</code>, but it does not the trick because the order of extracted elements are different. For example, <code>m[upper.tri(m)]</code> will give me:</p> <pre><code>[1] 1 1 2 1 2 3 1 2 3 4 </code></pre> <p>While what of I want for the upper triangle is:</p> <pre><code>[1] 1 1 1 1 2 2 2 3 3 4 </code></pre>
2
Referer Not Allowed Map Error
<p>I have a file in my pc named "GMPos.html", the file contains 1 marker:</p> <pre><code> &lt;script src='https://maps.googleapis.com/maps/api/js?v=3.4&amp;key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var icon_shadow = new google.maps.MarkerImage('icons/mm_20_shadow.png', new google.maps.Size(28,22), new google.maps.Point(0,0), new google.maps.Point(10,21)); var a_icon = new google.maps.MarkerImage('icons/mm_20_red.png', new google.maps.Size(22,22), new google.maps.Point(0,0)); var map; function loadMap() { var myLatLng = new google.maps.LatLng(14.60192,-90.53268); var myOptions = { center: myLatLng, zoom: 12, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('map_canvas'), myOptions); var marker = new google.maps.Marker({ position: myLatLng, icon: a_icon, shadow: icon_shadow, map: map, title:'Id: GUA001' }); } &lt;/script&gt; </code></pre> <p>When I try to open the file in Firefox, I got the following error:</p> <blockquote> <p>"Google Maps API error: Google Maps API error: RefererNotAllowedMapError <a href="https://developers.google.com/maps/documentation/javascript/error-messages#referer-not-allowed-map-error" rel="nofollow">https://developers.google.com/maps/documentation/javascript/error-messages#referer-not-allowed-map-error</a> Your site URL to be authorized: file:///C:/RunTime/Mss/GMH/GMPos.html"</p> </blockquote> <p>So, I have added the following referres:</p> <pre><code>*C:/RunTime/Mss* file:///C:/RunTime/Mss/GMH/GMPos.html *file:///C:/RunTime/Mss/GMH/GMPos.html* </code></pre> <p>But still throws the same error, please help.</p> <p>Thank you in advance</p>
2
Relative path in html with php server
<p>I use <code>php -S localhost:8000</code> as my development server. At the end I'll use nginx. But I have a problem with php server.</p> <pre><code>root | |---/app | |---/index.html |---/scripts | | | |---/main.css | |---/styles | |---/main.js </code></pre> <p>In my <code>app/index.html</code> I have:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href="styles/main.css" type="text/css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;script src="scripts/main.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>When I open the page in my browser with <code>localhost:8000/app</code> the css and javascript can't be find. The browser is looking for <code>localhost:8000/styles</code> resp. <code>localhost:8000/scripts</code> instead of <code>localhost:8000/app/styles</code> resp. <code>localhost:8000/app/scripts</code>. When I directly open the file withouth server or with nginx, the files are found correctly. So the php server changes something. What's going on here?</p> <p>I tried it in Chrome and Firefox. Same behavior in both browsers. When I open the website with <code>localhost/app</code> (<code>nginx</code>) everything works as expected. When I open the website with <code>localhost:8000/app</code> (<code>php -S localhost:8000</code>) the scripts and styles can't be found. It's the same files with the same file root. Where comes the different behavior from?</p>
2
AngularJS $viewContentLoaded doesn't work
<p>I am trying to get $viewContentLoaded to work, but no matter what I try, it just refuses to fire. Here is where I am currently. </p> <p>Javascript (directive.js)</p> <pre><code>var app = angular.module('myapp', []); app.controller('MainCtrl', function($scope, $timeout) { $scope.$on('$viewContentLoaded', function () { $timeout(function () { var x = document.getElementById("iframe"); alert(x); //Never Fires. }, 0); }); }); </code></pre> <p>The HTML </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html ng-app="myapp"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;script data-require="[email protected]" src="http://code.angularjs.org/1.2.7/angular.js" data-semver="1.2.7"&gt;&lt;/script&gt; &lt;script src="script/directive.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body ng-controller="MainCtrl"&gt; &lt;iframe id="iframe"&gt;&lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I have tried this multiple ways: </p> <p>I have taken the $timeout stuff out. I've tried using it combined with routing. I've tried using $watch in place of $on. This was able to give me an alert, but not at the correct time. I've tried this in IE11 and Chrome, neither work There is nothing logged in the console. </p> <p>This just flat out will not work. Where am I going wrong? </p> <p>Edit: <a href="https://jsfiddle.net/U3pVM/25952/" rel="nofollow">https://jsfiddle.net/U3pVM/25952/</a></p>
2
AngularJS hash url and MVC routing
<p>I am facing issue in navigating to URL. My default page set to Login and my application URL is <code>http://localhost:12345/#/</code>.</p> <p>This works well but there are two ways the user can login to application </p> <blockquote> <ol> <li>Direct through the application.</li> <li>Getting username and password trough query string.</li> </ol> </blockquote> <p>When application is logging through Query String the url is like <code>http://localhost:12345?auth=123654654656564/#/</code>.</p> <p>I would like to remove auth value from the URL. I tried to map the routing but it doesn't work.</p> <pre><code>routes.MapRoute( name: "Default", url: "{controller}/{action}", defaults: new { controller = "Account", action = "Login"} ); </code></pre> <p>And also i tried to create one more action result that will return the <code>view</code></p> <pre><code>routes.MapRoute( name: "ActualDefault", url: "{controller}/{action}", defaults: new { controller = "Account", action = "LoginQuery" } ); </code></pre> <p>Controller:</p> <pre><code> public ActionResult Login() { if (Request.QueryString.Count &gt; 0 &amp;&amp; Request.QueryString != null) { //validating return RedirectToAction("LoginQuery", "Account"); } else { return View(); } } public ActionResult LoginQuery() { return View("Index"); } </code></pre> <p>The above code removes query string but the URL will be <code>http://localhost:12345/Account/LoginQuery/#/</code>.</p> <p>I just need the URL like <code>http://localhost:12345/#/</code>.</p>
2
build.plugins.plugin.version' for org.mortbay.jetty:jetty-maven-plugin is missing
<p>I used the book "Build ing a Restufl WEb Service with Spring" chapter2 project. I imported the maven project in eclipse and I did a maven test and get the below error:</p> <p>[WARNING] Some problems were encountered while building the effective model for com.packtpub.rest-with-spring:rest-with-spring-all:war:1.0.0-SNAPSHOT [WARNING] 'build.plugins.plugin.version' for org.mortbay.jetty:jetty-maven-plugin is missing. @ com.packtpub.rest-with-spring:rest-with-spring-all:[unknown-version], C:\workspace_buildingRest\B04788_02_code\all\pom.xml, line 21, column 21 [WARNING] [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.</p> <p>Here is my pom.xml</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;com.packtpub.rest-with-spring&lt;/groupId&gt; &lt;artifactId&gt;rest-with-spring&lt;/artifactId&gt; &lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt; &lt;/parent&gt; &lt;artifactId&gt;rest-with-spring-all&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;${project.groupId}&lt;/groupId&gt; &lt;artifactId&gt;rest-with-spring-billing&lt;/artifactId&gt; &lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt; &lt;classifier&gt;classes&lt;/classifier&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt; &lt;artifactId&gt;jetty-maven-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;useTestScope&gt;true&lt;/useTestScope&gt; &lt;stopPort&gt;8005&lt;/stopPort&gt; &lt;stopKey&gt;DIE!&lt;/stopKey&gt; &lt;systemProperties&gt; &lt;systemProperty&gt; &lt;name&gt;jetty.port&lt;/name&gt; &lt;value&gt;8080&lt;/value&gt; &lt;/systemProperty&gt; &lt;/systemProperties&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p></p> <p>Any help or hint is greatly appeciated it.</p>
2
How to compress hdf5 file when resizing?
<p>Here is my code:</p> <pre><code>n = 100000 #This is what makes it tricky - lots of files going into this hdf5 file with h5py.File('image1.h5','w') as f: dset_X = f.create_dataset('X',(1,960,224,224),maxshape=(None,960,224,224),chunks=True,compression='gzip') dset_y = f.create_dataset('y',(1,112,224*224),maxshape=(None,112,224*224),chunks=True,compression='gzip') n_images = 0 for fl in files[:n]: X_chunk,y_chunk = get_arrays(fl) dset_X.resize(n_images+1,axis=0) dset_y.resize(n_images+1,axis=0) print dset_X.shape,dset_y.shape dset_X[n_images:n_images+1,:,:,:]=X_chunk dset_y[n_images:n_images+1,:,:]=y_chunk n_images+=1 </code></pre> <p>This works fine and dandy. However, with 1 file, the size of the hdf5 is 6.7MB. With 2 files its 37MB ( should be 12 MB right?). With 10 its all the way up to 388MB (should be 67 right?)</p> <p>So clearly adding the compression flag to the end of the 2nd and third line isn't working as intended. How can I achieve something like this? </p>
2
MySQL into output file error
<p>I am very new with SQL but I have to extract some fields of a table stored in a sql file.</p> <p>I have installed mysql and create the database and source the file. Now I wanted to execute a sql request in order to read all the elts of the table, extract the interesting fields and write them into cvs file: </p> <pre><code>SELECT * INTO OUTFILE '/home/cr/database/Dump2/program_info.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n' FROM program_info; </code></pre> <p>When running the command I have the following error message:</p> <blockquote> <p>ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement</p> </blockquote> <p>Does anyone knows how to solve it ? I have struggled with this message all the afternoon but could not .</p> <p>I am working on Linux ubuntu and my config file is /etc/my.cfg</p> <blockquote> <p>[mysqld] read-only = 0 secure-file-priv = ""</p> </blockquote> <p>Thank you for your help</p>
2
Using Google Maps API with Meteor.js
<p>I'm trying to use the Google Maps API with Meteor 1.3 and with the dburles:google-maps package.</p> <p>I tried various way to load it but the thing is that I can't use it because it takes too long to load I think and my page is rendered before.</p> <p>I load it this way in my <code>main.js</code> to be sure that is loaded first.</p> <pre><code>import { GoogleMaps } from 'meteor/dburles:google-maps'; import { Meteor } from 'meteor/meteor'; Meteor.startup(function () { GoogleMaps.load({ key: 'myKey' }); }); </code></pre> <p>Then I include the helper in my template to display the map.</p> <pre><code>&lt;template name="home"&gt; &lt;h1&gt;Home&lt;/h1&gt; &lt;div class="map-container"&gt; {{&gt; googleMap name="exampleMap" options=exampleMapOptions}} &lt;/div&gt; &lt;/template&gt; </code></pre> <p>Finally there is my helper to set the options for the template.</p> <pre><code>import { Template } from 'meteor/templating'; import { GoogleMaps } from 'meteor/dburles:google-maps'; import './home_page.html'; Template.home.helpers({ exampleMapOptions() { // Make sure the maps API has loaded if (GoogleMaps.loaded()) { // Map initialization options return { center: new google.maps.LatLng(-37.8136, 144.9631), zoom: 8, }; } }, }); Template.home.onCreated(function() { GoogleMaps.ready('exampleMap', function(map) { console.log("I'm ready!"); }); }); </code></pre> <p>I think that the condition <code>if (GoogleMaps.loaded())</code> is the reason why nothing is displayed but if I dont put it I got an error because the <code>google</code> object doesn't exist.</p>
2
Expire php session variable after period of time
<p>Is there a way to set a php session variable (<code>$_SESSION['example'</code>) to expire after a given amount of time. To clarify, <strong>I want to keep the user's session intact and keep all other variables with their values</strong>, I only want to set a single session variable to expire after a short time period (1 minute or so). Is there any way to set the variable to expire on its own or will I have to keep track of time and delete the variable when I have determined that the time has expired? I am using php 5 with apache2 on ubuntu. Thanks.</p>
2
Comparing a char value with an object
<p>In Java, the <code>pop()</code> function returns the popped out value in the form of an object.</p> <p>I converted the object into a <code>String</code> using the <code>.toString()</code> method. I have a character which I converted into a <code>String</code>. Now my question is that if I compare the two Strings, will they be equal or not?</p> <p>Example: (Assume that I already had some values in the stack)</p> <pre><code>Stack&lt;Character&gt; stack=new Stack&lt;&gt;(); Character c=stack.pop(); //let the returned value is : a String a=c.toString(); String b=Character.toString('a'); </code></pre> <p>Now if I compare the two Strings as:</p> <pre><code>if(a.equals(b)){System.out.println("same");} </code></pre> <p>Will the condition becomes true?</p>
2
What is the best way to concatenate multi-dimensional arrays in java?
<p>I have 2 dimensional, 3 dimensional and 4 dimensional arrays. (All at different times)<br> If I want to concatenate 4 2D arrays (4 2x2's in to 1 4x4), I can do this with simple looping </p> <pre><code>int[][] result = new int[2 * array1.length][2 * array1.length]; for(int x = 0; x &lt; array1.length; x++) for(int y = 0; y &lt; array1.length; y++) result[x][y] = array1[x][y]; for(int x = array1.length; x &lt; result.length; x++) for(int y = 0; y &lt; array1.length; y++) result[x][y] = array2[x - array1.length][y]; ... </code></pre> <p>As you can see, this gets very messy (2^n sets of loops where n is number of dimensions). I know I could simplify this with System.arraycopy, but I would still need just as many sets of loops.<br> Is there an easier way for me to do this? Preferrably one that works for all dimensional arrays?<br> Note that I am adding on to each dimension, not just adding one to the end of another. To visualize what I'm doing, imagine each 2D array as a square and each 3D array as a cube. To combine them, stitch them together forming a 2x2 square (where each unit is one 2D array) or a 2x2x2 cube (where each unit is one 3D array).<br> Here's a poorly drawn visualization of 2D combination.<br> <code>|--| + |--| + |--| + |--| = |--|--|</code><br> <code>|--| |--| |--| |--| |--|--|</code><br> <code>. |--|--|</code></p>
2
cURL not working on Google Compute engine
<p>I'm facing a similar issue to this question on my VM instance that runs WordPress:</p> <blockquote> <p><a href="https://stackoverflow.com/questions/38014596/php-retrieve-facebook-image-in-google-compute-engine">PHP - Retrieve Facebook image in Google Compute Engine</a></p> </blockquote> <p>I'm using AJAX to call <code>send_otp.php</code> with <code>mobile_number</code> as a parameter.</p> <p>My <code>send_otp.php</code> script is:</p> <pre><code>$mobile_number = $_POST['mobile_number']; // Don't do in production, possible RCE $url = &quot;http://gateway.com/api?numbers=&quot; . $mobile_number. &quot;&quot;; // Initiate curl $ch = curl_init(); // Disable SSL verification (Don't do in production) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Will return the response, if false it print the response curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Set the url curl_setopt($ch, CURLOPT_URL, $url); // Execute $result = curl_exec($ch); // Closing curl_close($ch); $result = json_decode($result, true); </code></pre> <p>And my Javascript code is as follows:</p> <pre><code>cust_mob = jQuery('#number'); jQuery.ajax({ url: 'send_otp.php', type: 'POST', dataType: 'json', data: { mobile_nuber: '' + cust_mob.val().toString() + '', security: '&lt;?php echo wp_create_nonce('mobile-validate-nonce'); ?&gt;' }, success: function (response) { console.log('success'); }, error: function (response) { console.log('success'); } }); </code></pre> <p>I've removed a lot of code just to post it here and everything works fine on my local machine WordPress installation using WAMP.</p> <p>This code is a part of my theme and all I'm doing is zipping the theme folder and uploading it to WordPress after making changes. Everything works fine except this 'curl' part e.g. login using ajax and updating profile using AJAX is working fine.</p> <p>Please tell me how to resolve it, or are there any other methods to achieve the same?</p>
2
Passing json array using retrofit
<p>I am new to android and retrofit and I am facing a lot of problem parsing json array.. I can print the json response in my logcat. and its working fine. I just want to display the image and data now on my device in a cardview. Please I have been struggling with this for more den weeks.. Help me guys. Help me with my code. I dont want to give up.</p> <p><strong>pojo class:</strong> </p> <pre><code>public class DetailData { public String image; public String pname; public String pprice; public String pdescr; public String getPdescr() { return pdescr; } public void setPdescr(String pdescr) { this.pdescr = pdescr; } public String getPprice() { return pprice; } public void setPprice(String pprice) { this.pprice = pprice; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } } </code></pre> <p><strong>Adapter class:</strong></p> <pre><code>public class DetailsAdapter extends RecyclerView.Adapter&lt;DetailsAdapter.usersViewHolder&gt; { private ArrayList&lt;DetailData&gt; itemList; private Context context1; onclickListener mOnclickListener; public DetailsAdapter(Context context, ArrayList&lt;DetailData&gt; itemList) { this.itemList = itemList; this.context1 = context; } public void updatevalues(ArrayList&lt;DetailData&gt; newlist) { this.itemList = newlist; notifyDataSetChanged(); } public class usersViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @Bind(R.id.description) TextView pdescr; @Bind(R.id.image) ImageView image; @Bind(R.id.pprice) TextView pprice; @Bind(R.id.parent) RelativeLayout parent; public usersViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); parent.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.parent: mOnclickListener.onCategoryClick(itemView, getAdapterPosition()); break; default: break; } } } @Override public DetailsAdapter.usersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cat_detaillist, null); DetailsAdapter.usersViewHolder viewHolder = new DetailsAdapter.usersViewHolder(layoutView); return viewHolder; } @Override public void onBindViewHolder(usersViewHolder holder, int position) { DetailData current = itemList.get(position); holder.pdescr.setText(current.getPdescr()); holder.pprice.setText(current.getPprice()); // holder.pdescr.setText(current.getPdescr()); } @Override public int getItemCount() { return itemList.size(); } public interface onclickListener { void onCategoryClick(View v, int position); } public void setOnItemClickListener(final onclickListener mItemClickListener) { this.mOnclickListener = mItemClickListener; } } </code></pre> <p><strong>Activity class:</strong></p> <pre><code>public class Test extends AppCompatActivity { Call&lt;ResponseBody&gt; call; DetailsAdapter rcAdapter; RecyclerView recyclerView; ArrayList&lt;DetailData&gt; adapterList = new ArrayList&lt;&gt;(); LinearLayoutManager linearLayoutManager; private static final String JSON_BED = "http://localhost/shree_decor/jsonfetch.php"; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.cat_detail); Intent i = getIntent(); int catid = i.getExtras().getInt("catid"); recyclerView = (RecyclerView) findViewById(R.id.rv); rcAdapter = new DetailsAdapter(Test.this, adapterList); linearLayoutManager = new LinearLayoutManager(Test.this); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(rcAdapter); recyclerView.setHasFixedSize(true); API service = ServiceGenerator.createService(API.class); call = service.getCategoriesData(String.valueOf(catid)); call.enqueue(new Callback&lt;ResponseBody&gt;() { @Override public void onResponse(Call&lt;ResponseBody&gt; call, Response&lt;ResponseBody&gt; response) { String urlResponse = Utils.convertTypedBodyToString(response); JSONObject json = null; JSONArray jsonResponse = null; Log.i("CatResponse - ", "" + urlResponse); //Log.i("CatResponse - ", "" + json); //CHECK THIS! try { json = new JSONObject(urlResponse); //coverting arraylist to array String[] stringArray = adapterList.toArray(new String[0]); for (int i = 0; i &lt; stringArray.length; i++) { DetailData current = new DetailData(); current.setPname(stringArray[i]); // current.setImage(img[i]); adapterList.add(current); } //return adapterList; } catch (JSONException e) { e.printStackTrace(); } try { jsonResponse = json.getJSONArray("result"); Log.i("Array", "" + jsonResponse); } catch (JSONException e) { e.printStackTrace(); } //PASS THE JSON ARRAY ONLY ArrayList&lt;DetailData&gt; itemList = null; Context context1 = null; //Log.i("CatResponse1 - ", "" + json); adapterList = getData(jsonResponse); DetailsAdapter da = new DetailsAdapter(context1, itemList); da.updatevalues(adapterList); } @Override public void onFailure(Call&lt;ResponseBody&gt; call, Throwable t) { Log.i("RetroError - ", "" + t.getMessage()); } }); } public ArrayList&lt;DetailData&gt; getData(JSONArray details) { ArrayList&lt;DetailData&gt; data = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; details.length(); i++) { DetailData current = new DetailData(); try { current.setImage(details.getJSONObject(i).getString("image")); current.setPdescr(details.getJSONObject(i).getString("pdescr")); current.setPname(details.getJSONObject(i).getString("pname")); current.setPprice(details.getJSONObject(i).getString("pprice")); data.add(current); } catch (JSONException e) { e.printStackTrace(); } } return data; } } </code></pre> <p><strong>xml layouts</strong> </p> <pre><code> &lt;include android:id="@+id/toolbar" layout="@layout/toolbar" /&gt; &lt;android.support.v7.widget.RecyclerView android:id="@+id/rv" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;/android.support.v7.widget.RecyclerView&gt; &lt;/LinearLayout&gt; &lt;android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" card_view:cardCornerRadius="5dp"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="10dp" android:orientation="vertical"&gt; &lt;ImageView android:id="@+id/image" android:layout_height="match_parent" android:layout_width="wrap_content"&gt;&lt;/ImageView&gt; &lt;TextView android:id="@+id/description" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:textSize="18dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" /&gt; &lt;TextView android:id="@+id/pprice" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; &lt;/android.support.v7.widget.CardView&gt; </code></pre> <p>response</p> <pre><code>{ "result": [{ "image": null, "pname": "Barshi Bed", "pprice": "20000", "pdescr": "Barshi bed Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." }, { "image": null, "pname": "King bed nexa one", "pprice": "15000", "pdescr": "King bed nexa one Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." }, { "image": null, "pname": "Royal Sofa", "pprice": "25000", "pdescr": "Royal Sofa Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." }] } </code></pre> <p>Please help me!</p>
2
How to display image into picture box contain in string
<p>I have an image string contain in an XML file and want to convert the string into an image. I have used the following code which is giving error: <strong>Parameter is not valid.</strong></p> <p>Code is following which is give above error:</p> <pre><code> Byte[] data = new Byte[0]; byte[] array = Encoding.ASCII.GetBytes("D:\notimg.txt"); MemoryStream mem = new MemoryStream(array); pictureBox1.InitialImage = null; pictureBox1.Image = Image.FromStream(mem); </code></pre> <p>Below is the data contained in XML tag which I need to convert into the image and display into picture box, I have placed the below data into a notepad file and removed the XML tag . Please, anyone, guide how to display the below data into an image. Thanks in advance.</p> <pre><code>&lt;photograph&gt;/9j/4AAQSkZJRgABAQECWAJYAAD/4QBuRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAZKGAAcAAAA6AAAALAAAAABVTklDT0RFAABDAHIAZQBhAHQAZQBkACAAYgB5ACAAQQBjAGMAdQBTAG8AZgB0ACAAQwBvAHIAcAAu/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy/8AAEQgBwgFeAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A9+opaT0oAKKWigBKKWigBKKWkoAKKKKACiiigAoopaAEopaKAEopaKAEopaKAEopaKAEopaKAEopaKAEopaKAEopaKAEopaKAEopaKAEopaKAEopaKAEopaKAEopaKAEopaKACk9KWk9KAFooooAKKKKACkpaSgAooooAKKKKAClpKWgAoorPv8AVrLTE3XM6oeyDlj9BSvYDQorir7xm5hb7HCIgDgPKRk/Qf8A665O61+7uSftF5K4btuwPyHFLmFc9aNzAhwZo1PoWAqNdQtHYqlzExBwdrA4rxv+0FUYXNDX4btjtSuxXPZ2u4V6yxj6uBSC8gP3Z4T9JBXixmyODSbzngD8RRdjue3CXd0XI/2SDQZFX72VHuOK8agvZbfOw7c+gq9beItRtyPLvZl56Ftw/I5p3C560CCMg5HtTq89tPGN3G37+GKYf3l+RvxxwfyretPFNpOPmYj1DDDD+hp3C50lFRRTRzxrJE4ZWGQQalpjCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKT0paSgBaKKKACiiigApKWkoAKKKKACiiigAqKWWOCJpJGCIgyWPAApZpo7eJpZWCovJJrzfxJ4hOp3DW0MgW2jOc54b396luwmy7rPjdyWh0zCAcecwyT9AelchPqMjuzyMzyP1Zjk1Ukl6hTx796rs1KxJPJclzk5zUJl9Kjyc8flTSSOq4FCVgJi3oAaRnz0Tb9Ki3gDgUB8U7jJVJ/vfnUyuynqCBUAb0FOXd6UgsWlkODlfxp4NQKrdxx9KeuV/CmFiyuVI2uRViOV88kfUcVQEn4EVKkoPUflQB0uk63cacQI2DxE8o39Peu60zVINSi3RnBAGVPUV5TG68bTx+lX7LUptPuhMhPoy9jQhbHrNFUtPvYr+yjniPDAZHcH0q7VFhRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAlFFFABRRRQAUUUUAFFFFABRRRQAU1mVF3MQAKGIVSScAck1x3inxE1kv2eA4mccf9Mx6/U9vSk3YTdjL8Za21xOLOGQrFGfnUHqfeuKkf5sg5xT55NzEs2SaqtIBx6VCXclCn3qMntxTS2e5FNyv940xjs4HBINKST940wAfSlBI44FAIcB2HFSKvuajU4z81OXGeTQth2JVOPTiplGccZqEoNu5WP50qSFOWUsB6HFAiflT8v5UqzA9SUbpVd7mNum5SPU803zMcsA49RSuBZ80g4Kqw/I07tvjOR3HcVSEmMN1/pUgf8AjTgjqKdwLKzbSCDwavRyCWPb0PashmzkgY3c49DU0EpRgc0MDuvBuo+VLJA7YyQMHpXbtd26j5pUX/eOK8aW7ltnE8LFGPBI7e9Oi1CfzDIJnDk5LE5Jouw1PY47y2lbakyMR6GrFeRw63fRtzMWHowyK6TSvE7p8jnHoGPy/wD1qaYJncUVTtL2O5UbflbGdpPb1B7irlUUgooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooqreXSWdpJO7BVRc5Jo2Fexna1qSWNpJIxG2PgDP3m7D8K8mvbvzJ5JnYu7nOSa0df1t9Um2odsMfTPc9ya52TG/nJrNa6krUa8vOf6Uwle/HvTWbsKYSTTGPLxjsW/HFAc5wFA96YBk+n1qTAUcc0gsOyxPapETPXg01flALbgPYU/wA4IRsBB9xmqDYRo2QZ2Fu9K0kQQgR4z69qYJJSSFC/yqMXbq3Qj2IyKWwD12gZ2kD+8vOKcueiPuBpquGOUOxsdu/4U/y2XGR15BFK4xsg5+dcEUi5Qe3oalXdnnml8vPNK4WIjjqBipFbB46U4Rd6csXQY5ouOwh42jtyRTgnzcdKVozwOmKkRe350XsFhwOUIPpTF4OAasqi46HNQSIQSF4+lCkKxLFICQA+D71bjlIPzZ+orMC4PuPep4d+OOcenWqFY6Kx1i4tCmx9yqcgZxiu+0fWIdTh+VgJUHzLXlCSEY7+xFX7DUJbOdZoppRRVDR//2Q==&lt;/photograph&gt; </code></pre>
2
Windows 10 tray menu behind taskbar
<p>I have an application with an icon in the system tray.<br> When you right click the tray icon it shows a menu where the user can select an action.<br> I have found that if I have a full screen application running and then use alt + esc to get to the tray icon. Then when I right click the icon the menu will show up behind(under) the windows taskbar.<br> In some cases, the menu is so low that it is not possible to select the lowest menu item in the context menu.<br> When it is not a full screen application that is in front the menu is correctly shown on top of the taskbar. I have also testes on windows 7 where it works fine with full screen application.<br> I have tried with different full screen application like internet explorer, Notepad++ but the same thing happens.<br> I can also see that there are lots of other application like “Skype for business” and “Radeon Settings” that does the same thing.<br> Skype for business with menu behind taskbar: <a href="https://i.stack.imgur.com/zGDO2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zGDO2.png" alt="enter image description here"></a><br><br> For the build-in windows 10 applications this works better.<br> The Windows Time and Language parts of the system tray will show menus on top of the taskbar with the new windows 10 layout (black)<br> The Windows Sound and Network icons will hide the taskbar while showing a regular right click menu, but keeping the start menu open. (This however looks a bit strange)<br> <br> I have tried with the NotificationIcon sample from the windows SDK but this also does not work correctly.<br> <br> So the question is what is the right way to program showing tray context menu’s for windows 10?<br> My code looks like this.</p> <pre><code>case WM_RBUTTONDOWN: { SetForegroundWindow(); CMenu menu; menu.LoadMenu(ID_TRAY_MENU_SHOW_APP); CMenu* pPopup = menu.GetSubMenu ( 0 ) ; GetCursorPos ( &amp;pt ) ; pPopup-&gt;TrackPopupMenu ( TPM_LEFTALIGN | TPM_RIGHTBUTTON,pt.x, pt.y, this ); } </code></pre> <p>Thanks for you help</p>
2
How to contain UIViewController view between navigation bar and tab bar?
<p>I have created a storyboard layout which contains UIViewControllers within UINavigationControllers which all connect back to a UITabBarController. There is a login page which is not connected to anything (just a UIViewController) which segues into the UITabBarController when the app detects user authentication. You can see what this looks like in the following image:</p> <p><a href="https://i.stack.imgur.com/kyuSW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kyuSW.png" alt="Storyboard Layout"></a></p> <p>When I set the translucent property of the Navigation Bar to "false" or "No", the view y origin gets pushed down to the bottom of the Navigation Bar (which is the behavior that I am looking for). However, when I set the translucent property of the Tab Bar to "false" or "No", the Tab Bar DOES become opaque, but the view is not resized to fit between the top and bottom bars. I have unchecked the <strong>Extend Edges</strong> property for both <strong>Under Top Bars</strong> and <strong>Under Bottom Bars</strong> for all UIViewControllers, UINavigationControllers, and the UITabBarController.</p> <p><a href="https://i.stack.imgur.com/Ij2fW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ij2fW.png" alt="Extend Edges"></a></p> <p>When I add subviews programmatically (no auto-layout), the UIViewController's view is still the height of the entire screen, and is only pushed down from the top bar, but not pushed up from the bottom bar. While creating this question, this is the result I got on the simulator (subviews are not even starting below the Navigation Bar):</p> <p><a href="https://i.stack.imgur.com/agPs4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/agPs4.png" alt="Simulator"></a></p> <p>The layout that I'm trying to achieve is to have the view fit between the Navigation Bar and the Tab Bar so that both bars are opaque and no content goes underneath them. Any ideas or suggestions?</p> <p>EDIT:</p> <p>After eliminating individual Navigation Controllers and adding a single one before the TabBar Controller, I'm getting weird behavior including navigation items disappearing and one of my subviews still goes under bottom bar.</p> <p><a href="https://i.stack.imgur.com/3dLmG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3dLmG.png" alt="Simulator"></a></p> <p>EDIT 2:</p> <p>After doing some research, It seems that having navigation controllers inside each tab is a normal view hierarchy. Unfortunately, I still have not figured out how to limit a view controller's view to be between a navigation bar and a tab bar. Any suggestions?</p>
2
Cannot assign value of type '[String]' to type 'String? Swift 2
<p>I am receiving this error message "Cannot assign value of type '[String]' to type 'String?'" associated with this line "point.title = r" and this line "point.subtitle = z". I've tried lots of things like place.description which makes the entire array a string...</p> <pre><code>//I have multiple arrays, lat, long and pass besides place. var place = [String]() //I have four of the chunks of code for each array let json = try NSJSONSerialization.JSONObjectWithData(jSONData, options: .AllowFragments) if let dataFile3 = json["data"] as? [[String: AnyObject]] { for c in dataFile3 { if let placeName = c["PlaceName"] { place.append((placeName as? String)!) for var (i,x) in zip(lat, long) { for _ in place { for _ in pass { print(i) print(x) //print(i + ", " + x) // String to double conversion, can I do this when I set the array as a string? let lati = NSString(string: i).doubleValue let longi = NSString(string: x).doubleValue //I have a list of values array so I need to have a for loop that inputs the value over and over again. var point = MGLPointAnnotation() point.coordinate = CLLocationCoordinate2D(latitude: lati, longitude: longi) point.title = place point.subtitle = pass mapView.addAnnotation(point) }}} //var i and x for loop } //viewDidLoad } //creates the markers popup for each point with data func mapView(mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -&gt; Bool { // Always try to show a callout when an annotation is tapped. return true } </code></pre> <p>How do I fix the error above?</p> <p>EDIT: With Santosh's help this is what I changed...</p> <pre><code>let point = MGLPointAnnotation() var i = lat var x = long //lat and long is served and then all the r,z points, then another lat, long...need to fix this and it may work. for (i,x) in zip(lat, long) { for aPlace in place { for aPass in pass { print(i) print(x) // String to double conversion, can I do this when I set the array as a string? let lati = NSString(string: i).doubleValue let longi = NSString(string: x).doubleValue point.coordinate = CLLocationCoordinate2D(latitude: lati, longitude: longi) point.title = aPlace print(aPlace) point.subtitle = aPass print(aPass) self.mapView.addAnnotation(point) }}} </code></pre> <p>This is running correctly now or at least reporting the correct values but the loop just keeps a loopin...</p>
2
Python ignoring if statement in while loop
<p>I recently finished learning Python on Codecademy, so I decided to make a rock, paper, scissors game for my first real program since it seemed fairly simple.</p> <p>When testing the program, Python seems to ignore the big if/elif statement that's nested within the while loop. The game generates a random integer (0 being rock, 1 being paper, 2 being scissors) and then prints it (for debugging). Then it prompts the player for input. After that, instead of evaluating the choice with the if statement, it just asks the player for another choice. It also prints a new random integer so I know it's just skipping over the if statement and going back to the beginning of the while loop.</p> <p>Below is the code for the game. If there's some kind of syntax error with the if statement I'm not seeing it. Does anyone know what's going on?</p> <pre><code>from random import randint def choose(): print '\nWill you play rock, paper, or scissors?' rawhumanchoice = raw_input('&gt; ') if rawhumanchoice == 'rock' or rawhumanchoice == 'r': humanchoice = 0 elif rawhumanchoice == 'paper' or rawhumanchoice == 'p': humanchoice = 1 elif rawhumanchoice == 'scissors' or rawhumanchoice == 's': humanchoice = 2 else: print '\nSorry, I didn\'t catch that.' choose() def gameinit(): roundsleft = 0 pcwins = 0 humanwins = 0 print 'How many rounds do you want to play?' roundsleft = raw_input('&gt; ') while roundsleft &gt; 0: pcchoice = randint(0,2) print pcchoice humanchoice = -1 choose() if humanchoice == 0: #This is what Python ignores if pcchoice == 0: print '\nRock and rock... it\'s a tie!' roundsleft -= 1 elif pcchoice == 1: print '\nPaper beats rock... PC wins.' roundsleft -= 1 pcwins += 1 elif pcchoice == 2: print '\nRock beats scissors... human wins!' roundsleft -= 1 humanwins += 1 elif humanchoice == 1: if pcchoice == 0: print '\nPaper beats rock... human wins!' roundsleft -= 1 humanwins += 1 elif pcchoice == 1: print '\nPaper and paper... it\'s a tie!' roundsleft -= 1 elif pcchoice == 2: print '\nScissors beat paper... PC wins.' roundsleft -= 1 pcwins += 1 elif humanchoice == 2: if pcchoice == 0: print '\nRock beats scissors... PC wins.' roundsleft -= 1 pcwins += 1 elif pcchoice == 1: print '\nPaper beats rock... human wins!' roundsleft -= 1 humanwins += 1 elif pcchoice == 2: print '\nScissors and scissors... it\'s a tie!' roundsleft -= 1 else: if humanwins &gt; pcwins: result = 'The human wins the match!' elif humanwins &lt; pcwins: result = 'The PC wins the match.' elif humanwins == pcwins: result = 'The match is a tie!' print '\nThe score is %s:%s... %s \n' % (humanwins,pcwins,result) gameinit() gameinit() </code></pre>
2
Select multiple columns inside table and retrieve value from jquery
<p>I have been looking hours and hours but I cannot find a solution to my problem.. I have literally searched everywhere on StackOverflow....</p> <p>Case: I got a HTML table with many different columns. I want to select multiple columns inside my table and make them retrieve values from jquery.</p> <p><a href="https://i.stack.imgur.com/HGw5p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HGw5p.png" alt="enter image description here"></a></p> <p>I do not want to achieve the result above, but I want to achieve result below:</p> <p><a href="https://i.stack.imgur.com/Pz9sG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pz9sG.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/0Ol0c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Ol0c.png" alt="enter image description here"></a></p>
2
how to design a form layout in ios 9 using Swift 3
<p>I am trying to design a form layout in ios 9 . I tried using the UITableViewController Static Cell.<a href="https://i.stack.imgur.com/swCsh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/swCsh.png" alt="this is the first image"></a></p> <p><a href="https://i.stack.imgur.com/LkSVI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LkSVI.png" alt="this the second image"></a></p> <p>this how i exactly wanted the Layout .</p> <p>I did this using static cell with multiple section in ui table view controller </p> <p>but As soon as I attach a class to this UITableViewController the view goes away on run, unable to figure out ,the code of UITableViewController class is the default code generated by the xcode.</p> <p>should i do any modification in the code of the class </p> <p>or should i proceed with different approach.</p> <p>please help.</p> <p>Code of the Class </p> <pre><code>import UIKit class BasicTableViewController: UITableViewController { @IBOutlet var basicTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int { // #warning Incomplete implementation, return the number of sections return 6 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { // #warning Incomplete implementation, return the number of rows return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { return cell } </code></pre>
2
UISlider thumb image with clear background shows track behind it
<p>How can I set a clear thumb background on <code>UISlider</code> so that the track is not visible behind the thumb?</p> <p>When I use <code>setThumbImage:forState:</code> and pass a partially transparent image, the slider's minimum track and maximum track image/colors are visible behind the thumb image:</p> <p><a href="https://i.stack.imgur.com/YEY1C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YEY1C.png" alt="track visible behind thumb" /></a></p> <p>I want it to look like in the iOS Camera application, where the &quot;transparent&quot; thumb image circle clips the track background color:</p> <p><a href="https://i.stack.imgur.com/PzMw4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PzMw4.png" alt="iOS camera slider" /></a></p>
2
Extract domain name from string using PHP
<p>How can I extract domain name from string like "AmericanSwan.com Indian Websites" ?</p> <p>I am tried many options but none of them provide domain name. </p>
2
(PHP) Can't write to file, can only read
<p>I am new to PHP and am trying to practice reading and writing files. I am able to read the file and echo it, but I am not able to write onto it. I have modified the permissions of both the target file and the PHP file to 777 (all permissions). It keeps echoing the file contents without changing them, and I'm not receiving any errors. </p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;?php //rewrite file $f = fopen("test.txt", "w"); fwrite($f, $_POST["info"]); //output file $str = fread($f, filesize("test.txt")); echo $str; fclose($f); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Thanks</p>
2
How to run Docker commands as non-root user in Docker in Docker?
<p>I have the following Dockerfile:</p> <pre><code>FROM docker RUN addgroup docker &amp;&amp; \ adduser -DH demo &amp;&amp; \ addgroup demo docker CMD /bin/sh </code></pre> <p>In this image, I'm creating a user called demo, which is then added to a group called docker. This is pretty much how full fledged environments are set up so that non-root/non-sudo users can issue docker commands. However, it doesn't work for me. What am I missing? I tried mapping the user and groups (via user, and group id's) to the user on the host system, but it still didn't work. I'm running this in Docker for Mac Beta (1.12.0-rc3-beta18).</p>
2
Check for empty String
<p>I want to know how it is possible to check for an empty string. </p> <p>I created a SQL statement which selects some datas in my database. </p> <pre><code>qry_pkv = "SELECT DISTINCT MANDT, PATH301 FROM NC301B " &amp; _ "WHERE EDIPROC like 'P30_'" &amp; _ "AND (LF301M &gt; 0) " &amp; _ "AND (PATH301 LIKE '%\pkv_dav\%') " &amp; _ "OR (PATH301 LIKE '%\PKV_DAV\%');" </code></pre> <p>The statement works great but I don't know how to check if there is any value inside of <code>qry_pkv</code>.</p> <pre><code>rs.open qry_pkv, cn, 3 Zeile = "Skriptausfuehrung wird gestartet." Call Trace (3, "I", Zeile) If qry_pkv &lt;&gt; Null Then rs.MoveFirst ReDim Preserve AusgabeDir_pkv(0) i = 0 Zeile = "PKV_DAV Verzeichnisse" 'Überschrift für LOG-Datei. Call Trace (3, "@", Zeile) 'Überschrift wird in LOG-Datei geschrieben. Do While Not rs.EOF 'Schleife für durchsuchen der Datenbank. ReDim Preserve AusgabeDir_pkv(i) ReDim Preserve MANDT_pkv(i) AusgabeDir_pkv(i) = rs("DIRIN") 'Ausgabeverzeichnis wird in Variable gespeichert und verarbeitet. MANDT_pkv(i) = rs("MANDT") Zeile = "Verzeichnis in Bearbeitung: " &amp; "MDT " &amp; MANDT_pkv(i) &amp; " PFAD " &amp; AusgabeDir_pkv(i) 'Status der Verarbeitung. Call Writelog (Zeile) 'Status wird in LOG-Datei geschrieben. ' call loeschen_gio(AusgabeDir_gio(i)) 'Funktion löschen wird aufgerufen um Verzeichnis zu leeren wenn älter n Tage. i = i+1 rs.MoveNext Loop Else Zeile = "PKV_DAV Verzeichnisse" 'Ergebnis wird in LOG-Datei geschrieben. Call Trace (3, "@", Zeile) 'Prozedur "WriteLog" wird aufgerufen Zeile = "Keine PKV_DAV Verzeichnisse vorhanden." 'Ergebnis wird in LOG-Datei geschrieben. Call Trace (3, "-", Zeile) 'Prozedur "WriteLog" wird aufgerufen End If </code></pre> <p>My plan was that the script is jumping to the <code>Else</code> statement in case of an empty <code>qry_pkv</code>.</p>
2
Inject a service on the console in angular2
<p>How do I inject a service in angular2 in the console?</p> <p>In angular1 just wrote: </p> <pre><code>angular.element(document).injector().get('MyService') </code></pre>
2
Extract fields and values from string in Python
<p>I'm trying to extract the field name and the value.From a string containing fields and values like the following one:</p> <pre><code>/location=(7966, 8580, 1) /station=NY /comment=Protein RadB n=1 Tax=M (SB / ATCC) RepID=A6USB2_METV </code></pre> <ul> <li><p>Each string can contain a different number of fields</p></li> <li><p>The field names will always be enclosed between '/' and '='</p></li> <li><p>The values can contain '/' and whitespace but not '='</p></li> </ul> <p>The expected result is something like:</p> <pre><code>['location','(7966, 8580, 1)','station','NY','comment','Protein RadB n=1 Tax=M (SB / ATCC) RepID=A6USB2_METV'] </code></pre> <p>So far I've been able to extract the field names using:</p> <pre><code>&gt;&gt; re.findall(r"\/([a-z]*?)\=",string) ['location', 'station', 'comment'] </code></pre> <p>And I've tried to use negative <code>?!</code> without success.</p> <p>Thanks in advance!</p>
2
How to add a hyperlink to a name in XSLT, with XML?
<p>I am new to XML &amp; XSL and am finding it difficult to understand the syntax. I have been working on this issue for the past 2 days, but am not finding a success. </p> <p>I am writing a XSl file to display a list of movies with its attributes in a table. I have to display the title of the movie as a link to its uri, IF the uri exists for that movie in the XML file . </p> <p>The code displays the titles, but not as a link. </p> <p>XML code:</p> <pre><code>&lt;movie&gt; &lt;title&gt;Die Hard&lt;/title&gt; &lt;uri&gt;http://www.imdb.com/title/tt0095016/?ref_=nv_sr_1&lt;/uri&gt; &lt;/movie&gt; &lt;movie&gt; &lt;title&gt;avatar&lt;/title&gt; &lt;/movie&gt; </code></pre> <p>The 2nd movie doesn't have a uri.</p> <p>XSLT code: </p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" &gt; &lt;xsl:output method="html" indent="yes"/&gt; &lt;xsl:template match="/"&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; table { width: 50%; background-color: lightyellow; padding: 2px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h2&gt;Movies after 2005&lt;/h2&gt; &lt;table border="1"&gt; &lt;tr&gt; &lt;th&gt;ID&lt;/th&gt; &lt;th&gt;Title&lt;/th&gt; &lt;th&gt;Director &lt;/th&gt; &lt;th&gt;Year&lt;/th&gt; &lt;th&gt;Genre&lt;/th&gt; &lt;/tr&gt; &lt;xsl:apply-templates select="movies/movie[year&gt;2005]"&gt; &lt;xsl:sort select="title"/&gt; &lt;/xsl:apply-templates&gt; &lt;tr&gt; &lt;xsl:if test="self::node()[uri]"&gt; &lt;!-- Test condition statement for uri tag--&gt; &lt;td&gt; &lt;a href="{uri}"&gt; &lt;xsl:value-of select="uri"/&gt; &lt;xsl:value-of select="title"/&gt; &lt;/a&gt; &lt;/td&gt; &lt;/xsl:if&gt; &lt;/tr&gt; &lt;tr &gt; &lt;td colspan="3"&gt; Number of movies &lt;/td&gt; &lt;td&gt; &lt;xsl:value-of select="count(//movie)"/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; &lt;xsl:template match="movie"&gt; &lt;tr&gt; &lt;td&gt; &lt;xsl:value-of select="id"/&gt; &lt;/td&gt; &lt;td&gt; &lt;xsl:value-of select="title"/&gt; &lt;/td&gt; &lt;td&gt; &lt;xsl:value-of select="Principaldirector"/&gt; &lt;/td&gt; &lt;td&gt; &lt;xsl:value-of select="year"/&gt; &lt;/td&gt; &lt;td&gt; &lt;xsl:for-each select="genre"&gt; &lt;xsl:if test="position() &gt; 1"&gt; &lt;xsl:text&gt;, &lt;/xsl:text&gt; &lt;/xsl:if&gt; &lt;xsl:value-of select="."/&gt; &lt;/xsl:for-each&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>I tried putting the if statement in the title template, but was getting 'invalid child' errors. </p>
2
Question mark in URL after closing alert box
<p>I have a dummy Bootstrap modal with a very simple JS alert meant to be triggered when the submit button is clicked. The code is live <a href="http://www.peppyburro.com/site2index.php" rel="noreferrer">here</a> and this is what it looks like:</p> <pre><code>&lt;div class="modal fade" id="contact" role="dialog" &gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;form class="form-horizontal" role="form" name="contact-form"&gt; &lt;div class="modal-header"&gt; &lt;h4&gt;test&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt;&lt;p&gt;This is body&lt;/p&gt;&lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="submit" id="submit" class="btn btn-primary btn-lg" onclick="alert('something');"&gt;Send&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p></p> <p>If you visit the site, you can trigger the modal by clicking on the contact link in the top navigation menu. The modal looks like this:</p> <p><a href="https://i.stack.imgur.com/cr91p.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cr91p.png" alt="enter image description here"></a></p> <p>As you can see, there's just one field and a submit button. The button's <em>onclick()</em> event is set to alert the word "something" on the screen. This works fine except that when you close the alert, the page refreshes with a "?" appended to the URL. How do I prevent this refresh and where does the question mark come from?</p>
2
Not able to import ComponentResolver and ViewContainerRef
<p>I am trying to load a child component dynamically based on some event from the parent component. I am getting some compilation errors in the Import statement and in the ViewChild statements. The following are the <a href="https://i.stack.imgur.com/2KjvQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2KjvQ.png" alt="errors"></a> </p> <p>Error# 1</p> <pre><code>import { Component, ComponentResolver, ViewContainerRef, ViewChild, } from 'angular2/core'; Error: Module "...node_modules/angular2/core" has no exported member ComponentResolver </code></pre> <p>Error# 2</p> <pre><code>@ViewChild("childContainer", { read: ViewContainerRef }) childContainer: ViewContainerRef; Error: Supplied parameters do not match any signature of call target </code></pre> <p>Error# 3</p> <pre><code>this._cr.resolveComponent(ExtractorDetails).then(cmpFactory =&gt; { let cmpRef = this.childContainer.createComponent(cmpFactory); cmpRef.instance.QueueID = this.queueID; }); Error: Property createComponent does not exist on type 'ViewContainerRef' </code></pre> <p>My package.json file is as follows:</p> <pre><code>{ "name": "ASP.NET", "version": "0.0.0", "dependencies": { "angular/http": "2.0.0-rc.1", "angular2": "2.0.0-beta.17", "bootstrap": "^3.3.5", "es6-promise": "^3.0.2", "es6-shim": "^0.33.3", "jquery": "^2.2.4", "reflect-metadata": "0.1.2", "rxjs": "5.0.0-beta.2", "systemjs": "0.19.22", "zone.js": "0.5.15" }, "devDependencies": { "gulp": "3.8.11", "gulp-concat": "2.5.2", "gulp-cssmin": "0.1.7", "gulp-uglify": "1.2.0", "rimraf": "2.2.8" } } </code></pre> <p>My Parent component looks like below import { Component, ComponentResolver, ViewContainerRef, ViewChild, } from 'angular2/core'; import { ExtractorDetails } from './ExtractorDetails'; ..</p> <pre><code>@Component({ selector: 'kendo-grid', templateUrl: './HTML/Admin/KendoGrid.html', providers: [Configuration, Constants], directives: [Grid] }) export class ExtractorGrid { options: any; rowObject: any; extractorDetails: any; public component: any; queueID: number; @ViewChild("childContainer", { read: ViewContainerRef }) childContainer: ViewContainerRef; constructor(private configSetttings: Configuration, private constants: Constants, private viewContainer: ViewContainerRef, private _cr: ComponentResolver) { this.setUpGridOptions(); } onChange(event) { this.rowObject = event.target; this._cr.resolveComponent(ExtractorDetails).then(cmpFactory =&gt; { let cmpRef = this.childContainer.createComponent(cmpFactory); cmpRef.instance.QueueID = this.queueID; }); } .... } </code></pre> <p>Can anyone point me which angular2 version I need to refer if I need to use ComponentResolver and ViewContainerRef?</p>
2
JPA correct way to handle detached entity state in case of exceptions/rollback
<p>I have this class and I tought three ways to handle detached entity state in case of persistence exceptions (which are handled elsewhere):</p> <pre><code>@ManagedBean @ViewScoped public class EntityBean implements Serializable { @EJB private PersistenceService service; private Document entity; public void update() { // HANDLING 1. ignore errors service.transact(em -&gt; { entity = em.merge(entity); // some other code that modifies [entity] properties: // entity.setCode(...); // entity.setResposible(...); // entity.setSecurityLevel(...); }); // an exception may be thrown on method return (rollback), // but [entity] has already been reassigned with a "dirty" one. //------------------------------------------------------------------ // HANDLING 2. ensure entity is untouched before flush is ok service.transact(em -&gt; { Document managed = em.merge(entity); // some other code that modifies [managed] properties: // managed.setCode(...); // managed.setResposible(...); // managed.setSecurityLevel(...); em.flush(); // an exception may be thrown here (rollback) // forcing method exit without [entity] being reassigned. entity = managed; }); // an exception may be thrown on method return (rollback), // but [entity] has already been reassigned with a "dirty" one. //------------------------------------------------------------------ // HANDLING 3. ensure entity is untouched before whole transaction is ok AtomicReference&lt;Document&gt; reference = new AtomicReference&lt;&gt;(); service.transact(em -&gt; { Document managed = em.merge(entity); // some other code that modifies [managed] properties: // managed.setCode(...); // managed.setResposible(...); // managed.setSecurityLevel(...); reference.set(managed); }); // an exception may be thrown on method return (rollback), // and [entity] is safe, it's not been reassigned yet. entity = reference.get(); } ... } </code></pre> <p><code>PersistenceService#transact(Consumer&lt;EntityManager&gt; consumer)</code> can throw unchecked exceptions.</p> <p>The goal is to maintain the state of the entity aligned with the state of the database, even in case of exceptions (prevent entity to become "dirty" after transaction fail).</p> <ul> <li><p>Method 1. is obviously naive and doesn't guarantee coherence.</p></li> <li><p>Method 2. asserts that nothing can go wrong after flushing.</p></li> <li><p>Method 3. prevents the new entity assigment if there's an exception in the whole transaction</p></li> </ul> <p><b>Questions:</b></p> <ol> <li>Is method 3. really safer than method 2.?</li> <li>Are there cases where an exception is thrown between <code>flush</code> [excluded] and <code>commit</code> [included]?</li> <li>Is there a standard way to handle this common problem?</li> </ol> <p>Thank you</p> <hr> <p>Note that I'm already able to rollback the transaction and close the EntityManager (<code>PersistenceService#transact</code> will do it gracefully), but I need to solve <em>database state and the business objects do get out of sync. Usually this is not a problem</em>. In my case this is <strong>the</strong> problem, because exceptions are usually generated by <code>BeanValidator</code> (those on JPA side, not on JSF side, for <em>computed</em> values that <em>depends</em> on user inputs) and I want the user to input correct values and try again, <strong>without losing the values he entered before</strong>.</p> <p>Side note: I'm using Hibernate 5.2.1</p> <hr> <p>this is the PersistenceService (CMT)</p> <pre><code>@Stateless @Local public class PersistenceService implements Serializable { @PersistenceContext private EntityManager em; @TransactionAttribute(TransactionAttributeType.REQUIRED) public void transact(Consumer&lt;EntityManager&gt; consumer) { consumer.accept(em); } } </code></pre> <hr> <h3>@DraganBozanovic</h3> <p>That's it! Great explanation for point 1. and 2.</p> <p>I'd just love you to elaborate a little more on point 3. and give me some advice on real-world use case.</p> <blockquote> <p>However, I would definitely not use AtomicReference or similar cumbersome constructs. Java EE, Spring and other frameworks and application containers support declaring transactional methods via annotations: Simply use the result returned from a transactional method.</p> </blockquote> <p>When you have to modify a single entity, the transactional method would just take the detached entity as parameter and return the updated entity, easy.</p> <pre><code>public Document updateDocument(Document doc) { Document managed = em.merge(doc); // managed.setXxx(...); // managed.setYyy(...); return managed; } </code></pre> <p>But when you need to modify more than one in a single transaction, the method can become a real pain:</p> <pre><code>public LinkTicketResult linkTicket(Node node, Ticket ticket) { LinkTicketResult result = new LinkTicketResult(); Node managedNode = em.merge(node); result.setNode(managedNode); // modify managedNode Ticket managedTicket = em.merge(ticket); result.setTicket(managedTicket); // modify managedTicket Remark managedRemark = createRemark(...); result.setRemark(managedemark); return result; } </code></pre> <p>In this case, my pain:</p> <ol> <li>I have to create a dedicated transactional method (maybe a dedicated <code>@EJB</code> too) </li> <li>That method will be called only once (will have just one caller) - is a "one-shot" non-reusable public method. Ugly.</li> <li>I have to create the dummy class <code>LinkTicketResult</code></li> <li>That class will be instantiated only once, in that method - is "one-shot"</li> <li>The method could have many parameters (or another dummy class <code>LinkTicketParameters</code>)</li> <li>JSF controller actions, in most cases, will just call a EJB method, extract updated entities from returned container and reassign them to local fields</li> <li>My code will be steadily polluted with "one-shotters", too many for my taste.</li> </ol> <p>Probably I'm not seeing something big that's just in front of me, I'll be very grateful if you can point me in the right direction.</p>
2
How to route in Angular 2 using Javascript
<p>I am following the <a href="https://angular.io/docs/ts/latest/tutorial/" rel="nofollow">Tour of Heroes tutorial</a>; currently at the <a href="https://angular.io/docs/ts/latest/tutorial/toh-pt5.html" rel="nofollow">Routing section</a>. I am using the 2.0.0-RC4 bundle.</p> <p>I have successfully refactored the <code>AppComponent</code> into a shell for the <code>HeroesComponent</code>. I have also added routes, loaded the necessary files, and done the necessary bootstrapping. </p> <p><strong>index.js</strong> — had to add the router beneath platform-browser because that's what I read in the <code>ng-router</code> source; <code>provideRouter</code> returns false otherwise</p> <pre><code>&lt;script src="node_modules/@angular/platform-browser/bundles/platform-browser.umd.js"&gt;&lt;/script&gt; &lt;script src="node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js"&gt;&lt;/script&gt; &lt;script src="node_modules/@angular/router/bundles/router.umd.js"&gt;&lt;/script&gt; </code></pre> <p><strong>main.js</strong></p> <pre><code>ng.platformBrowserDynamic.bootstrap(app.AppComponent, [ app.ROUTER_PROVIDERS ]); </code></pre> <p><strong>app.routes.js</strong></p> <pre><code>(function (app) { const routes = [ { path: 'heroes', component: app.HeroesComponent } ]; app.ROUTER_PROVIDERS = [ ng.router.provideRouter(routes) ]; })(window.app || (window.app = {})) </code></pre> <p><strong>app.component.js</strong></p> <pre><code>(function (app) { app.AppComponent = ng.core.Component({ selector: 'ig-app', directives: [ng.router.ROUTER_DIRECTIVES], providers: [app.HeroService], template:` &lt;h1&gt;{{title}}&lt;/h1&gt; &lt;a [routerLink]="['/heroes']"&gt;Heroes&lt;/a&gt; &lt;router-outlet&gt;&lt;/router-outlet&gt; ` }).Class({ constructor: function() { this.title = 'Tour of Heroes'; } }); })(window.app || (window.app = {})); </code></pre> <p>This loads my app with a Heroes link. But there is an error on the console</p> <blockquote> <p>EXCEPTION: Error: Uncaught (in promise): Error: Cannot match any routes: ''</p> </blockquote> <p>And then I append <code>/heroes</code> to the URL, the Heroes component does not load, and I get the following error in my console</p> <blockquote> <p>EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property 'of' of undefined </p> </blockquote> <p>Any pointers as to what I may be doing wrong?</p> <h3>EDIT</h3> <p>When I specify the route for <code>''</code> in my routes file like so...</p> <p><strong>app.routes.js</strong></p> <pre><code>(function (app) { const routes = [ { path: 'heroes', component: app.HeroesComponent }, { path: '', redirectTo: '/heroes', pathMatch: 'full' } ]; app.ROUTER_PROVIDERS = [ ng.router.provideRouter(routes) ]; })(window.app || (window.app = {})) </code></pre> <p>I get the second error I listed above on both pages. If I try setting it to the <code>app.AppComponent</code> I get errors which hint I should have a <code>redirectTo</code></p>
2
RecyclerView of RecyclerViews: Image Loading
<p>I try to implement a layout that contains a vertical <code>RecyclerView</code> that itself contains multiple horizontal <code>RecyclerViews</code> (imagine a news site, with multiple news sections, where each section contains multiple news stories that can be scrolled horizontally). </p> <p>The horizontal <code>RecyclerView</code> contains (among other things) an <code>ImageView</code>. I'm looking for the optimal strategy of loading an image from an URL into this <code>ImageView</code>. </p> <p>Firstly, my code. The Adapter for the outer RecyclerView: </p> <pre><code> @Override public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.content_preview_list_item, null); ItemRowHolder mh = new ItemRowHolder(v); mh.recycler_view_list.setAdapter(new SectionListDataAdapter(mContext, listener, new ArrayList&lt;ContentPreviewButtonItem&gt;())); mh.recycler_view_list.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false)); return mh; } @Override public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) { Log.d("RecyclerViewDataAdapter", "onBindViewHolder"); final String sectionName = dataList.get(i).getTitle(); ArrayList singleSectionItems = dataList.get(i).getItems(); itemRowHolder.itemTitle.setText(sectionName); ((SectionListDataAdapter)itemRowHolder.recycler_view_list.getAdapter()).setItemList(singleSectionItems); itemRowHolder.recycler_view_list.getAdapter().notifyDataSetChanged(); itemRowHolder.recycler_view_list.setHasFixedSize(true); } </code></pre> <p>And for the inner RecyclerView that contains the images: </p> <pre><code> @Override public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) { Log.d("SectionListDataAdapter", "onCreateViewHolder"); View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.content_preview_item, null); SingleItemRowHolder mh = new SingleItemRowHolder(v); return mh; } @Override public void onBindViewHolder(SingleItemRowHolder holder, int i) { Log.d("SectionListDataAdapter", "onBindViewHolder"); ContentPreviewButtonItem singleItem = itemsList.get(i); Uri imageUri = Uri.parse(singleItem.getImageUrl()); holder.itemImage.setImageURI(imageUri); //itemImage is a SimpleDraweeView } </code></pre> <p>While this code works great on mobile, there's a noticeable lag on tablet when multiple inner <code>RecyclerViews</code> and images are loaded at once. Right now I use Facebook's Fresco library to load the image into a <code>SimpleDraweeView</code>. I also tried Picasso but that yield an <code>OutOfMemoryException</code> when multiple images had to be loaded at once. I improved the performance by moving the adapter creation of the inner <code>RecyclerViews</code> into the <code>onCreateViewHolder</code> instead of the <code>onBindViewHolder</code>, but the lag is still noticeable. </p> <p>What's the best strategy or library to load images in this scenario. Thanks </p>
2
Width of UITableView content view does not match Container
<p>I have a TableVC embedded in a Container. The width of the Container running on an iPhone5 is 320. However the width of the ContentView in the TableView cell is 600. How can I make them match? (+/- padding). Am I missing a constraint? I have also tried setNeedsLayout() and layoutSubViews() in cellForRowAtIndexPath and in the custom cells subclass, but this doesn't seem to work either. </p> <p>In the picture below, I want the width of the darkgrey to match the light grey (+- padding)</p> <p>Any help much appreciated.....</p> <pre><code> override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("EventCell") as! CustomResultsTVCell // cell.setNeedsLayout() // cell.layoutSubviews() // cell.layoutIfNeeded() let barViewWidth = Float(cell.barView.frame.width) print("barview width is \(barViewWidth)") // prints 584 let contentViewWidth = cell.myContentView.frame.width print("contentView width is \(contentViewWidth)") // prints 600 </code></pre> <p>The CustomCell class is </p> <pre><code>import Foundation import UIKit class CustomResultsTVCell: UITableViewCell { @IBOutlet weak var myContentView: UIView! @IBOutlet weak var barView: UIView! override func awakeFromNib() { super.awakeFromNib() // super.layoutSubviews() // setNeedsLayout() // layoutSubviews() layoutIfNeeded() } </code></pre> <p><a href="https://i.stack.imgur.com/CGHI1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CGHI1.png" alt="xcode"></a></p>
2
How to open a csv file for reading purpose using mmap in python?
<p>I want to open csv file for reading purpose. But I'm facing some exceptions regarding to that.</p> <p>I'm using Python 2.7.</p> <p><strong>main.python-</strong> </p> <pre><code>if __name__ == "__main__": f = open('input.csv','r+b') m = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) reader = csv.DictReader(iter(m.readline, "")) for read in reader: num = read['time'] print num </code></pre> <p><strong>output-</strong></p> <pre><code>Traceback (most recent call last): File "/home/PycharmProjects/time_gap_Task/main.py", line 22, in &lt;module&gt; for read in reader: File "/usr/lib/python3.4/csv.py", line 109, in __next__ self.fieldnames File "/usr/lib/python3.4/csv.py", line 96, in fieldnames self._fieldnames = next(self.reader) _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) </code></pre> <p>How to resolve this error? and how to open csv file using mmap and csv in good manner so code is working perfect?</p>
2
How to get the inner text for a single node using HtmlAgilityPack
<p>My HTML looks like this:</p> <pre><code> &lt;div id="footer"&gt; &lt;div id="footertext"&gt; &lt;p&gt; Copyright &amp;copy; FUCHS Online Ltd, 2013. All Rights Reserved. &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I would like to obtain this text from the markup and store it as a string in my C# code: "Copyright &copy; FUCHS Online Ltd, 2013. All Rights ".</p> <p>This is what I have tried:</p> <pre><code> public string getvalue() { HtmlWeb web = new HtmlWeb(); HtmlAgilityPack.HtmlDocument doc = web.Load("www.fuchsonline.com"); var link = doc.DocumentNode.SelectNodes("//div[@id='footertext']"); return link.ToString(); } </code></pre> <p>This returns an object of type "HtmlAgilityPack.HtmlNodeCollection". How do I get just this text value?</p>
2
Using SES SDK to send email from python 2.7 on Lambda
<p>I am trying to build a lambda function using python 2.7 ( using boto3). I need to use AWS SDK to trigger the ses email. I will be sending to, email_subject, email_body as the arguments to this function. This function in turn should use the aws access key Id and aws secrete access key which would have permissions to trigger emails from the already verified domain and verified email id.</p> <p>I am looking for a way to specify aws credentials -</p> <pre><code>import boto3 client = boto3.client('ses') ..... &lt; how to mention credentials before calling send_email function ? &gt; response = client.send_email( ...... ) </code></pre>
2
ActiveMQ Artemis on wildfly with standalone ActiveMQ
<p>I am trying to use <code>MDB</code> to connect a wildfly 10 server using the inbuilt ActiveMQ Artemis to connect to my standalone ActiveMQ-Server running version 5.13.3. It seems like Artemis is not able to communicate with any of the supported ActiveMQ-Protocols.</p> <hr> <p><strong>ActiveMQ standalone broker</strong> has the following <code>transportConnectors</code>:</p> <pre><code>&lt;transportConnectors&gt; &lt;transportConnector name="auto" uri="auto://localhost:5671?protocolDetectionTimeOut=5000&amp;amp;wireFormat.maxFrameSize=104857600"/&gt; &lt;transportConnector name="http" uri="http://0.0.0.0:8180?maximumConnections=1000&amp;amp;wireFormat.maxFrameSize=104857600"/&gt; &lt;transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=1000&amp;amp;wireFormat.maxFrameSize=104857600" /&gt; &lt;transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&amp;amp;wireFormat.maxFrameSize=104857600"/&gt; &lt;transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=1000&amp;amp;wireFormat.maxFrameSize=104857600"/&gt; &lt;transportConnector name="mqtt" uri="mqtt://0.0.0.0:1883?maximumConnections=1000&amp;amp;wireFormat.maxFrameSize=104857600"/&gt; &lt;transportConnector name="ws" uri="ws://0.0.0.0:61614?maximumConnections=1000&amp;amp;wireFormat.maxFrameSize=104857600"/&gt; &lt;/transportConnectors&gt; </code></pre> <hr> <p><strong>Wildfly MessageBean</strong> has the following <code>Annotation</code>:</p> <pre><code>@MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"), @ActivationConfigProperty(propertyName="destination", "TestDestination"), @ActivationConfigProperty(propertyName="clientID", propertyValue = "test"), @ActivationConfigProperty(propertyName="connectionParameters", propertyValue = "host=127.0.0.1;port=5671"), @ActivationConfigProperty(propertyName="connectorClassName", propertyValue = "org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory"), @ActivationConfigProperty(propertyName="acknowledgeMode", propertyValue="Auto-acknowledge") }, mappedName = "TestDestination") public class MessageProcessingBean implements MessageListener { </code></pre> <hr> <p>Depending on the connector I choose to connect to, I receive different error-messages on the ActiveMQ-Server. </p> <p>Connecting to the <code>auto</code>-endpoint yields the following message:</p> <blockquote> <p>ERROR | Could not accept connection : java.lang.IllegalStateException: Could not detect the wire format</p> </blockquote> <p>No error on the wildfly-side.</p> <hr> <p>Connection to the <code>Openwire</code>-endpoint yields the following message:</p> <blockquote> <p>WARN | Transport Connection to: tcp://127.0.0.1:45000 failed: java.io.IOException: Unknown data type: 77</p> </blockquote> <p>this also yields an error on the wildfly-side:</p> <blockquote> <p>17:04:23,384 ERROR [org.apache.activemq.artemis.core.client] (Thread-16 (ActiveMQ-client-netty-threads-1716275972)) > AMQ214013: Failed to decode packet: java.lang.IllegalArgumentException: AMQ119032: Invalid type: 1 at org.apache.activemq.artemis.core.protocol.core.impl.PacketDecoder.decode(PacketDecoder.java:413) at org.apache.activemq.artemis.core.protocol.ClientPacketDecoder.decode(ClientPacketDecoder.java:60) at org.apache.activemq.artemis.core.protocol.ClientPacketDecoder.decode(ClientPacketDecoder.java:39) at org.apache.activemq.artemis.core.protocol.core.impl.RemotingConnectionImpl.bufferReceived(RemotingConnectionImpl.java:324) at org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryImpl$DelegatingBufferHandler.bufferReceived(ClientSessionFactoryImpl.java:1105) at org.apache.activemq.artemis.core.remoting.impl.netty.ActiveMQChannelHandler.channelRead(ActiveMQChannelHandler.java:68) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294) at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294) at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:846) at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131) at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511) at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468) at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354) at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:112) at java.lang.Thread.run(Thread.java:745)</p> </blockquote> <p>I could go so on and receive errormessages on all endpoints. The result in fact is that ActiveMQ-Artemis is sending in a data format which is not supported by ActiveMQ.</p> <p>Which steps have to be taken to connect ActiveMQ-Artemis with a standalone ActiveMQ-Server?</p>
2
RabbitMQ Pub/Sub - Subscriber is not able to receive message
<p>I am using sample code to implement Publish/Subscribe using "fanout" exchange type. But as in below code subscriber is not displaying 'Hello Word' message which is published.</p> <p><strong>Publisher.cs</strong></p> <pre><code> var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(exchange: "logs", type: "fanout"); var message = GetMessage(args); var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "logs", routingKey: "", basicProperties: null, body: body); Console.WriteLine(" [x] Sent {0}", message); } Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } private static string GetMessage(string[] args) { return ((args.Length &gt; 0) ? string.Join(" ", args) : "info: Hello World!"); } </code></pre> <p><strong>Subscriber.cs</strong></p> <pre><code> var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(exchange: "logs", type: "fanout"); var queueName = channel.QueueDeclare().QueueName; channel.QueueBind(queue: queueName, exchange: "logs", routingKey: ""); Console.WriteLine(" [*] Waiting for logs."); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) =&gt; { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] {0}", message); }; channel.BasicConsume(queue: queueName, noAck: true, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } </code></pre> <p><strong>Code Ref:</strong> <a href="https://www.rabbitmq.com/tutorials/tutorial-three-dotnet.html" rel="nofollow">https://www.rabbitmq.com/tutorials/tutorial-three-dotnet.html</a></p>
2
How to return raw php code?
<p>I have this code for example:</p> <pre><code>ob_start(); echo "hello there"; $output = ob_get_contents(); return $output; </code></pre> <p>When I run it, I get back:</p> <pre><code>hello there </code></pre> <p>But how can I get back </p> <pre><code>echo "hello there"; </code></pre> <p>Is there a way to do this easily?</p>
2
Exception in bundles on application startup
<p>I've got an ASP.NET MVC Application. All scripts are in bundle as usual. Here is my code from BundleConfig.cs</p> <pre><code> bundles.Add(new ScriptBundle("~/bundles/public-js").Include( "~/Scripts/angular.min.js", "~/Scripts/angular-route.min.js", "~/Scripts/angular-resource.min.js", "~/Scripts/angular-cookies.min.js", "~/Scripts/angular-sanitize.min.js", "~/Scripts/angular-ui/ui-bootstrap-tpls.min.js", "~/Scripts/bootstrap.min.js", "~/Scripts/string.utilities.js", "~/Scripts/public/google-charts-loader.js", "~/Scripts/biz/core/app-config.js", "~/Scripts/public/core/db-api.js", "~/Scripts/public/core/app.js", "~/Scripts/public/core/directives.js", "~/Scripts/public/core/controller-helpers.js", "~/Scripts/public/core/public-controller-helpers.js", "~/Scripts/public/core/services.js", "~/Scripts/public/core/list-controller.js", "~/Scripts/public/core/item-controller.js", "~/Scripts/n.utilities.biz.js" )); </code></pre> <p>According IntelliTrace i've got an exception that was caugth and handled by system. Here is exception description is </p> <pre><code>Exception thrown: 'System.Web.HttpException' in System.Web.dll (": Invalid file name for file monitoring: 'C:\IISTest\SuperMVC\Scripts\public'. Common reasons for failure include: - The filename is not a valid Win32 file name. - The filename is not an absolute path. - The filename contains wildcard characters. - The file specified is a directory. - Access denied.) </code></pre> <p>Application continue to works fine with no errors. Why this error appears on application startup?</p>
2
how to specify test specific setup and teardown in python unittest
<p>I want to create unittest test with two different set up and tearDown methon in same class with two different test.</p> <p>each test will use its specific setUp and tearDown method in python unittest framework.</p> <p>could anyone help me.</p> <pre><code> class processtestCase(unittest.TestCase): print "start the process test cases " def setUp1(self): unittest.TestCase.setUp(self) def test_test1(self): "test Functinality" def tearDown1(self): unittest.TestCase.tearDown(self) def setUp2(self): unittest.TestCase.setUp2(self) def test_test2(self): "test Functinality" def tearDown2(self): unittest.TestCase.tearDown2(self) ' if __name__ == '__main__': unittest.main() </code></pre>
2