title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
What is the purpose of ui-helper-hidden-accessible in an unordered list?
<p>Judging by the class name and the jQuery UI CSS source, the <code>ui-helper-hidden-accessible</code> class appears to be a way of hiding an element while still making it accessible.</p> <p>What I don't understand is what purpose it serves in this particular case. I tried searching SO and Google for reasons to use this class, but didn't find my answer.</p> <p>Here is an excerpt from the HTML generated by <a href="https://github.com/michael/multiselect">this UI Multiselect widget</a>:</p> <pre><code>&lt;div style="width: 176px;" class="ui-multiselect ui-helper-clearfix ui-widget"&gt; &lt;div style="width: 105px;" class="selected"&gt; &lt;div class="actions ui-widget-header ui-helper-clearfix"&gt; &lt;span class="count"&gt;0 items selected&lt;/span&gt;&lt;a href="#" class="remove-all"&gt;Remove all&lt;/a&gt; &lt;/div&gt; &lt;ul style="height: 270px;" class="selected connected-list ui-sortable"&gt; &lt;li class="ui-helper-hidden-accessible"&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div style="width: 69px;" class="available right-column"&gt; &lt;div class="actions ui-widget-header ui-helper-clearfix"&gt; &lt;input class="search empty ui-widget-content ui-corner-all" type="text"&gt;&lt;a href="#" class="add-all"&gt;Add all&lt;/a&gt; &lt;/div&gt; &lt;ul style="height: 279px;" class="available connected-list"&gt; &lt;li class="ui-helper-hidden-accessible"&gt;&lt;/li&gt; &lt;li style="display: block;" class="ui-state-default ui-element ui-draggable" title="3D Animation"&gt;&lt;span class="ui-helper-hidden"&gt;&lt;/span&gt;3D Animation&lt;a href="#" class="action"&gt;&lt;span class="ui-corner-all ui-icon ui-icon-plus"&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li style="display: block;" class="ui-state-default ui-element ui-draggable" title="Accreditation"&gt;&lt;span class="ui-helper-hidden"&gt;&lt;/span&gt;Accreditation&lt;a href="#" class="action"&gt;&lt;span class="ui-corner-all ui-icon ui-icon-plus"&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p></p> <p>I am using this widget and want to make some changes. While I'm at it, I'm cleaning up the code and removing unnecessary bits. I don't see the purpose of the following line of code.</p> <pre><code>&lt;li class="ui-helper-hidden-accessible"&gt;&lt;/li&gt; </code></pre> <p>I tried removing the <code>li</code> in question and don't see what difference it makes, but I can't claim to know a lot about accessibility.</p> <p>Note: I am new to GitHub and wasn't sure about the proper etiquette. But since the original author no longer maintains the widget, I didn't think it was appropriate to contact him directly.</p> <p>So does that line of code serve a particular purpose that I haven't considered or is it OK to remove it?</p> <p><strong>EDIT:</strong> I just had another thought. Maybe the purpose of the hidden <code>li</code> is to create valid HTML since an empty <code>ul</code> is not valid for HTML 4.01 nor XHTML. But doesn't that only matter to a validator?</p>
0
1,163
java.io.EOFException: End of input at line 1 column 1
<p>My <code>Retrofit</code> should recieve a List of Bookmarks, and everything worked while I was using <code>WAMP</code> server. When I changed server to external (nothing else changed, just ip address of the server and retrieving of everything else works) I have an error:</p> <pre><code> java.io.EOFException: End of input at line 1 column 1 at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:1407) at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:553) at com.google.gson.stream.JsonReader.peek(JsonReader.java:429) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:74) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61) at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37) at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25) at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:116) at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:211) at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:106) at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135) at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) </code></pre> <p><strong>My Retrofit code:</strong></p> <pre><code>public void init() { OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder(); HttpLoggingInterceptor debugger = new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY); okHttpClient .addInterceptor(debugger); Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constants.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient.build()) .build(); RequestInterface requestInterface = retrofit.create(RequestInterface.class); String email = pref.getString(Constants.EMAIL, ""); System.out.println(email); String id_group = pref.getString(Constants.ID_GROUP, ""); System.out.println(id_group); String nazwa = pref.getString(Constants.NAZWA, ""); Integer id_int_group = Integer.parseInt(id_group); Bookmark bookmark = new Bookmark(email, id_int_group, nazwa); ServerRequest request2 = new ServerRequest(); request2.setOperation(Constants.GET_MY_GROUPS); request2.setBookmark(bookmark); Call&lt;List&lt;Bookmark&gt;&gt; response2 = requestInterface.operation2(request2); response2.enqueue(new Callback&lt;List&lt;Bookmark&gt;&gt;() { @Override public void onResponse(Call&lt;List&lt;Bookmark&gt;&gt; call, retrofit2.Response&lt;List&lt;Bookmark&gt;&gt; response2) { listOfBookmarks = response2.body(); bookmarkToString(); simpleAdapter.notifyDataSetChanged(); // refresh listivew } @Override public void onFailure(Call&lt;List&lt;Bookmark&gt;&gt; call, Throwable t) { Log.d(Constants.TAG, "Nie zaladowano!", t); } }); } </code></pre> <p><strong>EDIT://</strong> PHP code:</p> <pre><code>&lt;?php class Bookmark { private $host = 'localhost'; private $user = 'nwbrn_root'; private $db = 'nwbrn_app'; private $pass = 'zxs@1208NMLK'; private $conn; public function __construct() { $this -&gt; conn = new PDO("mysql:host=".$this -&gt; host.";dbname=".$this -&gt; db, $this -&gt; user, $this -&gt; pass); } public function checkBookmarkExist($email, $id_group){ try { $query = $this-&gt;conn-&gt;prepare("SELECT COUNT(*) from bookmarks WHERE email =:email AND id_group =:id_group"); // $query = $this -&gt; conn -&gt; prepare($sql); $query-&gt;bindParam(':email', $email, PDO::PARAM_STR); $query-&gt;bindParam(':id_group', $id_group, PDO::PARAM_INT); $query-&gt;execute(array('email' =&gt; $email, 'id_group' =&gt; $id_group)); $row_count = $query -&gt; fetchColumn(); if ( $row_count&gt;0 ) { $response["result"] = "success"; $response["message"] = "Your favourite!"; return json_encode($response); } else { $response["result"] = "failure"; $response["message"] = "Not in your favourite!"; return json_encode($response); } } catch (PDOException $e) { die ($e-&gt;getMessage()); } } public function fullStarSelected($email, $id_group, $nazwa){ try { $query = $this-&gt;conn-&gt;prepare("DELETE from bookmarks WHERE email =:email AND id_group =:id_group AND nazwa =:nazwa"); // mysqli_set_charset($this-&gt;conn, "utf8"); $query-&gt;bindParam(':email', $email, PDO::PARAM_STR); $query-&gt;bindParam(':id_group', $id_group, PDO::PARAM_INT); $query-&gt;bindParam(':nazwa', $nazwa, PDO::PARAM_STR); $query-&gt;execute(); if ( $query -&gt;rowCount() &gt; 0 ) { $response["result"] = "failure"; $response["message"] = "Row not deleted!"; return json_encode($response); } else { $response["result"] = "success"; $response["message"] = "Row deleted successfully!"; return json_encode($response); } } catch (PDOException $e) { die ($e-&gt;getMessage()); } } public function blankStarSelected($email, $id_group, $nazwa){ try { $query = $this-&gt;conn-&gt;prepare("INSERT INTO bookmarks (email, id_group, nazwa) VALUES (:email, :id_group, :nazwa)"); // mysqli_set_charset($this-&gt;conn, "utf8"); $query-&gt;bindParam(':email', $email, PDO::PARAM_STR); $query-&gt;bindParam(':id_group', $id_group, PDO::PARAM_INT); $query-&gt;bindParam(':nazwa', $nazwa, PDO::PARAM_STR); $query-&gt;execute(); if (!$query) { printf("Error: %s\n", mysqli_error($this-&gt;conn)); exit(); } $result = array(); // $query1 = $this-&gt;conn-&gt;prepare("SELECT COUNT(*) from bookmarks WHERE email =:email AND id_group =:id_group LIMIT 1"); if ( $query-&gt;rowCount() &gt; 0 ) { $response["result"] = "success"; $response["message"] = "Row added successfully!"; return json_encode($response); } else { $response["result"] = "failure"; $response["message"] = "Row not added!"; return json_encode($response); } } catch (PDOException $e) { die ($e-&gt;getMessage()); } } public function getMyGroups($email, $id_group){ try { $con = mysqli_connect($this-&gt;host,$this-&gt;user,$this-&gt;pass,$this-&gt;db); $sql = "SELECT * FROM bookmarks WHERE email = '$email'"; $res = mysqli_query($con,$sql); $result = array(); if (!$res) { printf("Error: %s\n", mysqli_error($con)); exit(); } while($row = mysqli_fetch_array($res)){ $temp = array(); $temp['id_group']=$row['id_group']; $temp['email']=$row['email']; $temp['nazwa']=$row['nazwa']; array_push($result,$temp); } echo json_encode($result); } catch (PDOException $e) { die ($e-&gt;getMessage()); } } } </code></pre>
0
3,692
com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect
<p>I assumed this question was asked several times but I had to reask it again. Because solutions provided for this question did not give me an exact answer to get rid of this bloody error.</p> <p>I use <code>mongo-java-driver-2.12.4</code> and <code>mongo.jar</code> when I try to insert document to db I get following error. Any help is appreciated. </p> <p>Error :</p> <pre><code>Exception in thread "main" com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=127.0.0.1:27000, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=127.0.0.1:27001, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=127.0.0.1:27002, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}] at com.mongodb.BaseCluster.getDescription(BaseCluster.java:128) </code></pre> <p>Code : </p> <pre><code> public class MongoDbConnectDatabase { public static void main(String[] args) { // To connect to mongodb server try { List&lt;ServerAddress&gt; lstServer = new ArrayList&lt;ServerAddress&gt;(); lstServer.add(new ServerAddress("127.0.0.1", 27000)); lstServer.add(new ServerAddress("127.0.0.1", 27002)); lstServer.add(new ServerAddress("127.0.0.1", 27001)); MongoClient mongoClient = new MongoClient(lstServer); // Now connect to your database DB db = mongoClient.getDB("test"); System.out.println("connect to database successfully"); DBCollection coll = db.createCollection("mycol", null); System.out.println("Collection created successfully"); DBCollection colReceived= db.getCollection("mycol"); System.out.println("Collection mycol selected successfully"); BasicDBObject doc = new BasicDBObject("title", "MongoDB"). append("description", "database"). append("likes", 100). append("url", "http://www.tutorialspoint.com/mongodb/"). append("by", "tutorials point"); colReceived.insert(doc); System.out.println("Document inserted successfully"); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </code></pre>
0
1,069
SQLite Performance Benchmark -- why is :memory: so slow...only 1.5X as fast as disk?
<h2>Why is :memory: in sqlite so slow?</h2> <p>I've been trying to see if there are any performance improvements gained by using in-memory sqlite vs. disk based sqlite. Basically I'd like to trade startup time and memory to get extremely rapid queries which do <em>not</em> hit disk during the course of the application. </p> <p>However, the following benchmark gives me only a factor of 1.5X in improved speed. Here, I'm generating 1M rows of random data and loading it into both a disk and memory based version of the same table. I then run random queries on both dbs, returning sets of size approx 300k. I expected the memory based version to be considerably faster, but as mentioned I'm only getting 1.5X speedups. </p> <p>I experimented with several other sizes of dbs and query sets; the advantage of :memory: <em>does</em> seem to go up as the number of rows in the db increases. I'm not sure why the advantage is so small, though I had a few hypotheses: </p> <ul> <li>the table used isn't big enough (in rows) to make :memory: a huge winner</li> <li>more joins/tables would make the :memory: advantage more apparent</li> <li>there is some kind of caching going on at the connection or OS level such that the previous results are accessible somehow, corrupting the benchmark</li> <li>there is some kind of hidden disk access going on that I'm not seeing (I haven't tried lsof yet, but I did turn off the PRAGMAs for journaling)</li> </ul> <p>Am I doing something wrong here? Any thoughts on why :memory: isn't producing nearly instant lookups? Here's the benchmark: </p> <pre><code>==&gt; sqlite_memory_vs_disk_benchmark.py &lt;== #!/usr/bin/env python """Attempt to see whether :memory: offers significant performance benefits. """ import os import time import sqlite3 import numpy as np def load_mat(conn,mat): c = conn.cursor() #Try to avoid hitting disk, trading safety for speed. #http://stackoverflow.com/questions/304393 c.execute('PRAGMA temp_store=MEMORY;') c.execute('PRAGMA journal_mode=MEMORY;') # Make a demo table c.execute('create table if not exists demo (id1 int, id2 int, val real);') c.execute('create index id1_index on demo (id1);') c.execute('create index id2_index on demo (id2);') for row in mat: c.execute('insert into demo values(?,?,?);', (row[0],row[1],row[2])) conn.commit() def querytime(conn,query): start = time.time() foo = conn.execute(query).fetchall() diff = time.time() - start return diff #1) Build some fake data with 3 columns: int, int, float nn = 1000000 #numrows cmax = 700 #num uniques in 1st col gmax = 5000 #num uniques in 2nd col mat = np.zeros((nn,3),dtype='object') mat[:,0] = np.random.randint(0,cmax,nn) mat[:,1] = np.random.randint(0,gmax,nn) mat[:,2] = np.random.uniform(0,1,nn) #2) Load it into both dbs &amp; build indices try: os.unlink('foo.sqlite') except OSError: pass conn_mem = sqlite3.connect(":memory:") conn_disk = sqlite3.connect('foo.sqlite') load_mat(conn_mem,mat) load_mat(conn_disk,mat) del mat #3) Execute a series of random queries and see how long it takes each of these numqs = 10 numqrows = 300000 #max number of ids of each kind results = np.zeros((numqs,3)) for qq in range(numqs): qsize = np.random.randint(1,numqrows,1) id1a = np.sort(np.random.permutation(np.arange(cmax))[0:qsize]) #ensure uniqueness of ids queried id2a = np.sort(np.random.permutation(np.arange(gmax))[0:qsize]) id1s = ','.join([str(xx) for xx in id1a]) id2s = ','.join([str(xx) for xx in id2a]) query = 'select * from demo where id1 in (%s) AND id2 in (%s);' % (id1s,id2s) results[qq,0] = round(querytime(conn_disk,query),4) results[qq,1] = round(querytime(conn_mem,query),4) results[qq,2] = int(qsize) #4) Now look at the results print " disk | memory | qsize" print "-----------------------" for row in results: print "%.4f | %.4f | %d" % (row[0],row[1],row[2]) </code></pre> <p>Here's the results. Note that disk takes about 1.5X as long as memory for a fairly wide range of query sizes. </p> <pre><code>[ramanujan:~]$python -OO sqlite_memory_vs_disk_clean.py disk | memory | qsize ----------------------- 9.0332 | 6.8100 | 12630 9.0905 | 6.6953 | 5894 9.0078 | 6.8384 | 17798 9.1179 | 6.7673 | 60850 9.0629 | 6.8355 | 94854 8.9688 | 6.8093 | 17940 9.0785 | 6.6993 | 58003 9.0309 | 6.8257 | 85663 9.1423 | 6.7411 | 66047 9.1814 | 6.9794 | 11345 </code></pre> <p>Shouldn't RAM be almost instant relative to disk? What's going wrong here? </p> <h2>Edit</h2> <p>Some good suggestions here. </p> <p>I guess the main takehome point for me is that **there's probably no way to make :memory: <em>absolutely faster</em>, but there is a way to make disk access <em>relatively slower.</em> ** </p> <p>In other words, the benchmark is adequately measuring the realistic performance of memory, but not the realistic performance of disk (e.g. because the cache_size pragma is too big or because I'm not doing writes). I'll mess around with those parameters and post my findings when I get a chance. </p> <p>That said, if there is anyone who thinks I can squeeze some more speed out of the in-memory db (other than by jacking up the cache_size and default_cache_size, which I will do), I'm all ears...</p>
0
1,860
Access UIView width at runtime
<p>In Swift, how do I get the width (or height) at runtime, of a UIView that's created programmatically using auto layout constraints?</p> <p>I've tried <code>view1.frame.size.width</code> and <code>view1.frame.width</code>, but both return <code>0</code>.</p> <p>I've been following an auto layout tutorial by <a href="http://makeapppie.com/2014/07/26/the-swift-swift-tutorial-how-to-use-uiviews-with-auto-layout-programmatically/" rel="noreferrer">MakeAppPie</a> and added <code>view1.layer.cornerRadius = view1.bounds.width/2</code> as below, but this had no effect, so I did a po on <code>view1.bounds.width</code> and got <code>0</code>:</p> <pre><code>class ViewController: UIViewController { func makeLayout() { //Make a view let view1 = UIView() view1.setTranslatesAutoresizingMaskIntoConstraints(false) view1.backgroundColor = UIColor.redColor() //Make a second view let view2 = UIView() view2.setTranslatesAutoresizingMaskIntoConstraints(false) view2.backgroundColor = UIColor(red: 0.75, green: 0.75, blue: 0.1, alpha: 1.0) //Add the views view.addSubview(view1) view.addSubview(view2) //--------------- constraints //make dictionary for views let viewsDictionary = ["view1":view1,"view2":view2] //sizing constraints //view1 let view1_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:[view1(&gt;=50)]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary) let view1_constraint_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:[view1(50)]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary) view1.addConstraints(view1_constraint_H) view1.addConstraints(view1_constraint_V) //view2 let view2_constraint_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:[view2(50)]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary) let view2_constraint_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:[view2(&gt;=40)]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary) view2.addConstraints(view2_constraint_H) view2.addConstraints(view2_constraint_V) //position constraints //views let view_constraint_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-100-[view2]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary) let view_constraint_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-136-[view1]-100-[view2]-100-|", options: NSLayoutFormatOptions.AlignAllTrailing, metrics: nil, views: viewsDictionary) view.addConstraints(view_constraint_H) view.addConstraints(view_constraint_V) view1.layer.cornerRadius = view1.bounds.width/2 } override func viewDidLoad() { super.viewDidLoad() func supportedInterfaceOrientations() -&gt; Int { return Int(UIInterfaceOrientationMask.All.rawValue) } // Do any additional setup after loading the view, typically from a nib. view.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 1, alpha: 1.0) makeLayout() } } </code></pre>
0
1,183
Angular App running on nginx and behind an additional nginx reverse proxy
<p>I'm currently trying to create a reverse proxy for two Angular apps. I want the apps to be both accessible through the 443 port of the docker host with SSL enabled (like <a href="https://192.168.x.x/app1" rel="noreferrer">https://192.168.x.x/app1</a> and <a href="https://192.168.x.x/app2" rel="noreferrer">https://192.168.x.x/app2</a>), so that the users don't have to type in the port numbers for each app.</p> <p>My setting is, that every part of the application runs within its own Docker container: - Container 1: Angular App 1 (Port 80 exposed to host on port 8080) - Container 2: Angular App 2 (Port 80 exposed to host on port Port 8081) - Container 3: Reverse Proxy (Port 443 exposed)</p> <p>Both Angular apps and the reverse proxy are running on nginx. The apps are build like that: <code>ng build --prod --base-href /app1/ --deploy-url /app1/</code></p> <p>The nginx setting of the apps is like that:</p> <pre><code>server { listen 80; sendfile on; default_type application/octet-stream; gzip on; gzip_http_version 1.1; gzip_disable "MSIE [1-6]\."; gzip_min_length 256; gzip_vary on; gzip_proxied expired no-cache no-store private auth; gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript; gzip_comp_level 9; root /usr/share/nginx/html; index index.html index.htm; location / { try_files $uri $uri/ /index.html =404; } } </code></pre> <p>The nginx configuration of the reverse proxy is like that:</p> <pre><code>server { listen 443; ssl on; ssl_certificate /etc/nginx/certs/domaincertificate.cer; ssl_certificate_key /etc/nginx/certs/domain.key; location /app1/ { proxy_pass http://192.168.x.x:8080; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_http_version 1.1; proxy_cache_bypass $http_upgrade; } location /app2/ { proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_http_version 1.1; proxy_cache_bypass $http_upgrade; proxy_pass http://192.168.x.x:8081; } } </code></pre> <p>If I try to open the app on the url '<a href="https://192.168.x.x/app1" rel="noreferrer">https://192.168.x.x/app1</a>', the app is reached, but I get error messages for all static files 'Uncaught SyntaxError: Unexpected token &lt;': <a href="https://i.stack.imgur.com/b3ay4.jpg" rel="noreferrer">Errormessages from chrome</a></p> <p>It seems, that instead of the static js and css files, the index.html of the app is returned. I believe that this is a problem of the nginx config of the apps themselves. </p> <p>I have spent quite a time trying to figure out how to solve that problem, but no luck yet. I hope that someone here can help me with that.</p>
0
1,106
Microsoft Graph 401 Unauthorized with access token
<p>Unable to get data from the the Microsoft Graph API.</p> <pre><code>private String getUserNamesFromGraph() throws Exception { String bearerToken = "Bearer "+getAccessToken(); String url = "https://graph.microsoft.com/v1.0/users"; String returnData = null; try { URL apiURL = new URL(url); URLConnection con = apiURL.openConnection(); con.setRequestProperty("Authorization", bearerToken); con.setRequestProperty("Content-Type", "application/json"); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); returnData = response.toString(); System.out.println(returnData); } catch(Exception e) { System.out.println(e); } return returnData; } private String getAccessToken() throws Exception { String url = "https://login.microsoftonline.com/common/oauth2/v2.0/token"; URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); // header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", "eTarget API"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "client_id=*** APPLICATION ID FROM APPLICATION REGISTRATION PORTAL ***&amp;scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&amp;client_secret=*** APPLICATION SECRET FROM APPLICATION REGISTRATION PORTAL ***&amp;grant_type=client_credentials"; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result String returnData = response.toString(); System.out.println(returnData); Map jsonTokenData = new Gson().fromJson(returnData, Map.class); String accessToken = (String)jsonTokenData.get("access_token"); //System.out.println(accessToken); return accessToken; } </code></pre> <ul> <li>The application is <a href="https://apps.dev.microsoft.com" rel="noreferrer">registered</a></li> <li>I have a method <code>getAccessToken()</code> that successfully returns an access token</li> <li>The method <code>getUserNamesFromGraph()</code> however returns a 401 Unauthorized instead of the expected data.</li> </ul> <p>I've gone through the documentation countless times, trying different variations and endpoints but to no avail. Any ideas appreciated.</p>
0
1,229
Raspberry Pi UART serial wont work
<p>I am trying to send/receive data over serial connection (GPIO UART pins) between a Raspberry Pi (B model, raspian wheezy) and an STM32F4 board.</p> <p>To setup the serial port, i followed all the stepts found in several tutorials like: <a href="http://elinux.org/RPi_Serial_Connection#Preventing_Linux_using_the_serial_port" rel="noreferrer">http://elinux.org/RPi_Serial_Connection#Preventing_Linux_using_the_serial_port</a></p> <p>When failing to get a connection to the STM32F4 board, i read that you can test the serial port locally on the pi if you just connect the TX, RX pins off the pi to eachother and it should just repeat the entered data in minicom.</p> <p>sadly this does not work either.</p> <p>The settings for ttyAMA0 in files 'cmdline' and 'inittab' are ok. (like described in many tutorials)</p> <p>and allso tried auto configuration scrips from <a href="https://github.com/lurch/rpi-serial-console" rel="noreferrer">https://github.com/lurch/rpi-serial-console</a></p> <p>Connecting RX to the TX pin on rpi directly does not give any output in minicom. I allso tried with a python script that repeats given input. Nothing seems to work, i'm kind of lost here.</p> <p>Minicom start command should be correct(tried with different baud rates):</p> <pre><code>root@raspberrypi:/home/jef# minicom -b 9600 -o -D /dev/ttyAMA0 OPTIONS: I18n Compiled on Apr 28 2012, 19:24:31. Port /dev/ttyAMA0 </code></pre> <p>On the bottom of minicom it allways shows status offline:</p> <pre><code>CTRL-A Z for help | 9600 8N1 | NOR | Minicom 2.6.1 | VT102 | Offline </code></pre> <p>When checking available serial ports with python nothinig is swown:</p> <pre><code>python -m serial.tools.list_ports no ports found </code></pre> <p>User is in dailout group so that should not be the issue(tried as root and non root):</p> <pre><code>root@raspberrypi:/home/jef# id uid=0(root) gid=0(root) groups=0(root),20(dialout),1001(indiecity) </code></pre> <p>Verification that serial port is not used by getty anymore:</p> <pre><code>root@raspberrypi:/home/jef# ps aux | grep getty root 2809 0.0 0.1 3740 804 tty1 Ss+ 10:36 0:00 /sbin/getty --noclear 38400 tty1 root 2810 0.0 0.1 3740 804 tty2 Ss+ 10:36 0:00 /sbin/getty 38400 tty2 root 2811 0.0 0.1 3740 804 tty3 Ss+ 10:36 0:00 /sbin/getty 38400 tty3 root 2812 0.0 0.1 3740 804 tty4 Ss+ 10:36 0:00 /sbin/getty 38400 tty4 root 2813 0.0 0.1 3740 804 tty5 Ss+ 10:36 0:00 /sbin/getty 38400 tty5 root 2814 0.0 0.1 3740 804 tty6 Ss+ 10:36 0:00 /sbin/getty 38400 tty6 root 3129 0.0 0.1 2012 624 pts/0 S+ 11:57 0:00 grep getty </code></pre> <p>i checked for other apps using ttyAMA0, allso nothing:</p> <pre><code>root@raspberrypi:/home/jef# ps aux | grep ttyAMA0 root 3125 0.0 0.1 2012 628 pts/0 S+ 11:56 0:00 grep ttyAMA0 </code></pre> <p>users has correct rights to access serial port:</p> <pre><code>root@raspberrypi:/home/jef# ls -l /dev/ttyAMA0 crw-rw---T 1 root dialout 204, 64 Dec 25 11:53 /dev/ttyAMA0 </code></pre> <p>Is there anything i missed? I read about 20 different tutorials and blogs on how to setup the serial port and i can't fond what causes this. Could you give me some advice i could look for please.</p>
0
1,344
Android Studio getting "Must implement OnFragmentInteractionListener"
<p>I'm getting a throw that says "Must implement OnFragmentInteractionListener, and I already have it...</p> <p>I've looked at every question asked here, and no one helped me.</p> <p>Could anyone please help me?</p> <p>ERROR:</p> <pre><code>FATAL EXCEPTION: main Process: com.example.android.navigationdrawer, PID: 5916 java.lang.RuntimeException: com.example.android.navigationdrawer.MainActivity@3aefae64 must implement OnFragmentInteractionListener at com.example.android.navigationdrawer.FragmentCamera.onAttach(FragmentCamera.java:83) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1019) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613) at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5930) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) </code></pre> <p>MAINACTIVITY (extending to OnFragmentInteractionListener)</p> <pre><code>package com.example.android.navigationdrawer; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, FragmentCamera.OnFragmentInteractionListener { </code></pre> <p>MAINACTIVITY (FragmentCamera @Override)</p> <pre><code>@Override public void onFragmentInteraction(Uri uri) { } </code></pre> <p>MAINACTIVITY (ONCREATE)</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } </code></pre> <p>MAINACTIVITY (FRAGMENT TRANSACTION)</p> <pre><code> boolean FragmentTransaction = false; Fragment fragment = null; //Camera if (id == R.id.nav_camera) { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); startActivity(intent); ImageView mImageView = (ImageView) findViewById(R.id.Galley1); //Galley } else if (id == R.id.nav_gallery) { fragment = new FragmentCamera(); FragmentTransaction = true; } </code></pre> <p>...</p> <pre><code> if(FragmentTransaction) { getSupportFragmentManager().beginTransaction() .replace(R.id.drawer_layout, fragment) .commit(); item.setChecked(true); getSupportActionBar().setTitle(item.getTitle()); } </code></pre> <p>FRAGMENTCAMERA</p> <pre><code>package com.example.android.navigationdrawer; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link FragmentCamera.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link FragmentCamera#newInstance} factory method to * create an instance of this fragment. */ public class FragmentCamera extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public FragmentCamera() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment FragmentCamera. */ // TODO: Rename and change types and number of parameters public static FragmentCamera newInstance(String param1, String param2) { FragmentCamera fragment = new FragmentCamera(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_camera, container, false); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * &lt;p/&gt; * See the Android Training lesson &lt;a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * &gt;Communicating with Other Fragments&lt;/a&gt; for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } } </code></pre> <p>If you need some more code, comment and I will add it!</p>
0
3,205
Unable to Start Tomcat 7.0 in Eclipse Indigo
<p>I've to start working on a web-app project for which I've Eclipse Indigo and Tomcat 7.0 installed. The environment also has JRE 7, Android SDK in it. But whenever I start the server, it gets timed out!</p> <p>Moreover, I'm able to start the server outside Eclipse and sucessfully execute a web app in the browser. But to debug, I would rather have it in Eclipse.</p> <p>The error message is:</p> <pre><code>Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor. </code></pre> <p>In the console I get:</p> <pre><code> Mar 14, 2012 11:51:18 PM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\program files\Java\jre7\bin;C:\WINNT\Sun\Java\bin;C:\WINNT\system32;C:\WINNT;C:/Program Files/Java/jre7/bin/client;C:/Program Files/Java/jre7/bin;C:/Program Files/Java/jre7/lib/i386;C:\oracle\product\11.1.0\BIN\;C:\WINNT\system32;C:\WINNT;C:\WINNT\System32\Wbem;C:\Program Files\Executive Software\Diskeeper\;C:\Program Files\Pointsec\Pointsec Media Encryption\Program\;C:\Program Files\Windows Imaging\;C:\oracle\product\11.1.0\BIN;C:\Program Files\Reflection\;C:\eclipse;;. Mar 14, 2012 11:51:18 PM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:AUDI_ASSIST_v2.0_WS_REDESIGN_Interceptor' did not find a matching property. Mar 14, 2012 11:51:18 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["http-bio-9080"] Mar 14, 2012 11:51:18 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["ajp-bio-9009"] Mar 14, 2012 11:51:18 PM org.apache.catalina.startup.Catalina load INFO: Initialization processed in 504 ms Mar 14, 2012 11:51:18 PM org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina Mar 14, 2012 11:51:18 PM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/7.0.26 Mar 14, 2012 11:51:18 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [109] milliseconds. Mar 14, 2012 11:51:18 PM org.apache.catalina.loader.WebappClassLoader validateJarFile INFO: validateJarFile(D:\documents and settings\fahmf\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\AUDI_ASSIST_v2.0_WS_REDESIGN_Interceptor\WEB-INF\lib\com.ibm.ws.webservices.thinclient_7.0.0.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class Mar 14, 2012 11:51:20 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-bio-9080"] Mar 14, 2012 11:51:20 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-bio-9009"] Mar 14, 2012 11:51:20 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 1697 ms </code></pre> <p>I have tried the solutions proposed in other questions on this forum like increasing the time out period,changing the port numbers, uninstalling &amp; reinstalling Tomcat, changing the 'publisiing' option for the server but nothing seems to work.</p> <p>Any help would be sincerely appreciated. Thanks in advance...</p>
0
1,133
Access C++ function from QML
<p>I'm trying to make a little program with Qt. I have a <code>main.cpp</code> with the following code:</p> <pre><code>#include &lt;QtGui/QApplication&gt; #include "qmlapplicationviewer.h" Q_DECL_EXPORT int main(int argc, char *argv[]) { QScopedPointer&lt;QApplication&gt; app(createApplication(argc, argv)); QmlApplicationViewer viewer; viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto); viewer.setMainQmlFile(QLatin1String("qml/tw_looptijden_berekenen/main.qml")); viewer.showExpanded(); return app-&gt;exec(); } int reken_tijden_uit(){ return true; } </code></pre> <p>and I have a <code>.qml</code> file:</p> <pre><code>import QtQuick 1.1 Rectangle { width: 360 height: 360 Text { text: qsTr("Hello World") anchors.centerIn: parent } MouseArea { anchors.fill: parent onClicked: { Qt.quit(); } } } </code></pre> <p>Now, when I click on the <code>MouseArea</code>, the program quits. What I want is that it calls the function <code>reken_tijden_uit</code> in the <code>main.cpp</code> file.</p> <p>I've googled a lot, and searched on this site to. I've found a couple of answers, but I didn't get one working.</p> <p>So what code do I put where so I can call the function <code>reken_tijden_uit</code> in C++?</p> <p>Thanks in advance.</p> <hr> <p>The header file looks like this:</p> <pre><code>#ifndef EIGEN_FUNCTION_HEADER_H #define EIGEN_FUNCTION_HEADER_H class MyObject : public QObject{ Q_OBJECT public: explicit MyObject (QObject* parent = 0) : QObject(parent) {} Q_INVOKABLE int reken_tijden_uit(){ return 1; } }; #endif // EIGEN_FUNCTION_HEADER_H </code></pre> <p><code>main.cpp</code>:</p> <pre><code>#include &lt;QtGui/QApplication&gt; #include "qmlapplicationviewer.h" #include "eigen_function_header.h" QScopedPointer&lt;QApplication&gt; app(createApplication(argc, argv)); qmlRegisterType&lt;MyObject&gt;("com.myself", 1, 0, "MyObject"); Q_DECL_EXPORT int main(int argc, char *argv[]) { QScopedPointer&lt;QApplication&gt; app(createApplication(argc, argv)); QmlApplicationViewer viewer; viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto); viewer.setMainQmlFile(QLatin1String("qml/tw_looptijden_berekenen/main.qml")); viewer.showExpanded(); return app-&gt;exec(); } </code></pre> <p>and the QML file:</p> <pre><code>import QtQuick 1.1 import com.myself 1.0 Rectangle { width: 360 height: 360 Text { text: qsTr("Hello World") anchors.centerIn: parent } MyObject { id: myobject } MouseArea { anchors.fill: parent onClicked: { myobject.reken_tijden_uit() } } } </code></pre> <p>And the errors are as follow:</p> <pre><code>D:\*\main.cpp:6: error: 'argc' was not declared in this scope D:\*\main.cpp:6: error: 'argv' was not declared in this scope D:\*\main.cpp:8: error: expected constructor, destructor, or type conversion before '&lt;' token </code></pre> <p>So what did I do wrong?</p>
0
1,272
Issue with NoClassDefFoundError error in a web environment Spring/Wicket/Derby/Jetty
<p>I am trying to build a simple JDBC Spring Template application, the web framework I am using is wicket and under the jetty 6 web server (through the Jetty Maven Plugin). Also, I am building the app with Eclipse.</p> <p>For some reason, I am getting a NoClassDefFoundError with the Derby jdbc class. I am assuming I would get a class not found exception was not found, so am guessing something else is happening. The derby class is part of the classpath, the WEB-INF/lib directory. What do you think the issue is?</p> <p><strong>My thoughts on the problem:</strong> It is not a "jar not found in the classpath" error but more an issue with Java or spring dynamically loading that class and when it gets loaded.</p> <p>I am using Eclipse as the development tool but it probably isn't part of the problem. I am still using Maven on the command line and getting the same issue.</p> <p>Here is the error:</p> <p>WicketMessage: Can't instantiate page using constructor public wicketspring.easy.HomePage()</p> <p>Root cause:</p> <pre><code>java.lang.NoClassDefFoundError: Could not initialize class org.apache.derby.jdbc.EmbeddedDriver at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:169) at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1130) at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880) at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:113) at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:79) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:577) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:619) at wicketspring.easy.jdbc.JdbcWicketSpringHandler.data(JdbcWicketSpringHandler.java:39) at WICKET_wicketspring.easy.jdbc.JdbcWicketSpringHandler$$FastClassByCGLIB$$f1187cb6.invoke(&lt;generated&gt;) at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191) at org.apache.wicket.proxy.LazyInitProxyFactory$CGLibInterceptor.intercept(LazyInitProxyFactory.java:319) at WICKET_wicketspring.easy.jdbc.JdbcWicketSpringHandler$$EnhancerByCGLIB$$e8f0e174.data(&lt;generated&gt;) at wicketspring.easy.HomePage.&lt;init&gt;(HomePage.java:91) at wicketspring.easy.HomePage.&lt;init&gt;(HomePage.java:47) </code></pre> <p>Here is the applicationContext.xml for Spring:</p> <pre><code>&lt;beans&gt; &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"&gt; &lt;property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" /&gt; &lt;property name="url"&gt;&lt;value&gt;jdbc:derby:wicketspringdb&lt;/value&gt;&lt;/property&gt; &lt;property name="username"&gt;&lt;value&gt;&lt;/value&gt;&lt;/property&gt; &lt;property name="password"&gt;&lt;value&gt;&lt;/value&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;/bean&gt; &lt;/beans&gt; &lt;beans&gt; &lt;import resource="classpath:common.xml"/&gt; &lt;bean id="jdbcHandler" class=wicketspring.easy.jdbc.JdbcWicketSpringHandler"&gt; &lt;property name="jdbcTemplate" ref="jdbcTemplate" /&gt; &lt;/bean&gt; &lt;/beans&gt; ... Another stack trace system out. Page.java:74) - At [2b] -- java.lang.NoClassDefFoundError: Could not initialize class org.apache.derby.jdbc.EmbeddedDriver java.lang.NoClassDefFoundError: Could not initialize class org.apache.derby.jdbc.EmbeddedDriver at wicketspring.easy.HomePage.&lt;init&gt;(HomePage.java:72) at wicketspring.easy.HomePage.&lt;init&gt;(HomePage.java:47) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java: 39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorIm pl.java:27) </code></pre> <p>...</p> <p>Here is the java code, the code compiles and I can print out the class but I can't instantiate it. Strange?</p> <p>Java Code:</p> <pre><code>package wicketspring.easy; import java.util.List; import org.apache.wicket.Application; import org.apache.wicket.PageParameters; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.proxy.IProxyTargetLocator; import org.apache.wicket.proxy.LazyInitProxyFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import model.LoadableDetachableList; import model.SelectionOptionBean; import wicketspring.easy.jdbc.JdbcWicketSpringHandler; import wicketspring.easy.service.IStateListService; import wicketspring.easy.service.StateListServiceImpl; import org.apache.derby.jdbc.EmbeddedDriver; public class HomePage extends WebPage { private final JdbcWicketSpringHandler jdbcWicketSpringHandler; public HomePage(final PageParameters parameters) { super(parameters); jdbcWicketSpringHandler = (JdbcWicketSpringHandler) LazyInitProxyFactory.createProxy(JdbcWicketSpringHandler.class, new IProxyTargetLocator() { private static final long serialVersionUID = 1L; public Object locateProxyTarget() { return ((WicketApplication) Application.get()).context().getBean("jdbcHandler"); } }); /// WEIRD BECAUSE IT REACHES THIS POINT!!! LOGGER.debug("At [1] -- " + EmbeddedDriver.class); try { LOGGER.debug("At [2] -- " + new org.apache.derby.jdbc.EmbeddedDriver()); } catch (NoClassDefFoundError ne) { // STACK TRACE ERROR HERE!!!! LOGGER.debug("At [2b] -- " + ne); ne.printStackTrace(); } catch (Exception e) { LOGGER.debug("At [2] -- " + e); e.printStackTrace(); } try { LOGGER.debug("At -- " + Class.forName("org.apache.derby.jdbc.EmbeddedDriver")); } catch (NoClassDefFoundError ne) { LOGGER.debug("At [3b] -- " + ne); ne.printStackTrace(); } catch (Exception e) { LOGGER.debug("At [3] -- " + e); e.printStackTrace(); } /// ERROR FOR STACKOVERFLOW IS GENERATED FROM THIS LINE!!!! LOGGER.debug("At HomePage - jdbcHandler [3]: " + jdbcWicketSpringHandler.toStringJdbcTemplate()); LOGGER.debug("At HomePage - jdbcHandler [3]: " + jdbcWicketSpringHandler.data()); ... } // End of Class // </code></pre> <p>Edit: I might be missing a jar file that is a dependency of Spring Jdbc or dbcp.</p> <p>Here is my WEB-INF/lib listing:</p> <pre><code>antlr-2.7.6.jar aopalliance-1.0.jar avalon-framework-4.1.3.jar axis-1.4.jar axis-jaxrpc-1.4.jar cglib-nodep-2.2.jar commons-collections-3.1.jar commons-dbcp-1.2.2.jar commons-logging-1.1.jar commons-pool-1.3.jar derby-10.6.1.0.jar dom4j-1.6.1.jar hibernate-core-3.5.1-Final.jar jetty-6.1.4.jar jetty-management-6.1.4.jar jetty-util-6.1.4.jar jta-1.1.jar log4j-1.2.14.jar logkit-1.0.1.jar mx4j-3.0.1.jar mx4j-tools-3.0.1.jar servlet-api-2.5-6.1.4.jar servlet-api-2.5.jar slf4j-api-1.5.8.jar slf4j-log4j12-1.4.2.jar spring-2.5.6.jar spring-aop-2.5.6.jar spring-beans-2.5.6.jar spring-context-2.5.6.jar spring-core-2.5.6.jar spring-jdbc-2.5.6.jar spring-test-2.5.6.jar spring-tx-2.5.6.jar testRunWrapper-1.0.0.jar wicket-1.4.13.jar wicket-ioc-1.4.13.jar wicket-spring-1.4.13.jar xml-apis-1.0.b2.jar </code></pre>
0
3,311
How to make HTML table expand on click?
<p>I am rendering HTML table with the help of JavaScript. I have made the table successfully, but now I have one requirement to show some new data in a row like on click expand row</p> <p>Table functionality:</p> <ul> <li>I am populating my table Some brand wise each brand has some items inside them, which I want to show when the brand is clicked</li> <li>I almost created the table, but not able to create the expandable row</li> <li>My one of column is populating wrong data also</li> </ul> <p>In my code I have commented all the lines what I am doing at which line</p> <p><strong>Issues I am facing</strong></p> <ul> <li>I have already commented the line where I am calculating netamount to populate inside <code>tbody</code> as <code>GRN entery</code> brand wise but that's causing the issue</li> </ul> <p>I have created two code snippets one as full static HTML like what I want, and a second to show what I have done.</p> <p><strong>The help I have found on Google</strong></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-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"&gt;&lt;/script&gt; &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"&gt; &lt;table class="table table-responsive table-hover table-bordered"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt; Brand Name&lt;/th&gt; &lt;th colspan="2"&gt;Total&lt;/th&gt; &lt;th colspan="2"&gt;Jayanagar&lt;/th&gt; &lt;th colspan="2"&gt;Malleshwaram&lt;/th&gt; &lt;th colspan="2"&gt;Kolar&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;&lt;/th&gt; &lt;th&gt;Grn Entery&lt;/th&gt; &lt;th&gt;Sales&lt;/th&gt; &lt;th&gt;Grn Entery&lt;/th&gt; &lt;th&gt;Sales&lt;/th&gt; &lt;th&gt;Grn Entery&lt;/th&gt; &lt;th&gt;Sales&lt;/th&gt; &lt;th&gt;Grn Entery&lt;/th&gt; &lt;th&gt;Sales&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Total&lt;/th&gt; &lt;th&gt;1,97,445&lt;/th&gt; &lt;th&gt;6,83,880&lt;/th&gt; &lt;th&gt;1,97,445&lt;/th&gt; &lt;th&gt;4,76,426&lt;/th&gt; &lt;th&gt;0&lt;/th&gt; &lt;th&gt;1,15,313&lt;/th&gt; &lt;th&gt;0&lt;/th&gt; &lt;th&gt;92,141&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;span class="clickable" data-toggle="collapse" id="row1" data-target=".row1"&gt;&lt;i class="fas fa-plus" id="test"&gt;&lt;/i&gt;&amp;nbsp&lt;/span&gt;Bakery FG&lt;/td&gt; &lt;td&gt;1,610&lt;/td&gt; &lt;td&gt;0.82%&lt;/td&gt; &lt;td&gt;1,610 &lt;/td&gt; &lt;td&gt;0.82%&lt;/td&gt; &lt;!-- this is comming as (1610/197445)*100 --&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row1"&gt; &lt;td&gt;Khara Boondhi-L&lt;/td&gt; &lt;td&gt;980&lt;/td&gt; &lt;td&gt;0.50%&lt;/td&gt; &lt;td&gt;980&lt;/td&gt; &lt;td&gt;0.50%&lt;/td&gt; &lt;!-- this is comming as (980/197445)*100 --&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;!-- lly for other outlets it will be calculated --&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row1"&gt; &lt;td&gt;Samosa-L&lt;/td&gt; &lt;td&gt;130&lt;/td&gt; &lt;td&gt;0.7%&lt;/td&gt; &lt;td&gt;130&lt;/td&gt; &lt;td&gt;0.7%&lt;/td&gt; &lt;!-- this is comming as (130/197445)*100 --&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row1"&gt; &lt;td&gt;Corn Flakes Masala-L&lt;/td&gt; &lt;td&gt;500&lt;/td&gt; &lt;td&gt;0.25%&lt;/td&gt; &lt;td&gt;500&lt;/td&gt; &lt;td&gt;0.25%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;span class="clickable" data-toggle="collapse" data-target=".row2"&gt;&lt;i class="fas fa-plus" id="test"&gt;&lt;/i&gt;&amp;nbsp&lt;/span&gt;Pastry &amp; Cake FG&lt;/td&gt; &lt;td&gt;49,230&lt;/td&gt; &lt;td&gt;25.00%&lt;/td&gt; &lt;td&gt;49,230&lt;/td&gt; &lt;td&gt;25.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row2"&gt; &lt;td&gt;Plum Cake 250gm&lt;/td&gt; &lt;td&gt;110&lt;/td&gt; &lt;td&gt;0.05%&lt;/td&gt; &lt;td&gt;110&lt;/td&gt; &lt;td&gt;0.05%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row2"&gt; &lt;td&gt;Butterscotch Cake&lt;/td&gt; &lt;td&gt;720&lt;/td&gt; &lt;td&gt;0.36%&lt;/td&gt; &lt;td&gt;720&lt;/td&gt; &lt;td&gt;0.36%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row2"&gt; &lt;td&gt;Chocolate chips cake&lt;/td&gt; &lt;td&gt;40000&lt;/td&gt; &lt;td&gt;20.25%&lt;/td&gt; &lt;td&gt;40000&lt;/td&gt; &lt;td&gt;20.25%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row2"&gt; &lt;td&gt;Mango Delight Cake&lt;/td&gt; &lt;td&gt;14000&lt;/td&gt; &lt;td&gt;7.09%&lt;/td&gt; &lt;td&gt;14000&lt;/td&gt; &lt;td&gt;7.09%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row2"&gt; &lt;td&gt;Almond Honey Chocolate Cake&lt;/td&gt; &lt;td&gt;500&lt;/td&gt; &lt;td&gt;0.25% &lt;td&gt;500&lt;/td&gt; &lt;td&gt;0.25% &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row2"&gt; &lt;td&gt;Peach Cake&lt;/td&gt; &lt;td&gt;5500&lt;/td&gt; &lt;td&gt;2.78%&lt;/td&gt; &lt;td&gt;5500&lt;/td&gt; &lt;td&gt;2.78%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row2"&gt; &lt;td&gt;Black Forest Cake&lt;/td&gt; &lt;td&gt;1000&lt;/td&gt; &lt;td&gt;0.50%&lt;/td&gt; &lt;td&gt;1000&lt;/td&gt; &lt;td&gt;0.50%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;span class="clickable" data-toggle="collapse" data-target=".row3"&gt;&lt;i class="fas fa-plus" id="test"&gt;&lt;/i&gt;&amp;nbsp&lt;/span&gt;Ice Cream FG&lt;/td&gt; &lt;td&gt;108441&lt;/td&gt; &lt;td&gt;54.92%&lt;/td&gt; &lt;td&gt;108441&lt;/td&gt; &lt;td&gt;54.92%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;Chocolate Crazy Boom&lt;/td&gt; &lt;td&gt;2360&lt;/td&gt; &lt;td&gt;1.19%&lt;/td&gt; &lt;td&gt;2360&lt;/td&gt; &lt;td&gt;1.19%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;Kesar Badam Falooda&lt;/td&gt; &lt;td&gt;4430&lt;/td&gt; &lt;td&gt;2.24%&lt;/td&gt; &lt;td&gt;4430&lt;/td&gt; &lt;td&gt;2.24%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;Strawberry Ice-cream&lt;/td&gt; &lt;td&gt;1231&lt;/td&gt; &lt;td&gt;0.62%&lt;/td&gt; &lt;td&gt;1231&lt;/td&gt; &lt;td&gt;0.62%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;TOP- Chocochips&lt;/td&gt; &lt;td&gt;2200&lt;/td&gt; &lt;td&gt;1.11%&lt;/td&gt; &lt;td&gt;2200&lt;/td&gt; &lt;td&gt;1.11%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;Cheese Cake Ice-Cream&lt;/td&gt; &lt;td&gt;500&lt;/td&gt; &lt;td&gt;0.25%&lt;/td&gt; &lt;td&gt;500&lt;/td&gt; &lt;td&gt;0.25%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;Sundae Large&lt;/td&gt; &lt;td&gt;2350&lt;/td&gt; &lt;td&gt;1.20%&lt;/td&gt; &lt;td&gt;2350&lt;/td&gt; &lt;td&gt;1.20%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;Mango Ice-cream&lt;/td&gt; &lt;td&gt;8000&lt;/td&gt; &lt;td&gt;40.5%&lt;/td&gt; &lt;td&gt;8000&lt;/td&gt; &lt;td&gt;40.5%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;Ice Blue Sundae&lt;/td&gt; &lt;td&gt;2340&lt;/td&gt; &lt;td&gt;1.19%&lt;/td&gt; &lt;td&gt;2340&lt;/td&gt; &lt;td&gt;1.19%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;Creamy Litchi Boom&lt;/td&gt; &lt;td&gt;2200&lt;/td&gt; &lt;td&gt;1.11%&lt;/td&gt; &lt;td&gt;2200&lt;/td&gt; &lt;td&gt;1.11%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;Cookies Ice-cream&lt;/td&gt; &lt;td&gt;7000&lt;/td&gt; &lt;td&gt;3.54%&lt;/td&gt; &lt;td&gt;7000&lt;/td&gt; &lt;td&gt;3.54%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;TOP- Wafer&lt;/td&gt; &lt;td&gt;88000&lt;/td&gt; &lt;td&gt;44.56%&lt;/td&gt; &lt;td&gt;88000&lt;/td&gt; &lt;td&gt;44.56%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;Litchi cherry Sundae&lt;/td&gt; &lt;td&gt;2440&lt;/td&gt; &lt;td&gt;1.23%&lt;/td&gt; &lt;td&gt;2440&lt;/td&gt; &lt;td&gt;1.23%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;Peach Malaba&lt;/td&gt; &lt;td&gt;2230&lt;/td&gt; &lt;td&gt;1.12%&lt;/td&gt; &lt;td&gt;2230&lt;/td&gt; &lt;td&gt;1.12%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row3"&gt; &lt;td&gt;Cherry Mania Ice-Cream&lt;/td&gt; &lt;td&gt;2700&lt;/td&gt; &lt;td&gt;1.36%&lt;/td&gt; &lt;td&gt;2700&lt;/td&gt; &lt;td&gt;1.36%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;span class="clickable" data-toggle="collapse" data-target=".row4"&gt;&lt;i class="fas fa-plus" id="test"&gt;&lt;/i&gt;&amp;nbsp&lt;/span&gt;North Indian FG&lt;/td&gt; &lt;td&gt;324&lt;/td&gt; &lt;td&gt;0.17%&lt;/td&gt; &lt;td&gt;324&lt;/td&gt; &lt;td&gt;0.17%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;tr class="collapse row4"&gt; &lt;td&gt;Fruit Mixture&lt;/td&gt; &lt;td&gt;324&lt;/td&gt; &lt;td&gt;0.17%&lt;/td&gt; &lt;td&gt;324&lt;/td&gt; &lt;td&gt;0.17%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;td&gt;0&lt;/td&gt; &lt;td&gt;0.00%&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p>I want to create something like the above snippet, but its expanding on clicking of row. I want to do it when the user clicks on <code>plus</code> icon, which I <a href="https://getbootstrap.com/docs/4.0/components/collapse/" rel="nofollow noreferrer">figured out how to do</a>.</p> <p><strong>My dynamic code with JSON data</strong></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 format(number, decimals = 2, locale = 'en-in') { const fixed = parseInt(number).toFixed(decimals); const [int, dec] = fixed.split('.') const intFormatted = (+int).toLocaleString(locale) return intFormatted + (dec ? '.' + dec : ''); } var data = [{ "outlet": "JAYANAGAR", "brandname": "Bakery FG", "itemname": "Khara Boondhi-L", "transactionType": "TransferIn", "netamount": 980 }, { "outlet": "JAYANAGAR", "brandname": "Bakery FG", "itemname": "Samosa-L", "transactionType": "TransferIn", "netamount": 130 }, { "outlet": "JAYANAGAR", "brandname": "Bakery FG", "itemname": "Corn Flakes Masala-L", "transactionType": "TransferIn", "netamount": 500 }, { "outlet": "JAYANAGAR", "brandname": "Pastry &amp; Cake FG", "itemname": "Plum Cake 250gm", "transactionType": "TransferIn", "netamount": 110 }, { "outlet": "JAYANAGAR", "brandname": "Pastry &amp; Cake FG", "itemname": "Butterscotch Cake", "transactionType": "TransferIn", "netamount": 720 }, { "outlet": "JAYANAGAR", "brandname": "Pastry &amp; Cake FG", "itemname": "Chocolate chips cake", "transactionType": "TransferIn", "netamount": 40000 }, { "outlet": "JAYANAGAR", "brandname": "Pastry &amp; Cake FG", "itemname": "Mango Delight Cake", "transactionType": "TransferIn", "netamount": 14000 }, { "outlet": "JAYANAGAR", "brandname": "Pastry &amp; Cake FG", "itemname": "Almond Honey Chocolate Cake", "transactionType": "TransferIn", "netamount": 500 }, { "outlet": "JAYANAGAR", "brandname": "Pastry &amp; Cake FG", "itemname": "Peach Cake", "transactionType": "TransferIn", "netamount": 5500 }, { "outlet": "JAYANAGAR", "brandname": "Pastry &amp; Cake FG", "itemname": "Black Forest Cake", "transactionType": "TransferIn", "netamount": 1000 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Chocolate Crazy Boom", "transactionType": "TransferIn", "netamount": 2360 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Hot Chocolate Fudge", "transactionType": "TransferIn", "netamount": 2340 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Chocolate Sugar Free Ice-Cream", "transactionType": "TransferIn", "netamount": 1000 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Kesar Badam Falooda", "transactionType": "TransferIn", "netamount": 4430 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Strawberry Ice-cream", "transactionType": "TransferIn", "netamount": 1231 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "TOP- Chocochips", "transactionType": "TransferIn", "netamount": 2200 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Cheese Cake Ice-Cream", "transactionType": "TransferIn", "netamount": 500 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Sundae Large", "transactionType": "TransferIn", "netamount": 2350 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Mango Ice-cream", "transactionType": "TransferIn", "netamount": 8000 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "TOP- Shooting Star", "transactionType": "TransferIn", "netamount": 2360 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Ice Blue Sundae", "transactionType": "TransferIn", "netamount": 2340 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Creamy Litchi Boom", "transactionType": "TransferIn", "netamount": 2200 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Cookies Ice-cream", "transactionType": "TransferIn", "netamount": 7000 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "TOP- Wafer", "transactionType": "TransferIn", "netamount": 88000 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Litchi cherry Sundae", "transactionType": "TransferIn", "netamount": 2440 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Peach Malaba", "transactionType": "TransferIn", "netamount": 2230 }, { "outlet": "JAYANAGAR", "brandname": "Ice Cream FG", "itemname": "Cherry Mania Ice-Cream", "transactionType": "TransferIn", "netamount": 2700 }, { "outlet": "JAYANAGAR", "brandname": "North Indian FG", "itemname": "Fruit Mixture", "transactionType": "TransferIn", "netamount": 324 }, { "outlet": "JAYANAGAR", "brandname": "NA", "itemname": "NA", "transactionType": "Sales", "netamount": 476426 }, { "outlet": "KOLAR", "brandname": "NA", "itemname": "NA", "transactionType": "Sales", "netamount": 115313 }, { "outlet": "MALLESHWARAM", "brandname": "NA", "itemname": "NA", "transactionType": "Sales", "netamount": 92141 } ] let formatData = function(data) { let brandnames = []; let itemnames = []; let outlets = []; let maxUniqueForOutlets = {}; data.forEach(element =&gt; { if (!maxUniqueForOutlets[element["brandname"]]) { // i just want to filter this brand and items whichhave NA maxUniqueForOutlets[element["brandname"]] = []; console.log(maxUniqueForOutlets[element["brandname"]]) //key value pair of brandname and itemname } if (maxUniqueForOutlets[element["brandname"]].indexOf(element["itemname"]) == -1) { maxUniqueForOutlets[element["brandname"]].push(element["itemname"]); } if (brandnames.indexOf(element.brandname) == -1 &amp;&amp; (element.brandname) !== "NA") { //taking brandname which do not have bradname===NA brandnames.push(element.brandname); } if (itemnames.indexOf(element.itemname) == -1 &amp;&amp; (element.itemname) !== "NA") { //taking itemname which do not have bradname===NA itemnames.push(element.itemname); } if (outlets.indexOf(element.outlet) == -1) { outlets.push(element.outlet); } }); return { data: data, brandnames: brandnames, itemnames: itemnames, outlets: outlets, maxUniqueForOutlets: maxUniqueForOutlets }; }; var totalSalesPercentage = ''; var olWiseSalesPercentage = ''; let renderTable = function(data) { let brandnames = data.brandnames; let itemnames = data.itemnames; let outlets = data.outlets; let maxUniqueForOutlets = data.maxUniqueForOutlets; data = data.data; let tbl = document.getElementById("ConsumptionTable"); let table = document.createElement("table"); let thead = document.createElement("thead"); let headerRow = document.createElement("tr"); let th = document.createElement("th"); th = document.createElement("th"); th.innerHTML = "Brand Name"; th.classList.add("text-center"); headerRow.appendChild(th); let grandTotal = 0; let grandNetAmount = 0; let outletWiseTotal = {}; let outletWiseNetamount = {}; th = document.createElement("th"); th.colSpan = 2; th.innerHTML = "Total"; th.classList.add("text-center"); headerRow.appendChild(th); outlets.forEach(element =&gt; { th = document.createElement("th"); th.colSpan = 2; th.innerHTML = element; // populating outlet th.classList.add("text-center"); headerRow.appendChild(th); outletWiseTotal[element] = 0; data.forEach(el =&gt; { if (el.outlet == element &amp;&amp; el.brandname !== "NA") { //taking brandname which do not have bradname===NA outletWiseTotal[element] += parseInt(el.netamount); //here i am calculating the outletWiseTotal where transcationType==TransferIn } if (el.outlet == element &amp;&amp; el.brandname == "NA" &amp;&amp; el.transactionType == "Sales") { //taking brandname which do not have bradname===NA outletWiseNetamount[element] = parseInt(el.netamount) || 0 } }); grandTotal += outletWiseTotal[element]; //then calculating grand total to populate it into Total column at grn entery grandNetAmount += outletWiseNetamount[element] || 0 }); thead.appendChild(headerRow); headerRow = document.createElement("tr"); th = document.createElement("th"); th.innerHTML = ""; headerRow.appendChild(th); for (let i = 0; i &lt; outlets.length + 1; i++) { th = document.createElement("th"); th.innerHTML = "Sales"; th.classList.add("text-center"); headerRow.appendChild(th); th = document.createElement("th"); th.innerHTML = "Grn Entery"; th.classList.add("text-center"); headerRow.appendChild(th); } headerRow.insertBefore(th, headerRow.children[1]); thead.appendChild(headerRow); table.appendChild(thead); headerRow = document.createElement("tr"); let td = document.createElement("th"); td.innerHTML = "Total"; td.classList.add("text-center"); headerRow.appendChild(td); let el1 = 0; outlets.forEach(element =&gt; { td = document.createElement("th"); td.innerHTML = outletWiseTotal[element].toLocaleString('en-IN'); td.classList.add("text-right"); headerRow.appendChild(td); if (element.outlet == element) { el1 = element.netAmount; } td = document.createElement("th"); td.innerHTML = outletWiseNetamount[element].toLocaleString('en-IN') || 0; td.classList.add("text-right"); headerRow.appendChild(td); }); td = document.createElement("th"); td.innerHTML = grandNetAmount.toLocaleString('en-IN'); td.classList.add("text-right"); headerRow.insertBefore(td, headerRow.children[1]); td = document.createElement("th"); td.innerHTML = grandTotal.toLocaleString('en-IN'); td.classList.add("text-right"); headerRow.insertBefore(td, headerRow.children[1]); thead.appendChild(headerRow); table.appendChild(thead); let tbody = document.createElement("tbody"); Object.keys(maxUniqueForOutlets).forEach(function(element) { // rendering brand name let row = document.createElement("tr"); row.classList.add('header'); td = document.createElement("td"); td.innerHTML = '&lt;span&gt;&lt;i class="fas fa-plus" id="test"&gt;&lt;/i&gt;&amp;nbsp&lt;/span&gt;' + element; //creating plus font icon to make click happen row.appendChild(td); let total = 0; let totalBCount = 0; outlets.forEach(outlet =&gt; { let el = 0; let bc = 0; data.forEach(d =&gt; { if (d.brandname == element &amp;&amp; d.outlet == outlet) { total += parseInt(d.netamount); el = d.netamount; //calculating outlet wise net amount } }); olWiseSalesPercentage = (el / outletWiseTotal[outlet]) * 100 || 0 td = document.createElement("td"); td.innerHTML = el.toLocaleString('en-IN'); // by this one i am populating outlet wise values for bramd but it is displaying wrong values td.classList.add("text-right"); row.appendChild(td); td = document.createElement("td"); td.innerHTML = olWiseSalesPercentage.toFixed(2) + "%"; td.classList.add("text-right"); row.appendChild(td); }); totalSalesPercentage = (total / grandTotal) * 100 //here doing some calculations const totalSalesPercentageFix = totalSalesPercentage.toFixed(2) + "%" td = document.createElement("td"); td.innerHTML = totalSalesPercentageFix; td.classList.add("text-right"); row.insertBefore(td, row.children[1]); td = document.createElement("td"); td.innerHTML = total.toLocaleString('en-IN'); td.classList.add("text-right"); row.insertBefore(td, row.children[1]); tbody.appendChild(row); maxUniqueForOutlets[element].forEach(function(k) { //this one is populating itemwise values but it starts with Total column Total column will populate Total let rowChildren = document.createElement("tr"); const filteredData = data.filter(a =&gt; a.itemname === k); if (filteredData.length &gt; 0) { var tdNew = document.createElement("td"); tdNew.innerHTML = filteredData[0].netamount; tdNew.classList.add("text-right"); var tdName = document.createElement("td"); tdName.innerHTML = filteredData[0].itemname; tdName.classList.add("text-left"); rowChildren.appendChild(tdName); rowChildren.appendChild(tdNew); outlets.forEach(outlet =&gt; { const emptyCell = document.createElement('td'); //this i am creating staticly how can i create this statically as here i have 3 outlets so i am creating emptyCell.innerHTML = "12"; emptyCell.classList.add("text-right"); rowChildren.appendChild(emptyCell); const emptyCell1 = document.createElement('td'); emptyCell1.innerHTML = "13"; emptyCell1.classList.add("text-right"); rowChildren.appendChild(emptyCell1); tbody.appendChild(rowChildren); }); } }) }); table.appendChild(tbody); tbl.innerHTML = ""; tbl.appendChild(table); table.classList.add("table"); table.classList.add("table-striped"); table.classList.add("table-bordered"); table.classList.add("table-hover"); } let formatedData = formatData(data); renderTable(formatedData); var ua = navigator.userAgent, event = (ua.match(/iPad/i)) ? "touchstart" : "click"; $('.table .header .fa-plus').on(event, function() { $(this).closest('.header').toggleClass("active", "").nextUntil('.header').css('display', function(i, v) { return this.style.display === 'table-row' ? 'none' : 'table-row'; }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#test { color: green; cursor: pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"&gt; &lt;div align="center" class="table table-responsive"&gt; &lt;table id="ConsumptionTable"&gt;&lt;/table&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I have tried the other approach, which was when the user clicks on any brand I was making an Ajax call and running the query on the basis of that brand name and getting data, but still not able to get the expand functionality.</p> <p>Now I realised that this is the best approach to get the data at once, then make table with that; I am just struggling to get it right</p> <p><strong>Dynamic Code Working process</strong></p> <ul> <li>Currently I have table with <code>Brand Name</code>,<code>Grn Entery</code>,<code>Sales</code> Sales body data which is in percentage I am calculating it by dividing <code>grn</code> by Total grn of that column and dividing it by 100</li> <li>So when user clicks on any brand names's icon that is <code>plus</code> in my case I want to expand rows with all itemnames of that brand and whole structure of table will be same as it is for <code>brandname</code> wise, grn calculation wil all be according to item name, currently it is as per brand name</li> </ul> <p><strong>Edit/update</strong></p> <p>I am having some issues:</p> <ul> <li><p>First of all using this code I am geting brand names and item names but it is taking NA also, I have tried to filter it out but haven't succeeded. Please check my snippet, I have commented all lines there.</p></li> <li><p>when there is transactiontype:sales and itemname and brandname= <code>NA</code> then I am populating those values in header as sales value they don't have any relation with calculating percentage</p></li> <li><p>when I am populating the item inside brand there I have to do it dynamically I have tried but didn't get that</p></li> </ul> <p><a href="https://i.stack.imgur.com/RTQng.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RTQng.png" alt="Table description with image"></a></p>
0
15,264
How to solve "Expected a value of type 'int', but got one of type 'String'" in Flutter
<p>I have a local JSON file which looks like this:</p> <pre><code>[ { &quot;1&quot;: [ { &quot;mode&quot;: &quot;text&quot;, &quot;value&quot;: &quot;text exapple1&quot; }, { &quot;mode&quot;: &quot;latex&quot;, &quot;value&quot;: &quot;\frac00&quot; }, { &quot;mode&quot;: &quot;text&quot;, &quot;value&quot;: &quot;text exapple2&quot; }, { &quot;mode&quot;: &quot;latex&quot;, &quot;value&quot;: &quot;\frac00&quot; }, { &quot;mode&quot;: &quot;text&quot;, &quot;value&quot;: &quot;text exapple3&quot; } ] }, { &quot;2&quot;: [ { &quot;mode&quot;: &quot;text&quot;, &quot;value&quot;: &quot;text exapple4&quot; } ] } ] </code></pre> <p>and I am trying to parse it using FutureBuilder in my code:</p> <pre><code>return FutureBuilder( future: DefaultAssetBundle.of(context).loadString(&quot;assets/paragraph.json&quot;), builder: (context, snapshot) { var mydata = json.decode(snapshot.data.toString()); if (mydata != null) { return SizeTransition( axis: Axis.vertical, sizeFactor: animation, child: Center(child: Text(mydata[&quot;1&quot;][0].toString())) ); } else { return SizeTransition( axis: Axis.vertical, sizeFactor: animation, child: Center(child: CircularProgressIndicator()) ); } }); </code></pre> <p>Here is the error message I get:</p> <blockquote> <p>══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ The following TypeErrorImpl was thrown building FutureBuilder(dirty, state: _FutureBuilderState#4fb8d): Expected a value of type 'int', but got one of type 'String'</p> </blockquote> <p>and if I do it like:</p> <pre><code>mydata[1][1] </code></pre> <p>it gives me a null output!</p> <p>What is wrong with this code and how to fix it?</p>
0
1,258
ERROR: You must give at least one requirement to install -- when running: pip install --upgrade --no-binary hdbscan
<p>I am trying to install hdbscan in my PC which runs Windows 10 and has installed Python 3.6. </p> <p>My first attempt failed:</p> <pre><code>(base) C:\WINDOWS\system32&gt;pip install hdbscan --user Collecting hdbscan Using cached https://files.pythonhosted.org/packages/10/7c/1401ec61b0e7392287e045b6913206cfff050b65d869c19f7ec0f5626487/hdbscan-0.8.22.tar.gz Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... done Requirement already satisfied: scikit-learn&gt;=0.17 in c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\site-packages (from hdbscan) (0.19.1) Requirement already satisfied: joblib in c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\site-packages (from hdbscan) (0.13.2) Requirement already satisfied: numpy&gt;=1.16.0 in c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\site-packages (from hdbscan) (1.17.2) Requirement already satisfied: cython&gt;=0.27 in c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\site-packages (from hdbscan) (0.29.10) Requirement already satisfied: scipy&gt;=0.9 in c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\site-packages (from hdbscan) (1.2.2) Building wheels for collected packages: hdbscan Building wheel for hdbscan (PEP 517) ... error ERROR: Command errored out with exit status 1: command: 'c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\python.exe' 'c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\site-packages\pip\_vendor\pep517\_in_process.py' build_wheel 'C:\Users\Alienware\AppData\Local\Temp\tmp8ir950og' cwd: C:\Users\Alienware\AppData\Local\Temp\pip-install-hxifwoph\hdbscan Complete output (67 lines): running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\hdbscan copying hdbscan\hdbscan_.py -&gt; build\lib.win-amd64-3.6\hdbscan copying hdbscan\plots.py -&gt; build\lib.win-amd64-3.6\hdbscan copying hdbscan\prediction.py -&gt; build\lib.win-amd64-3.6\hdbscan copying hdbscan\robust_single_linkage_.py -&gt; build\lib.win-amd64-3.6\hdbscan copying hdbscan\validity.py -&gt; build\lib.win-amd64-3.6\hdbscan copying hdbscan\__init__.py -&gt; build\lib.win-amd64-3.6\hdbscan creating build\lib.win-amd64-3.6\hdbscan\tests copying hdbscan\tests\test_hdbscan.py -&gt; build\lib.win-amd64-3.6\hdbscan\tests copying hdbscan\tests\test_rsl.py -&gt; build\lib.win-amd64-3.6\hdbscan\tests copying hdbscan\tests\__init__.py -&gt; build\lib.win-amd64-3.6\hdbscan\tests running build_ext Traceback (most recent call last): File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 207, in &lt;module&gt; main() File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 197, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 141, in build_wheel metadata_directory) File "C:\Users\Alienware\AppData\Local\Temp\pip-build-env-n2heecpm\overlay\Lib\site-packages\setuptools\build_meta.py", line 209, in build_wheel wheel_directory, config_settings) File "C:\Users\Alienware\AppData\Local\Temp\pip-build-env-n2heecpm\overlay\Lib\site-packages\setuptools\build_meta.py", line 194, in _build_with_temp_dir self.run_setup() File "C:\Users\Alienware\AppData\Local\Temp\pip-build-env-n2heecpm\overlay\Lib\site-packages\setuptools\build_meta.py", line 237, in run_setup self).run_setup(setup_script=setup_script) File "C:\Users\Alienware\AppData\Local\Temp\pip-build-env-n2heecpm\overlay\Lib\site-packages\setuptools\build_meta.py", line 142, in run_setup exec(compile(code, __file__, 'exec'), locals()) File "setup.py", line 96, in &lt;module&gt; setup(**configuration) File "C:\Users\Alienware\AppData\Local\Temp\pip-build-env-n2heecpm\overlay\Lib\site-packages\setuptools\__init__.py", line 145, in setup return distutils.core.setup(**attrs) File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\core.py", line 148, in setup dist.run_commands() File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\dist.py", line 955, in run_commands self.run_command(cmd) File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "C:\Users\Alienware\AppData\Local\Temp\pip-build-env-n2heecpm\overlay\Lib\site-packages\wheel\bdist_wheel.py", line 192, in run self.run_command('build') File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\command\build.py", line 135, in run self.run_command(cmd_name) File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "setup.py", line 26, in run build_ext.run(self) File "C:\Users\Alienware\AppData\Local\Temp\pip-build-env-n2heecpm\overlay\Lib\site-packages\Cython\Distutils\old_build_ext.py", line 186, in run _build_ext.build_ext.run(self) File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\command\build_ext.py", line 308, in run force=self.force) File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\ccompiler.py", line 1031, in new_compiler return klass(None, dry_run, force) File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\cygwinccompiler.py", line 285, in __init__ CygwinCCompiler.__init__ (self, verbose, dry_run, force) File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\cygwinccompiler.py", line 129, in __init__ if self.ld_version &gt;= "2.10.90": TypeError: '&gt;=' not supported between instances of 'NoneType' and 'str' ---------------------------------------- ERROR: Failed building wheel for hdbscan Running setup.py clean for hdbscan Failed to build hdbscan ERROR: Could not build wheels for hdbscan which use PEP 517 and cannot be installed directly </code></pre> <p>Do you understand why the system could not build the wheels for hdbscan?</p> <p>Is there something I can do about it? What are the alternatives at this point?</p> <p>I tried to install the hdbscan without the binaries but again failed:</p> <pre><code>(base) C:\WINDOWS\system32&gt;pip install --upgrade --no-binary hdbscan ERROR: You must give at least one requirement to install (see "pip help install") </code></pre> <hr> <pre><code>(base) C:\WINDOWS\system32&gt;pip list outdated Package Version ---------------------------------- --------------------- matplotlib 2.2.2 scipy 1.1.0 numpy 1.14.3 absl-py 0.7.1 alabaster 0.7.10 anaconda-client 1.6.14 anaconda-navigator 1.8.7 anaconda-project 0.8.2 arviz 0.4.1 asn1crypto 0.24.0 aspy.yaml 1.2.0 astor 0.7.1 astroid 1.6.3 astropy 3.0.2 astunparse 1.6.2 attrs 18.1.0 autograd 1.2 Babel 2.5.3 backcall 0.1.0 backports.shutil-get-terminal-size 1.0.0 beautifulsoup4 4.6.0 bitarray 0.8.1 bkcharts 0.2 blaze 0.11.3 bleach 1.5.0 blis 0.2.4 bokeh 0.12.16 boto 2.48.0 boto3 1.9.130 botocore 1.12.130 Bottleneck 1.2.1 brewer2mpl 1.4.1 bs4 0.0.1 bz2file 0.98 certifi 2018.4.16 cffi 1.11.5 cfgv 1.6.0 cftime 1.0.3.4 chardet 3.0.4 click 6.7 cloudpickle 1.2.1 clyent 1.2.2 colorama 0.3.9 colour 0.1.5 comtypes 1.1.4 conda 4.6.8 conda-build 3.10.5 conda-verify 2.0.0 contextlib2 0.5.5 convertdate 2.1.3 cryptography 2.2.2 cycler 0.10.0 cymem 2.0.2 Cython 0.29.10 cytoolz 0.9.0.1 d2l 0.9.2 dask 0.17.5 datashape 0.5.4 decorator 4.3.0 dill 0.3.0 distributed 1.21.8 Django 2.2.2 dltk 0.2.1 docutils 0.14 el-core-news-md 2.1.0 el-core-news-sm 2.1.0 embedder 0.1 en-core-web-md 2.1.0 entrypoints 0.2.3 ephem 3.7.6.0 et-xmlfile 1.0.1 fastcache 1.0.2 fastdtw 0.3.2 fasttext 0.8.3 fbprophet 0.1.post1 filelock 3.0.4 fix-yahoo-finance 0.0.22 Flask 1.0.2 Flask-Cors 3.0.4 future 0.17.1 gast 0.2.2 gensim 3.7.1 geojson 2.4.1 gevent 1.3.0 ggplot 0.11.5 glob2 0.6 google-pasta 0.1.4 googleapis-common-protos 1.6.0 graphviz 0.8.4 greenlet 0.4.13 grpcio 1.19.0 gym 0.14.0 h5py 2.7.1 heapdict 1.0.0 hmmlearn 0.2.2 holidays 0.9.10 html5lib 0.9999999 hyperopt 0.1.1 identify 1.4.1 idna 2.6 image 1.5.27 imageio 2.3.0 imagesize 1.0.0 importlib-metadata 0.9 importlib-resources 1.0.2 inflection 0.3.1 ipykernel 4.8.2 ipython 6.4.0 ipython-genutils 0.2.0 ipywidgets 7.2.1 isort 4.3.4 iterative-stratification 0.1.6 itsdangerous 0.24 jdcal 1.4 jedi 0.12.0 Jinja2 2.10 jmespath 0.9.4 joblib 0.13.2 json-tricks 3.12.2 jsonschema 2.6.0 jupyter 1.0.0 jupyter-client 5.2.3 jupyter-console 5.2.0 jupyter-contrib-core 0.3.3 jupyter-contrib-nbextensions 0.5.1 jupyter-core 4.4.0 jupyter-highlight-selected-word 0.2.0 jupyter-latex-envs 1.4.6 jupyter-nbextensions-configurator 0.4.1 jupyterlab 0.32.1 jupyterlab-launcher 0.10.5 Keras 2.2.5 Keras-Applications 1.0.8 Keras-Preprocessing 1.1.0 keras-rl 0.4.2 kiwisolver 1.0.1 lazy-object-proxy 1.3.1 llvmlite 0.23.1 locket 0.2.0 lunardate 0.2.0 lxml 4.4.1 Markdown 3.1 MarkupSafe 1.0 matplotlib 3.1.1 mccabe 0.6.1 menuinst 1.4.14 mistune 0.8.3 mkl-fft 1.0.0 mkl-random 1.0.1 mock 2.0.0 more-itertools 4.1.0 mpld3 0.3 mpmath 1.0.0 msgpack 0.6.1 msgpack-python 0.5.6 multipledispatch 0.5.0 multitasking 0.0.7 murmurhash 1.0.2 mxnet-cu101 1.5.0 navigator-updater 0.2.1 nbconvert 5.3.1 nbformat 4.4.0 netCDF4 1.5.1.2 networkx 2.1 neuralcoref 4.0 nltk 3.3 NNI 0.1.0 nodeenv 1.3.3 nose 1.3.7 notebook 5.5.0 numba 0.38.0 numexpr 2.6.5 numpy 1.17.2 numpydoc 0.8.0 odo 0.5.1 olefile 0.45.1 opencv-python 4.1.1.26 openpyxl 2.5.3 packaging 17.1 pandas 0.24.2 pandas-datareader 0.7.0 pandocfilters 1.4.2 parso 0.2.0 partd 0.3.8 path.py 11.0.1 pathlib2 2.3.2 patsy 0.5.0 pbr 5.1.3 pep8 1.7.1 pickleshare 0.7.4 Pillow 5.1.0 pip 19.2.3 pixiedust 1.1.13 pkginfo 1.4.2 plac 0.9.6 plotly 4.0.0 pluggy 0.6.0 ply 3.11 pmdarima 1.2.1 pre-commit 1.15.1 preshed 2.0.1 promise 2.2.1 prompt-toolkit 1.0.15 protobuf 3.7.1 psutil 5.4.5 py 1.5.3 py-translate 1.0.3 pybind11 2.2.4 pycodestyle 2.4.0 pycosat 0.6.3 pycparser 2.18 pycrypto 2.6.1 pycurl 7.43.0.1 pydot 1.4.1 pydotplus 2.0.2 pyflakes 1.6.0 pyglet 1.3.2 Pygments 2.2.0 pylint 1.8.4 pymongo 3.7.1 pyodbc 4.0.23 pyOpenSSL 18.0.0 pyparsing 2.2.0 PyProcessMacro 1.0.0 pyreadstat 0.2.1 PySocks 1.6.8 pystan 2.19.0.0 pytest 3.5.1 pytest-arraydiff 0.2 pytest-astropy 0.3.0 pytest-doctestplus 0.1.3 pytest-openfiles 0.3.0 pytest-remotedata 0.2.1 python-dateutil 2.7.3 pytz 2018.4 PyWavelets 0.5.2 pywin32 223 pywinpty 0.5.1 PyYAML 3.12 pyzmq 17.0.0 QtAwesome 0.4.4 qtconsole 4.3.1 QtPy 1.4.1 Quandl 3.4.6 regex 2019.8.19 requests 2.22.0 retrying 1.3.3 rope 0.10.7 ruamel-yaml 0.15.35 s3transfer 0.2.0 sacremoses 0.0.34 scikit-image 0.15.0 scikit-learn 0.19.1 scipy 1.2.2 seaborn 0.9.0 sec-edgar-downloader 2.2.1 Send2Trash 1.5.0 sentencepiece 0.1.83 setuptools 41.2.0 setuptools-git 1.2 shap 0.30.1 simplegeneric 0.8.1 SimpleITK 1.2.2 simplejson 3.16.0 singledispatch 3.4.0.3 six 1.11.0 smart-open 1.8.0 snowballstemmer 1.2.1 sortedcollections 0.6.1 sortedcontainers 1.5.10 spacy 2.1.3 Sphinx 1.7.4 sphinxcontrib-websupport 1.0.1 spyder 3.2.8 SQLAlchemy 1.2.7 sqlparse 0.3.0 srsly 0.0.5 statsmodels 0.9.0 sympy 1.1.1 tables 3.4.3 tb-nightly 1.14.0a20190301 tblib 1.3.2 tensorboard 2.0.0 tensorflow 2.0.0a0 tensorflow-datasets 1.2.0 tensorflow-estimator 1.13.0 tensorflow-gpu 1.13.1 tensorflow-metadata 0.14.0 tensorflow-probability 0.6.0 termcolor 1.1.0 terminado 0.8.1 testpath 0.3.1 tf-estimator-nightly 1.14.0.dev2019030115 tfds-nightly 1.2.0.dev201909050105 Theano 1.0.4 thinc 7.0.4 toml 0.10.0 toolz 0.9.0 torch 1.0.1 tornado 5.0.2 tox 3.8.6 tqdm 4.31.1 tradingeconomics 0.2.953 traitlets 4.3.2 transformers 2.0.0 translate 3.5.0 tsfresh 0.11.2 tushare 1.2.39 typing 3.6.4 unicodecsv 0.14.1 urllib3 1.22 virtualenv 16.4.3 wasabi 0.2.1 wcwidth 0.1.7 webencodings 0.5.1 websocket-client 0.56.0 Werkzeug 0.14.1 wheel 0.31.1 widgetsnbextension 3.2.1 win-inet-pton 1.0.1 win-unicode-console 0.5 wincertstore 0.2 wrapt 1.10.11 xarray 0.12.3 xgboost 0.82 xlrd 1.1.0 XlsxWriter 1.0.4 xlwings 0.11.8 xlwt 1.3.0 yahoo-finance 1.4.0 yahoofinancials 1.5 yfinance 0.1.45 zict 0.1.3 zipp 0.3.3 </code></pre>
0
14,268
Java Garbage Collector - Not running normally at regular intervals
<p>I have a program that is constantly running. Normally, it seems to garbage collect, and remain under about 8MB of memory usage. However, every weekend, it refuses to garbage collect unless I make an explicit call to it. However, if it nears the maximum heap size, it will still garbage collect. However the only reason this issue was noticed, is because it actually crashed from running out of memory on one weekend i.e. it must have reached the maximum heap size, and not run the garbage collector. </p> <p>The following image <a href="http://www.users.on.net/~rjl/memory.png" rel="noreferrer">(click to see)</a> is a graph of the program's memory usage over a day. On the sides of the graph, you can see the normal behaviour of the program's memory usage, but the first large peak is what seems to start over the weekend. This particular graph is a strange example, because after I made an explicit call to the garbage collector, it ran successfully, but then it went and climbed back to the maximum heap size and successfully garbage collected on it's own twice. </p> <p>What is going on here?</p> <p><strong>EDIT:</strong></p> <p>Ok, from the comments, it seems I haven't provided enough information. The program simply receives a stream of UDP packets, which are placed in a queue (set to have a maximum size of 1000 objects), which are then processed to have their data stored in a database. On average, it gets about 80 packets per second, but can peak to 150. It's running under Windows Server 2008. </p> <p>The thing is, this activity is fairly consistent, and if anything, at the time that the memory usage starts it's steady climb, the activity should be lower, not higher. Mind you, the graph I posted above is the only one I have that extends back that far, since I only changed the Java Visual VM wrapper to keep graph data back far enough to see it this week, so I have no idea if it's exactly the same time every week, because I can't watch it over the weekend, as it's on a private network, and I'm not at work on the weekend.</p> <p>Here is a graph of the next day: <img src="https://i.stack.imgur.com/iqAFd.png" alt="alt text"></p> <p>This is pretty much what the memory usage looks like every other day of the week. The program is never restarted, and we only tell it to garbage collect on a Monday morning because of this issue. One week we tried restarting it on a Friday afternoon, and it still started climbing sometime over the weekend, so the time that we restart it doesn't seem to have anything to do with the memory usage next week.</p> <p>The fact that it successfully garbage collects all those objects when we tell it to implies to me that the objects are collectable, it's just not doing it until it reaches the maximum heap size, or we explicitly call the garbage collector. A heap dump doesn't tell us anything, because when we try to perform one, it suddenly runs the garbage collector, and then outputs a heap dump, which of course looks perfectly normal at this point. </p> <p>So I suppose I have two questions: Why is it suddenly not garbage collecting the way it does the rest of the week, and why is it that on one occassion, the garbage collection that occurs when it reaches the maximum heap size was unable to collect all those objects (i.e. why would there be references to so many objects that one time, when every other time there must not be)? </p> <p>UPDATE:</p> <p>This morning has been an interesting one. As I mentioned in the comments, the program is running on a client's system. Our contact in the client organisation reports that at 1am, this program failed, and he had to restart it manually when he got into work this morning, and that once again, the server time was incorrect. This is an issue we've had with them in the past, but until now, the issue never seemed to be related.</p> <p>Looking through the logs that our program produces, we can deduce the following information:</p> <ol> <li>At 01:00, the server has somehow resynced it's time, setting it to 00:28. </li> <li>At 00:45 (according to the new, incorrect server time), one of the message processing threads in the program has thrown an out of memory error. </li> <li>However, the other message processing thread (there are two types of messages we receive, they are processed slightly differently, but they are both constantly coming in), continues to run, and as usual, the memory usage continues to climb with no garbage collection (as seen from the graphs we have been recording, once again).</li> <li>At 00:56, the logs stop, until about 7am when the program was restarted by our client. However, the memory usage graph, for this time, was still steadily increasing.</li> </ol> <p>Unfortunately, because of the change in server time, this makes the times on our memory usage graph unreliable. However, it seems to be that it tried to garbage collect, failed, increased the heap space to the maximum available size, and killed that thread all at once. Now that the maximum heap space has increased, it's happy to use all of it without performing a major garbage collection. </p> <p>So now I ask this: if the server time changes suddenly like it did, can that cause a problem with the garbage collection process? </p>
0
1,272
npm run dev script error
<p>I'm trying to follow a tutorial and i continue running into an error with has to do with the script. </p> <p>I've restarted the tutorial to try to make sure I didn't miss anything however I've hit the same road block. I'm on a mac in pycharm.</p> <p>So far in the tutorial (its off of udemy)we have installed the webpack-cli, webpack, and created a test.js file to see if importing and exporting modules work. </p> <p>test.js</p> <pre><code>console.log('imported module'); export default </code></pre> <p>Index.js</p> <pre><code>// Global app controller import num from './test'; console.log(`I imported ${num} from another module`); </code></pre> <p>package.json</p> <pre><code>{ "name": "forkify", "version": "1.0.0", "description": "forkify project", "main": "index.js", "dependencies": {}, "devDependencies": { "webpack": "^4.11.1", "webpack-cli": "^3.0.2" }, "scripts": { "dev": "webpack" }, "author": "Christopher Maltez", "license": "ISC" } </code></pre> <p>webpack.config.js</p> <pre><code>const path = require('path'); module.exports = { entry: './src/js/index.js', output: { path: path.resolve(__dirname,'dist/js'), filename: 'bundle.js' }, mode: 'development' }; </code></pre> <p>and here is the error log.</p> <pre><code>0 info it worked if it ends with ok 1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'run', 'dev' ] 2 info using npm@6.1.0 3 info using node@v8.11.2 4 verbose run-script [ 'predev', 'dev', 'postdev' ] 5 info lifecycle forkify@1.0.0~predev: forkify@1.0.0 6 info lifecycle forkify@1.0.0~dev: forkify@1.0.0 7 verbose lifecycle forkify@1.0.0~dev: unsafe-perm in lifecycle true 8 verbose lifecycle forkify@1.0.0~dev: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/chrismaltez/Desktop/pycharmprojects/UDEMY/JS-Udemy/Section 9: forkify/9-forkify-starter/node_modules/.bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Users/chrismaltez/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Library/Frameworks/Python.framework/Versions/3.5/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Users/chrismaltez/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/3.5/bin:/usr/local/mysql/bin/:/usr/local/mysql/bin/ 9 verbose lifecycle forkify@1.0.0~dev: CWD: /Users/chrismaltez/Desktop/pycharmprojects/UDEMY/JS-Udemy/Section 9: forkify/9-forkify-starter 10 silly lifecycle forkify@1.0.0~dev: Args: [ '-c', 'webpack' ] 11 info lifecycle forkify@1.0.0~dev: Failed to exec dev script 12 verbose stack Error: forkify@1.0.0 dev: `webpack` 12 verbose stack spawn ENOENT 12 verbose stack at ChildProcess.&lt;anonymous&gt; (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:48:18) 12 verbose stack at emitTwo (events.js:126:13) 12 verbose stack at ChildProcess.emit (events.js:214:7) 12 verbose stack at maybeClose (internal/child_process.js:925:16) 12 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5) 13 verbose pkgid forkify@1.0.0 14 verbose cwd /Users/chrismaltez/Desktop/pycharmprojects/UDEMY/JS-Udemy/Section 9: forkify/9-forkify-starter 15 verbose Darwin 17.5.0 16 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "dev" 17 verbose node v8.11.2 18 verbose npm v6.1.0 19 error file sh 20 error code ELIFECYCLE 21 error errno ENOENT 22 error syscall spawn 23 error forkify@1.0.0 dev: `webpack` 23 error spawn ENOENT 24 error Failed at the forkify@1.0.0 dev script. 24 error This is probably not a problem with npm. There is likely additional logging output above. 25 verbose exit [ 1, true ] </code></pre> <p>Here is a snippet of my file structure where I think is the problem. <a href="https://i.stack.imgur.com/nfyzx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nfyzx.png" alt="file structure"></a></p>
0
1,520
TypeError: __init__() takes 1 positional argument but 2 were given
<p>I am develop a simple rest api using Django 1.10 When I run my server and call app url I get an error:</p> <blockquote> <p>TypeError: <code>__init__()</code> takes 1 positional argument but 2 were given</p> </blockquote> <p>GET /demo/ HTTP/1.1" 500 64736</p> <h1>Traceback</h1> <pre><code>Environment: Request Method: GET Request URL: http://localhost:8000/demo/ Django Version: 1.10.4 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mydemoapp', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/aqib/DjangoProject/mydemoenv/lib/python3.5/site- packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/aqib/DjangoProject/mydemoenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/aqib/DjangoProject/mydemoenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /demo/ Exception Value: __init__() takes 1 positional argument but 2 were given </code></pre> <h1>models.py</h1> <pre><code>from django.db import models class ProfileModel(models.Model): name = models.CharField(max_length=30, blank=False, default='Your Name') address = models.CharField(max_length=100, blank=True) contact = models.IntegerField() def __str__(self): return '%s %s' % (self.name, self.address) </code></pre> <h1>views.py</h1> <pre><code>from django.shortcuts import render from rest_framework import viewsets from mydemoapp.models import ProfileModel from .serializers import ProfileSerializer class ProfileView(viewsets.ModelViewSet): profile = ProfileModel.objects.all() serializer_class = ProfileSerializer </code></pre> <h1>serializers.py</h1> <pre><code>from .models import ProfileModel from rest_framework import serializers class ProfileSerializer(serializers.ModelSerializer): class Meta: model = ProfileModel fields = ('name', 'address', 'contact') </code></pre> <h1>urls.py (Application Url)</h1> <pre><code>from django.conf.urls import url from mydemoapp import views urlpatterns = [ url(r'^$', views.ProfileView), ] </code></pre> <h1>urls.py (project url)</h1> <pre><code>from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^demo/', include('mydemoapp.urls')), ] </code></pre>
0
1,139
How do you use FirstOrDefault with Include?
<p>This works fine:</p> <pre><code>return Members .FirstOrDefault(m =&gt; m.Agreement.Equals(agreement)); </code></pre> <p>But this throws an exception if it doesn't find a match:</p> <pre><code> return Members .Include("Files") .FirstOrDefault(m =&gt; m.Agreement.Equals(agreement) &amp;&amp; !m.Files.Any(f =&gt; f.Status.Equals(12))); </code></pre> <p>So how can I get first/default (which may be null) when I'm using an Include?</p> <p>The exception is:</p> <blockquote> <p>Unexpected Exception at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.ConstantTranslator.TypedTranslate(ExpressionConverter parent, ConstantExpression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator<code>1.Translate(ExpressionConverter parent, Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.EqualsTranslator.TypedTranslate(ExpressionConverter parent, BinaryExpression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator</code>1.Translate(ExpressionConverter parent, Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input, DbExpressionBinding&amp; binding) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression&amp; source, DbExpressionBinding&amp; sourceBinding, DbExpression&amp; lambda) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)<br> at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator<code>1.Translate(ExpressionConverter parent, Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.NotTranslator.TypedTranslate(ExpressionConverter parent, UnaryExpression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator</code>1.Translate(ExpressionConverter parent, Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.BinaryTranslator.TypedTranslate(ExpressionConverter parent, BinaryExpression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator<code>1.Translate(ExpressionConverter parent, Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input, DbExpressionBinding&amp; binding) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression&amp; source, DbExpressionBinding&amp; sourceBinding, DbExpression&amp; lambda) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)<br> at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator</code>1.Translate(ExpressionConverter parent, Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.AggregateTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)<br> at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator<code>1.Translate(ExpressionConverter parent, Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.Convert()<br> at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable</code>1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery<code>1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__6() at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func</code>1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) at System.Data.Entity.Core.Objects.ObjectQuery<code>1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__5() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func</code>1 operation) at System.Data.Entity.Core.Objects.ObjectQuery<code>1.GetResults(Nullable</code>1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery<code>1.&lt;System.Collections.Generic.IEnumerable&lt;T&gt;.GetEnumerator&gt;b__0() at System.Data.Entity.Internal.LazyEnumerator</code>1.MoveNext() at System.Linq.Enumerable.Single[TSource](IEnumerable<code>1 source) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.&lt;GetElementFunction&gt;b__3[TResult](IEnumerable</code>1 sequence) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable<code>1 query, Expression queryRoot) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression) at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression) at System.Linq.Queryable.Count[TSource](IQueryable</code>1 source)</p> </blockquote>
0
2,636
Node events.js:174 throw er; // Unhandled 'error' event
<p>I get an error when requesting an API and it crashes on any win server. Can anybody help, please?</p> <p>This is part of my code:</p> <pre><code>app.get("/js/2806/api/products/getAllDrugs", (req, res) =&gt; { const connection = getDBConnection() const queryString = "SELECT * FROM tbl_drug"; connection.query(queryString, (err, rows, fields) =&gt; { if (err) { console.log("Failed to query for drugs: " + err); // res.sendStatus(500); res.json({ ErrorDetail: { code: -1, msg: err.code } }); res.end(); return } const drugs = rows.map((row) =&gt; { return { id: row.id, storeId: row.drugStoreId, drugName: row.drugName, description: row.drugDsc, drugUsing: row.drugUsing, drugDoseId: row.drugDoseId, categoryId: row.categoryId }; }) res.json({ ErrorDetail: { code: 0 }, Response: drugs }) }) }); </code></pre> <blockquote> <p>Error: Connection lost: The server closed the connection. at Protocol.end (C:\Users\Administrator\AppData\Local\CaptainCure\n s\mysql\lib\protocol\Protocol.js:112:13) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:97:28) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:502:10) at Socket.emit (events.js:194:15) at endReadableNT (_stream_readable.js:1125:12) at process._tickCallback (internal/process/next_tick.js:63:19) Emitted 'error' event at: at Connection._handleProtocolError (C:\Users\Administrator\AppData\ ainCure\node_modules\mysql\lib\Connection.js:425:8) at Protocol.emit (events.js:189:13) at Protocol._delegateError (C:\Users\Administrator\AppData\Local\Ca node_modules\mysql\lib\protocol\Protocol.js:390:10) at Protocol.end (C:\Users\Administrator\AppData\Local\CaptainCure\n s\mysql\lib\protocol\Protocol.js:116:8) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:97:28) I— lines matching original stack trace ...] at process._tickCallback Cinternal/process/next_tick.js:63:19> [nodemon I - wait in is (nodemon] si ing 'node app.js -erver is running on port: 3000 ode events.js:174 throw er; // Unhandled 'error' event is (nodemon] starting 'node app.js' -erver is running on port: 3000</p> </blockquote>
0
1,145
I am getting "code challenge required" when using IdentityServer4
<p>I am trying to redirect to IdentityServer for authorization, and getting "code challenge required" in redirect URL.</p> <p>An error message shows <strong>invalid_request</strong> with code challenge required, and also my redirect url <a href="http://localhost:44367/signin-oidc#error=invalid_request&amp;error_description=code%20challenge%20required&amp;state=CfDJ8Cq6lLUEMhZLqMhFVN" rel="noreferrer">http://localhost:44367/signin-oidc#error=invalid_request&amp;error_description=code%20challenge%20required&amp;state=CfDJ8Cq6lLUEMhZLqMhFVN</a></p> <p>Here is my client configuration:</p> <pre class="lang-cs prettyprint-override"><code>namespace TestClient { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure&lt;CookiePolicyOptions&gt;(options =&gt; { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context =&gt; true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddControllersWithViews(); ConfigureIdentityServer(services); services.AddCors(); } private void ConfigureIdentityServer(IServiceCollection services) { var builder = services.AddAuthentication(options =&gt; SetAuthenticationOptions(options)); services.AddMvcCore() .AddAuthorization(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); builder.AddCookie(); builder.AddOpenIdConnect(options =&gt; SetOpenIdConnectOptions(options)); } private void SetAuthenticationOptions(AuthenticationOptions options) { options.DefaultScheme = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectDefaults.AuthenticationScheme; } private void SetOpenIdConnectOptions(OpenIdConnectOptions options) { options.Authority = "https://localhost:44346"; options.ClientId = "TestIdentityServer"; options.RequireHttpsMetadata = false; options.Scope.Add("profile"); options.Scope.Add("openid"); options.Scope.Add("TestIdentityServer"); options.ResponseType = "code id_token"; options.SaveTokens = true; options.ClientSecret = "0b4168e4-2832-48ea-8fc8-7e4686b3620b"; } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. } app.UseHsts(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCors(builder =&gt; builder .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() ); app.UseCookiePolicy(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints =&gt; { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } } </code></pre> <p>And here is my IdentityService4 configuration</p> <pre class="lang-cs prettyprint-override"><code> public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { IdentityModelEventSource.ShowPII = true; services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt; options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity&lt;IdentityUser&gt;(options =&gt; options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;(); services.AddControllersWithViews(); services.AddRazorPages(); services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0); services.Configure&lt;IISOptions&gt;(iis =&gt; { iis.AuthenticationDisplayName = "Windows"; iis.AutomaticAuthentication = false; }); var builder = services.AddIdentityServer(options =&gt; { options.Events.RaiseErrorEvents = true; options.Events.RaiseInformationEvents = true; options.Events.RaiseFailureEvents = true; options.Events.RaiseSuccessEvents = true; }); // this adds the config data from DB (clients, resources) builder.AddInMemoryIdentityResources(Configuration.GetSection("IdentityResources")); builder.AddInMemoryApiResources(Configuration.GetSection("ApiResources")); builder.AddInMemoryClients(Configuration.GetSection("clients")); services.AddAuthentication(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. } app.UseHsts(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseIdentityServer(); app.UseEndpoints(endpoints =&gt; { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); } } </code></pre> <p>and appsettings.json</p> <pre class="lang-cs prettyprint-override"><code>"IdentityResources": [ { "Name": "openid", "DisplayName": "Your user identifier", "Required": true, "UserClaims": [ "sub" ] }, { "Name": "profile", "DisplayName": "User profile", "Description": "Your user profile information (first name, last name, etc.)", "Emphasize": true, "UserClaims": [ "name", "family_name", "given_name", "middle_name", "preferred_username", "profile", "picture", "website", "gender", "birthdate", "zoneinfo", "locale", "updated_at" ] } ], "ApiResources": [ { "Name": "TestIdentityServer", "DisplayName": "TestIdentityServer API Services", "Scopes": [ { "Name": "TestIdentityServer", "DisplayName": "TestIdentityServer API Services" } ] } ], "Clients": [ { "ClientId": "TestIdentityServer", "ClientName": "TestIdentityServer Credentials Client", // 511536EF-F270-4058-80CA-1C89C192F69A "ClientSecrets": [ { "Value": "entAuCGhsOQWRYBVx26BCgZxeMt/TqeVZzzpNJ9Ub1M=" } ], "AllowedGrantTypes": [ "hybrid" ], "AllowedScopes": [ "openid", "profile", "TestIdentityServer" ], "RedirectUris": [ "http://localhost:44367/signin-oidc" ], //"FrontChannelLogoutUris": [ "http://localhost:44367/Home/Privacy" ], //"PostLogoutRedirectUris": [ "http://localhost:44367/Home/Privacy" ], "redirect_uri": "http://localhost:44367/signin-oidc" } </code></pre>
0
4,006
Why is my code not CLS-compliant?
<p>I've got errors when I build my project:</p> <blockquote> <p>Warning as Error: Type of 'OthersAddresses.AddresseTypeParameter' is not CLS-compliant C:...\Units\OthersAddresses.ascx.cs</p> </blockquote> <pre><code>public Address.AddressTypeEnum AddressTypeParameter { get { return _addressTypeParameter; } set { _addressTypeParameter = value; } } </code></pre> <p>and this one:</p> <blockquote> <p>Warning as Error: Type of 'Global.UserInSession' is not CLS-compliant C:...\Global.asax.cs</p> </blockquote> <pre><code>public static User UserInSession { get { return (HttpContext.Current.Session["CurrentUser"] == null) ? null : HttpContext.Current.Session["CurrentUser"] as User; } set { HttpContext.Current.Session["CurrentUser"] = value; } } </code></pre> <hr> <p>I added attribute <code>[CLSCompliant(false)]</code> before <code>UserInSession</code> and <code>AddresseTypeParameter</code> and it works but I would like to understand why it was not CLS-compliant.</p> <p>Some more information about classes and enum:</p> <p><strong>Class User (User.cs)</strong></p> <pre><code>public class User { private string _uniqueIdentifier; private string _password = string.Empty; private string _email = string.Empty; private string _passwordQuestion = string.Empty; private string _passwordAnswer = string.Empty; private string _id_directions_db = string.Empty; private string _id_gesab = string.Empty; private string _zipCode = string.Empty; private string _fonction_id = string.Empty; private string _fonction = string.Empty; private string _structure_id = string.Empty; private string _structure = string.Empty; private string _firstName = string.Empty; private string _lastName = string.Empty; private string _company = string.Empty; private string _avatarPath = string.Empty; private Role _role = new Role(); private List&lt;Address&gt; _addressList = new List&lt;Address&gt;(); private string _otherInformation = string.Empty; private MembershipUser _membershipUserAssociated = null; ... public enum GenderEnum { Empty = 0, Monsieur, Madame } </code></pre> <p>And</p> <p><strong>enum AddressTypeEnum (Address.cs)</strong></p> <pre><code>public class Address { private AddressTypeEnum _addressType; private string _firstName = string.Empty; private string _lastName =string.Empty; private string _structure = string.Empty; private string _structureComplementary = string.Empty; private string _addressStreet = string.Empty; private string _addressComplementary = string.Empty; private string _bp = string.Empty; private string _zipCode = string.Empty; private string _country = string.Empty; private string _countryId = string.Empty; private string _city = string.Empty; private string _phone = string.Empty; private string _fax = string.Empty; private string _email = string.Empty; public enum AddressTypeEnum { Empty = 0, Personal = 1, Billing = 2, Delivery = 3 } </code></pre>
0
1,324
"invalid_grant error processing request" while making a reddit bot
<p>Im making a reddit bot that replies something to a specific comment.</p> <p>But Im getting this error : invalid_grant error processing request</p> <p>and I can't find the solution.</p> <p>here is my code, Im using Python.</p> <pre><code>import praw import time import config def login(): r = praw.Reddit(user_agent = "test bot", username = config.username, password = config.password, client_id = config.client_id, client_secret = config.client_secret) print("logged in") return r cache = [] def run_bot(r): subreddit = r.subreddit("Test") comments = subreddit.get_comments(limit=25) for comment in comments: comment_text = comment.body.lower() if "xD" in comment_text and comment.id not in cache: comment.reply("xD") cache.append(comment.id) while True: r = login() run_bot(r) time.sleep(5) </code></pre> <p>traceback:</p> <pre><code> logged in Traceback (most recent call last): File "xdbot.py", line 28, in &lt;module&gt; run_bot(r) File "xdbot.py", line 19, in run_bot comments = subreddit.get_comments(limit=25) File "D:\Programming\Phyton\lib\site-packages\praw\models\reddit\base.py", line 31, in __getattr__ self._fetch() File "D:\Programming\Phyton\lib\site-packages\praw\models\reddit\base.py", line 66, in _fetch params=self._info_params) File "D:\Programming\Phyton\lib\site-packages\praw\reddit.py", line 367, in get data = self.request('GET', path, params=params) File "D:\Programming\Phyton\lib\site-packages\praw\reddit.py", line 451, in request params=params) File "D:\Programming\Phyton\lib\site-packages\prawcore\sessions.py", line 174, in request params=params, url=url) File "D:\Programming\Phyton\lib\site-packages\prawcore\sessions.py", line 108, in _request_with_retries data, files, json, method, params, retries, url) File "D:\Programming\Phyton\lib\site-packages\prawcore\sessions.py", line 93, in _make_request params=params) File "D:\Programming\Phyton\lib\site-packages\prawcore\rate_limit.py", line 32, in call kwargs['headers'] = set_header_callback() File "D:\Programming\Phyton\lib\site-packages\prawcore\sessions.py", line 134, in _set_header_callback self._authorizer.refresh() File "D:\Programming\Phyton\lib\site-packages\prawcore\auth.py", line 328, in refresh password=self._password) File "D:\Programming\Phyton\lib\site-packages\prawcore\auth.py", line 142, in _request_token payload.get('error_description')) prawcore.exceptions.OAuthException: invalid_grant error processing request </code></pre>
0
1,044
Error: symbol(s) not found for architecture x86_64, collect2: ld returned 1 exit status
<p>I have been struggling for a while with an issue on Qt.</p> <p>Here is my code:</p> <p>hexbutton.h:</p> <pre><code>#ifndef HEXBUTTON_H #define HEXBUTTON_H #include &lt;QPushButton&gt; #include &lt;QWidget&gt; #include &lt;QIcon&gt; class HexButton : public QPushButton { Q_OBJECT public: HexButton(QWidget *parent, QIcon &amp;icon, int i, int j); public slots: void changeIcon(); }; #endif // HEXBUTTON_H </code></pre> <p>Hexbutton.cpp:</p> <pre><code>#include "hexbutton.h" HexButton::HexButton(QWidget *parent, QIcon &amp;icon, int i , int j) : QPushButton(parent){ //setFlat(true); setIcon(icon); setGeometry((i*40)+((j*40)/2), j*40, 40, 40); } void HexButton::changeIcon(){ setIcon(QIcon("/Users/jonathanbibas/Documents/Workspace Qt/Test/hexagon.gif")); } </code></pre> <p>MyWindow.h:</p> <pre><code>#ifndef MYWINDOW_H #define MYWINDOW_H #include &lt;QApplication&gt; #include &lt;QWidget&gt; #include &lt;QPushButton&gt; #include &lt;QLCDNumber&gt; #include &lt;QSlider&gt; #include &lt;QProgressBar&gt; #include "hexbutton.h" class MyWindow : public QWidget { public: MyWindow(); ~MyWindow(); private: HexButton * myButtons[11][11]; }; #endif // MYWINDOW_H </code></pre> <p>MyWindow.cpp:</p> <pre><code>#include "MyWindow.h" #include &lt;QColor&gt; #include &lt;QIcon&gt; MyWindow::MyWindow() : QWidget() { setFixedSize(740, 440); QIcon icon = QIcon("/Users/jonathanbibas/Documents/Workspace Qt/Test/whitehexagon.png"); for(int i =0 ; i &lt; 11 ; i ++){ for(int j =0 ; j &lt; 11 ; j ++){ myButtons[i][j] = new HexButton(this, icon, i, j); QObject::connect(myButtons[i][j], SIGNAL(clicked()), myButtons[i][j], SLOT(changeIcon())); } } } MyWindow::~MyWindow() { delete myButtons; } </code></pre> <p>And finally, Main.cpp:</p> <pre><code>#include &lt;QApplication&gt; #include "MyWindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); MyWindow fenetre; fenetre.show(); return app.exec(); } </code></pre> <p>Just in case, here is the Test.pro</p> <pre><code>SOURCES += \ Main.cpp \ MyWindow.cpp \ hexbutton.cpp HEADERS += \ MyWindow.h \ hexbutton.h </code></pre> <p>And I get the 2 errors:</p> <p>1) symbol(s) not found for architecture x86_64</p> <p>2) collect2: ld returned 1 exit status</p> <p>It also says 121 times (11*11):</p> <p>Object::connect: No such slot QPushButton::changeIcon() in ../Test/MyWindow.cpp:19</p> <p>and on the compile output it says:</p> <pre><code>18:22:15: Running build steps for project Test... 18:22:15: Configuration unchanged, skipping qmake step. 18:22:15: Starting: "/usr/bin/make" -w make: Entering directory `/Users/jonathanbibas/Documents/Workspace Qt/Test-build-desktop-Desktop_Qt_4_8_0_for_GCC__Qt_SDK__Debug' g++ -c -pipe -g -gdwarf-2 -arch x86_64 -Xarch_x86_64 -mmacosx-version-min=10.5 -Wall -W -DQT_GUI_LIB -DQT_CORE_LIB -I../../../QtSDK/Desktop/Qt/4.8.0/gcc/mkspecs/macx-g++ -I../Test -I../../../QtSDK/Desktop/Qt/4.8.0/gcc/lib/QtCore.framework/Versions/4/Headers -I../../../QtSDK/Desktop/Qt/4.8.0/gcc/include/QtCore -I../../../QtSDK/Desktop/Qt/4.8.0/gcc/lib/QtGui.framework/Versions/4/Headers -I../../../QtSDK/Desktop/Qt/4.8.0/gcc/include/QtGui -I../../../QtSDK/Desktop/Qt/4.8.0/gcc/include -I. -I../Test -I. -F/Users/jonathanbibas/QtSDK/Desktop/Qt/4.8.0/gcc/lib -o hexbutton.o ../Test/hexbutton.cpp g++ -headerpad_max_install_names -arch x86_64 -Xarch_x86_64 -mmacosx-version-min=10.5 -o Test.app/Contents/MacOS/Test Main.o MyWindow.o hexbutton.o moc_MyWindow.o -F/Users/jonathanbibas/QtSDK/Desktop/Qt/4.8.0/gcc/lib -L/Users/jonathanbibas/QtSDK/Desktop/Qt/4.8.0/gcc/lib -framework QtGui -framework QtCore Undefined symbols for architecture x86_64: "vtable for HexButton", referenced from: HexButton::HexButton(QWidget*, QIcon&amp;, int, int)in hexbutton.o HexButton::HexButton(QWidget*, QIcon&amp;, int, int)in hexbutton.o NOTE: a missing vtable usually means the first non-inline virtual member function has no definition. ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status make: *** [Test.app/Contents/MacOS/Test] Error 1 make: Leaving directory `/Users/jonathanbibas/Documents/Workspace Qt/Test-build-desktop-Desktop_Qt_4_8_0_for_GCC__Qt_SDK__Debug' 18:22:20: The process "/usr/bin/make" exited with code 2. Error while building project Test (target: Desktop) When executing build step 'Make' </code></pre> <p>Apparently the error comes from the Q_OBJECT (needed for the slots definition), but there is something wrong with my code, not with my compiler (because I have when slots are in MainWindow, it works fine).</p> <p>Thank you for your help!</p>
0
2,055
Problem running tests with enabled preview features in surefire and failsafe
<p>I'm trying to migrate a project to Java 12, with <code>--enable-preview</code>.</p> <p>I added <code>--enable-preview</code> in compiler settings:</p> <pre><code> &lt;plugin&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.8.0&lt;/version&gt; &lt;configuration&gt; &lt;release&gt;12&lt;/release&gt; &lt;compilerArgs&gt; &lt;arg&gt;--enable-preview&lt;/arg&gt; &lt;/compilerArgs&gt; &lt;/configuration&gt; &lt;/plugin&gt; </code></pre> <p>And also added it in argLine for surefire and failsafe:</p> <pre><code>&lt;properties&gt; &lt;argLine&gt;--enable-preview&lt;/argLine&gt; &lt;/properties&gt; </code></pre> <p>And do a <code>mvn clean verify</code> results in:</p> <pre><code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.0.0-M3:test (default-test) on project lombok-jdk10: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:3.0.0-M3:test failed: java.lang.UnsupportedClassVersionError: Preview features are not enabled for com/kirela/lombok/BarTest (class file version 56.65535). Try running with '--enable-preview' -&gt; [Help 1] </code></pre> <p>I also tried adding argLine directly to surefire/failsafe configuration, but the result is same.</p> <p>What am I missing here?</p> <p>I this a bug in surefire/failsafe?</p> <p>EDIT2: Surefire and failsafe config:</p> <pre><code> &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;3.0.0-M3&lt;/version&gt; &lt;configuration&gt; &lt;forkCount&gt;2&lt;/forkCount&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt; &lt;version&gt;3.0.0-M3&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;integration-test&lt;/goal&gt; &lt;goal&gt;verify&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;configuration&gt; &lt;forkCount&gt;2&lt;/forkCount&gt; &lt;/configuration&gt; &lt;/plugin&gt; </code></pre> <p>EDIT3: Minimal working example is here: <a href="https://github.com/krzyk/lombok-jdk10-example" rel="noreferrer">https://github.com/krzyk/lombok-jdk10-example</a></p> <p>The project fails with <code>--enable-preview</code>, but works when I remove it.</p>
0
3,158
JPA - Increment a numeric field through a sequence programmatically
<p>I have a JPA 2 web application (Struts 2, Hibernate 4 as JPA implementation only).</p> <p>The current requirement is to add a (non-id) numeric sequential field, filled for certain rows only, to an existing entity. When inserting a new row, based on a certain condition, I need to set the new field to <code>its highest value + 1</code> or to <code>NULL</code>.</p> <p>For example:</p> <pre><code>ID NEW_FIELD DESCRIPTION -------------------------------- 1 1 bla bla 2 bla bla &lt;--- unmatched: not needed here 3 bla bla &lt;--- unmatched: not needed here 4 2 bla bla 5 3 bla bla 6 4 bla bla 7 bla bla &lt;--- unmatched: not needed here 8 5 bla bla 9 bla bla &lt;--- unmatched: not needed here 10 6 bla bla </code></pre> <p>In the good old SQL, it would be something like: </p> <pre class="lang-sql prettyprint-override"><code>INSERT INTO myTable ( id, new_field, description ) VALUES ( myIdSequence.nextVal, (CASE myCondition WHEN true THEN myNewFieldSequence.nextVal ELSE NULL END), 'Lorem Ipsum and so on....' ) </code></pre> <p>But I've no clue on how to achieve it with JPA 2.</p> <p>I know I can define callbacks methods, but <a href="http://download.oracle.com/otndocs/jcp/persistence-2.0-fr-eval-oth-JSpec/" rel="nofollow noreferrer">JSR-000317 Persistence Specification for Eval 2.0 Eval</a> discourages some specific operations from inside it:</p> <blockquote> <p><strong> 3.5 Entity Listeners and Callback Methods</strong><br/> <sub> - Lifecycle callbacks can invoke JNDI, JDBC, JMS, and enterprise beans. </sub><br/> <sub> - In general, the lifecycle method of a portable application <strong>should not invoke EntityManager or Query operations, access other entity instances, or modify relationships within the same persistence context</strong>.<sup>[43]</sup> A lifecycle callback method may modify the non-relationship state of the entity on which it is invoked.</sub></p> <p><sup>[43]</sup> <sub>The semantics of such operations may be standardized in a future release of this specification.</sub></p> </blockquote> <p>Summarizing, yes to JDBC (!) and EJB, no to EntityManager and other Entities.</p> <hr> <h1>EDIT</h1> <p>I'm trying to achieve the solution described in the answer from @anttix, but I'm encoutering some problem, so please correct me where I'm wrong.</p> <p><strong>Table</strong></p> <pre><code>MyTable ------------------------- ID number (PK) NEW_FIELD number DESCRIPTION text </code></pre> <p><strong>Main Entity</strong></p> <pre><code>@Entity @Table(name="MyTable") public class MyEntity implements Serializable { @Id @SequenceGenerator(name="seq_id", sequenceName="seq_id", allocationSize=1) @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_id") private Long id; @OneToOne(cascade= CascadeType.PERSIST) private FooSequence newField; private String description /* Getters and Setters */ } </code></pre> <p><strong>Sub entity</strong></p> <pre><code>@Entity public class FooSequence { @Id @SequenceGenerator(name="seq_foo", sequenceName="seq_foo", allocationSize=1) @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_foo") private Long value; /* Getter and Setter */ } </code></pre> <p><strong>DAO</strong></p> <pre><code>myEntity.setNewField(new FooSequence()); entityManager.persist(myEntity); </code></pre> <p><strong>Exception</strong></p> <blockquote> <p>Caused by: javax.transaction.RollbackException: ARJUNA016053: Could not commit transaction.</p> <p>[...]</p> <p>Caused by: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: ERROR: relation "new_field" does not exist</p> <p>[...]</p> <p>Caused by: org.hibernate.exception.SQLGrammarException: ERROR: relation "new_field" does not exist</p> <p>[...]</p> <p>Caused by: org.postgresql.util.PSQLException: ERROR: relation "new_field" does not exist</p> </blockquote> <p>What am I doing wrong ? I'm pretty new to JPA 2 and I've never used an entity not associated to a physical table... this approach is totally new to me. </p> <p>I guess I need to put the <code>@Column</code> definition somewhere: how could JPA possibly know that the <code>newField</code> column (mapped through <a href="https://stackoverflow.com/a/19454829/1654265">ImprovedNamingStrategy</a> to <code>new_field</code> on the database) is retrieved through the <code>value</code> property of the <code>FooSequence</code> entity ?</p> <p>Some pieces of the puzzle are missing.</p> <hr> <p><strong>EDIT</strong> </p> <p>As asked in comments, this is the <code>persistence.xml</code>:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"&gt; &lt;persistence-unit name="MyService" transaction-type="JTA"&gt; &lt;jta-data-source&gt;java:jboss/datasources/myDS&lt;/jta-data-source&gt; &lt;properties&gt; &lt;property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" /&gt; &lt;property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/&gt; &lt;property name="hibernate.query.substitutions" value="true 'Y', false 'N'"/&gt; &lt;property name="hibernate.show_sql" value="true" /&gt; &lt;property name="format_sql" value="true" /&gt; &lt;property name="use_sql_comments" value="true" /&gt; &lt;/properties&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </code></pre>
0
2,513
AngularJS Two-way Data Binding in Nested Directives
<p>Please let me know if you need more information or want me to clarify anything. I have tried a lot of different things to figure this out but haven't found a solution.</p> <p>I'm relatively new to angularJS and I am trying to build an app with several layers of data. I have some basic user information stored in the scope of the body on controller PageController. I then have a settings form that loads in using $routeParams (with controller SettingsController) that includes a couple of custom directives for templating purposes. Since the directives are nested, I am using transclusion to load the second one inside of the first. This all seems to be working alright.</p> <p>My problem is that I am trying to reference the field <code>user.firstname</code> from within the innermost directive and want to use two-way databinding to allow changes made to the textbox to cause the value at the PageController scope to change as well. I know that a lot of these kinds of problems are caused by using primitives in ng-model, but I have tried putting everything within an extra object so that I trigger prototypal inheritance to no avail. What am I doing wrong here?</p> <p>Here's a <a href="http://jsfiddle.net/CxNc2/">JSFiddle</a> of my code, stripped down as much as possible to isolate the problem. In this example, if I type in the outside textbox, which is directly on the PageController scope, it will modify the inner textbox until that textbox is modified, upon which the connection is broken. This seems just like the problem of using primitives as described in other questions, but I can't figure out where the issue is here.</p> <p><em>HTML:</em></p> <pre><code>&lt;body class="event-listing" ng-app="app" ng-controller="PageController"&gt; &lt;div class="listing-event-wrap"&gt; &lt;input type="text" ng-model="user.firstname" /&gt; &lt;div ng-controller="SettingsController"&gt; &lt;section block title="{{data.updateInfo.title}}" description="{{data.updateInfo.description}}"&gt; &lt;div formrow label="{{data.updateInfo.labels.firstname}}" type="textInput" value="user.firstname"&gt;&lt;/div&gt; &lt;/section&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p><em>Angular Directives:</em></p> <pre><code>app.directive('formrow', function() { return { scope: { label: "@label", type: "@type", value: "=value" }, replace: true, template: '&lt;div class="form-row"&gt;' + '&lt;div class="form-label" data-ng-show="label"&gt;{{label}}&lt;/div&gt;' + '&lt;div class="form-entry" ng-switch on="type"&gt;' + '&lt;input type="text" ng-model="value" data-ng-switch-when="textInput" /&gt;' + '&lt;/div&gt;' + '&lt;/div&gt;' } }); app.directive('block', function() { return { scope: { title: "@title", description: "@description" }, transclude: true, replace: true, template: '&lt;div class="page-block"&gt;' + '&lt;h2 data-ng-show="title"&gt;{{title}}&lt;/h2&gt;' + '&lt;p class="form-description" data-ng-show="description"&gt;{{description}}&lt;/p&gt;' + '&lt;div class="block-inside" data-ng-transclude&gt;&lt;/div&gt;' + '&lt;/div&gt;' } }); </code></pre> <p><em>Angular Controllers:</em></p> <pre><code>app.controller("PageController", function($scope) { $scope.user = { firstname: "John" }; }); app.controller("SettingsController", function($scope) { $scope.data = { updateInfo: { title: "Update Your Information", description: "A description here", labels: { firstname: "First Name" } } } }); </code></pre>
0
1,476
PyTorch: DecoderRNN: RuntimeError: input must have 3 dimensions, got 2
<p>I am building a DecoderRNN using PyTorch (This is an image-caption decoder):</p> <pre><code>class DecoderRNN(nn.Module): def __init__(self, embed_size, hidden_size, vocab_size): super(DecoderRNN, self).__init__() self.hidden_size = hidden_size self.gru = nn.GRU(embed_size, hidden_size, hidden_size) self.softmax = nn.LogSoftmax(dim=1) def forward(self, features, captions): print (features.shape) print (captions.shape) output, hidden = self.gru(features, captions) output = self.softmax(self.out(output[0])) return output, hidden </code></pre> <p>The data have the following shapes:</p> <pre><code>torch.Size([10, 200]) &lt;- features.shape (10 for batch size) torch.Size([10, 12]) &lt;- captions.shape (10 for batch size) </code></pre> <p>Then I got the following errors. Any ideas what I missed here? Thanks!</p> <pre><code>--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) &lt;ipython-input-2-76e05ba08b1d&gt; in &lt;module&gt;() 44 # Pass the inputs through the CNN-RNN model. 45 features = encoder(images) ---&gt; 46 outputs = decoder(features, captions) 47 48 # Calculate the batch loss. /opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 323 for hook in self._forward_pre_hooks.values(): 324 hook(self, input) --&gt; 325 result = self.forward(*input, **kwargs) 326 for hook in self._forward_hooks.values(): 327 hook_result = hook(self, input, result) /home/workspace/model.py in forward(self, features, captions) 37 print (captions.shape) 38 # features = features.unsqueeze(1) ---&gt; 39 output, hidden = self.gru(features, captions) 40 output = self.softmax(self.out(output[0])) 41 return output, hidden /opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 323 for hook in self._forward_pre_hooks.values(): 324 hook(self, input) --&gt; 325 result = self.forward(*input, **kwargs) 326 for hook in self._forward_hooks.values(): 327 hook_result = hook(self, input, result) /opt/conda/lib/python3.6/site-packages/torch/nn/modules/rnn.py in forward(self, input, hx) 167 flat_weight=flat_weight 168 ) --&gt; 169 output, hidden = func(input, self.all_weights, hx) 170 if is_packed: 171 output = PackedSequence(output, batch_sizes) /opt/conda/lib/python3.6/site-packages/torch/nn/_functions/rnn.py in forward(input, *fargs, **fkwargs) 383 return hack_onnx_rnn((input,) + fargs, output, args, kwargs) 384 else: --&gt; 385 return func(input, *fargs, **fkwargs) 386 387 return forward /opt/conda/lib/python3.6/site-packages/torch/autograd/function.py in _do_forward(self, *input) 326 self._nested_input = input 327 flat_input = tuple(_iter_variables(input)) --&gt; 328 flat_output = super(NestedIOFunction, self)._do_forward(*flat_input) 329 nested_output = self._nested_output 330 nested_variables = _unflatten(flat_output, self._nested_output) /opt/conda/lib/python3.6/site-packages/torch/autograd/function.py in forward(self, *args) 348 def forward(self, *args): 349 nested_tensors = _map_variable_tensor(self._nested_input) --&gt; 350 result = self.forward_extended(*nested_tensors) 351 del self._nested_input 352 self._nested_output = result /opt/conda/lib/python3.6/site-packages/torch/nn/_functions/rnn.py in forward_extended(self, input, weight, hx) 292 hy = tuple(h.new() for h in hx) 293 --&gt; 294 cudnn.rnn.forward(self, input, hx, weight, output, hy) 295 296 self.save_for_backward(input, hx, weight, output) /opt/conda/lib/python3.6/site-packages/torch/backends/cudnn/rnn.py in forward(fn, input, hx, weight, output, hy) 206 if (not is_input_packed and input.dim() != 3) or (is_input_packed and input.dim() != 2): 207 raise RuntimeError( --&gt; 208 'input must have 3 dimensions, got {}'.format(input.dim())) 209 if fn.input_size != input.size(-1): 210 raise RuntimeError('input.size(-1) must be equal to input_size. Expected {}, got {}'.format( RuntimeError: input must have 3 dimensions, got 2 </code></pre>
0
2,100
Django /admin/ Page not found (404)
<p>I have the following error:</p> <pre><code>Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Raised by: nw.views.post_detail </code></pre> <p>But I can enter in example to <a href="http://127.0.0.1:8000/admin/nw/" rel="nofollow noreferrer">http://127.0.0.1:8000/admin/nw/</a></p> <p>And if I remove all <code>post_detail</code> functions/parts of the code then I can enter to <a href="http://127.0.0.1:8000/admin/" rel="nofollow noreferrer">http://127.0.0.1:8000/admin/</a> and it works, so something with this <code>post_detail</code> is wrong.</p> <p><strong>nw.views.post_detail:</strong></p> <pre><code>def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) context = { &quot;instance&quot;: instance, } return render(request, &quot;post_detail.html&quot;, context) </code></pre> <p><strong>urls.py:</strong></p> <pre><code>urlpatterns = [ url(r'', include('nw.urls', namespace='posts')), url(r'^admin/', admin.site.urls), ] </code></pre> <p>and</p> <pre><code>urlpatterns = [ url(r'^$', post_list, name='list'), url(r'^create/$', post_create), url(r'^(?P&lt;slug&gt;[\w-]+)/$', post_detail, name='detail'), url(r'^(?P&lt;slug&gt;[\w-]+)/edit/$', post_update, name='update'), url(r'^(?P&lt;slug&gt;[\w-]+)/delete/$', post_delete), ] </code></pre> <p><strong>post_detail.html:</strong></p> <pre><code>{% extends 'base.html' %} {% block head_title %}{{ instance.title }} | {{ block.super }}{% endblock head_title %} {% block content %} &lt;div class=&quot;instance&quot;&gt; &lt;h1&gt;{{ instance.title }}&lt;/h1&gt; &lt;div class=&quot;date&quot;&gt;{{ instance.published }}&lt;/div&gt; &lt;p&gt;{{ instance.text|linebreaksbr }}&lt;/p&gt; &lt;a href=&quot;https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}&quot;&gt; Facebook &lt;/a&gt; &lt;a href=&quot;https://twitter.com/home?status={{ share_string }}%20{{ request.build_absolute_uri }}&quot;&gt; Twitter &lt;/a&gt; &lt;a href='https://plus.google.com/share?url={{ request.build_absolute_uri }}'&gt;google&lt;/a&gt; &lt;a href=&quot;https://www.linkedin.com/shareArticle?mini=true&amp;url={{ request.build_absolute_uri }}&amp;title={{ instance.title }}&amp;summary={{ share_string }}&amp;source={{ request.build_absolute_uri }}&quot;&gt; Linkedin &lt;/a&gt; &lt;a href=&quot;http://www.reddit.com/submit?url={{ request.build_absolute_uri }}&amp;title={{ share_string }}.&quot;&gt;Reddit&lt;/a&gt; &lt;/div&gt; {% endblock %} </code></pre> <p><strong>models.py:</strong></p> <pre><code>class Post(models.Model): author = models.ForeignKey('auth.User', default=1) title = models.CharField(max_length=200) slug = models.SlugField(unique=True) text = models.TextField() published = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return self.title def get_absolute_url(self): return reverse(&quot;posts:detail&quot;, kwargs={&quot;slug&quot;: self.slug}) class Meta: ordering = [&quot;-published&quot;] def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Post.objects.filter(slug=slug).order_by(&quot;-id&quot;) exists = qs.exists() if exists: new_slug = &quot;%s-%s&quot; %(slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, sender=Post) </code></pre>
0
1,719
Using shared_from_this in templated classes
<p>I have a resource manager that, like Andrei Alexandrescu proposed in the book Modern C++ Design, follows a policy based design. I am having trouble though, because my resource manager needs to be able to provide references to itself to the managed resources by <code>shared_from_this()</code>.</p> <p>I built a minimal example reproducing my problem, which results you can see <a href="http://ideone.com/VbJo3f" rel="noreferrer">here</a>.</p> <p>Basically I have some managed resource that needs a reference to its manager:</p> <pre><code>template &lt;typename T&gt; class managed_resource { typedef std::shared_ptr&lt;manager&lt;T&gt;&gt; manager_ptr; public: managed_resource(manager_ptr const &amp; parent) : parent_(parent) { } /* ... */ private: manager_ptr parent_; }; </code></pre> <p>And a manager that stores and provides resources:</p> <pre><code>template &lt;typename Policy&gt; class manager : Policy , std::enable_shared_from_this&lt;manager&lt;Policy&gt;&gt; { typedef managed_resource&lt;Policy&gt; resource; typedef std::shared_ptr&lt;resource&gt; resource_ptr; public: resource_ptr get_resource(std::string const &amp; name) { Policy &amp; p = *this; if(p.find(name)) { return p.get(name); } resource_ptr res = std::make_shared&lt;resource&gt;(shared_from_this()); p.store(name, res); return res; } }; </code></pre> <p>As you can see, the storing itself is policy-based. While the manager does create the resources, the policy can freely decide between various approaches of storing the information (it could e.g. choose to not store anything and create new resources every time).</p> <p>This is an example of a storage policy:</p> <pre><code>class map_policy { typedef std::shared_ptr&lt;managed_resource&lt;map_policy&gt;&gt; resource_ptr; typedef std::map&lt;std::string, resource_ptr&gt; resources; public: bool find(std::string const &amp; name) { resources::iterator res_it = resources_.find(name); return res_it != resources_.end(); } resource_ptr get(std::string const &amp; name) { resources::iterator res_it = resources_.find(name); return res_it-&gt;second; } void store(std::string const &amp; name, resource_ptr const &amp; res) { resources_[name] = res; } private: resources resources_; }; </code></pre> <p>But I get a compilation error:</p> <pre><code>error: there are no arguments to ‘shared_from_this’ that depend on a template parameter, so a declaration of ‘shared_from_this’ must be available error: ‘std::enable_shared_from_this&lt;manager&lt;map_policy&gt; &gt;’ is an inaccessible base of ‘manager&lt;map_policy&gt;’ </code></pre> <p>For full compilation output see the <a href="http://ideone.com/VbJo3f" rel="noreferrer">minimal example</a>.</p> <p>Is it impossible to use <code>std::enable_shared_from_this</code> and <code>shared_from_this()</code> within policy based design? If not, what is the proper way of using it?</p>
0
1,321
Material UI Table not being responsive while using example Responsive Drawer
<p>I have created a web app with the base coming from the Material-UI Example on a <a href="https://material-ui.com/demos/drawers/#responsive-drawer" rel="noreferrer">responsive drawer</a></p> <p>I am trying to get a table to resize responsively to the screen width, but, for some reason, the <code>ResponsiveDrawer</code> container provided by Material-UI is breaking the responsiveness of the contents (i.e. the table)</p> <p><a href="https://codesandbox.io/s/2wq4jp557n" rel="noreferrer">Here is an example</a> that I wrote that is perfectly responsive:</p> <p><strong>App.js</strong></p> <pre><code>import React from "react"; import ReactDOM from "react-dom"; import Table from "@material-ui/core/Table/Table"; import TableHead from "@material-ui/core/TableHead/TableHead"; import TableRow from "@material-ui/core/TableRow/TableRow"; import TableCell from "@material-ui/core/TableCell/TableCell"; import TableBody from "@material-ui/core/TableBody/TableBody"; import Paper from "@material-ui/core/Paper/Paper"; import Grid from "@material-ui/core/Grid/Grid"; import "./styles.css"; function App() { return ( &lt;div className="App"&gt; &lt;Grid container justify={"center"}&gt; &lt;Grid item xs={12} md={10} style={{ padding: "8px" }}&gt; &lt;Paper style={{ overflowX: "auto" }}&gt; &lt;Table style={{ minWidth: "340px" }}&gt; &lt;TableHead&gt; &lt;TableRow&gt; &lt;TableCell&gt;Name&lt;/TableCell&gt; &lt;TableCell&gt;Column&lt;/TableCell&gt; &lt;TableCell&gt;Operating System&lt;/TableCell&gt; &lt;TableCell&gt;Status&lt;/TableCell&gt; &lt;TableCell&gt;CPU Cores&lt;/TableCell&gt; &lt;TableCell&gt;Memory (MB)&lt;/TableCell&gt; &lt;TableCell&gt;IP Address&lt;/TableCell&gt; &lt;/TableRow&gt; &lt;/TableHead&gt; &lt;TableBody&gt; &lt;TableRow&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;/TableRow&gt; &lt;/TableBody&gt; &lt;/Table&gt; &lt;/Paper&gt; &lt;/Grid&gt; &lt;/Grid&gt; &lt;/div&gt; ); } const rootElement = document.getElementById("root"); ReactDOM.render(&lt;App /&gt;, rootElement); </code></pre> <p>And <a href="https://codesandbox.io/s/wwlj1jq565" rel="noreferrer">here is that same example</a> using a modified (changed the content to <code>this.props.children</code> instead of static) version of Material-UI's <code>ResponsiveDrawer</code></p> <p><strong>ResponsiveDrawer.js</strong></p> <pre><code>import React from "react"; import PropTypes from "prop-types"; import AppBar from "@material-ui/core/AppBar"; import CssBaseline from "@material-ui/core/CssBaseline"; import Divider from "@material-ui/core/Divider"; import Drawer from "@material-ui/core/Drawer"; import Hidden from "@material-ui/core/Hidden"; import IconButton from "@material-ui/core/IconButton"; import InboxIcon from "@material-ui/icons/MoveToInbox"; import List from "@material-ui/core/List"; import ListItem from "@material-ui/core/ListItem"; import ListItemIcon from "@material-ui/core/ListItemIcon"; import ListItemText from "@material-ui/core/ListItemText"; import MailIcon from "@material-ui/icons/Mail"; import MenuIcon from "@material-ui/icons/Menu"; import Toolbar from "@material-ui/core/Toolbar"; import Typography from "@material-ui/core/Typography"; import { withStyles } from "@material-ui/core/styles"; const drawerWidth = 240; const styles = theme =&gt; ({ root: { display: "flex" }, drawer: { [theme.breakpoints.up("sm")]: { width: drawerWidth, flexShrink: 0 } }, appBar: { marginLeft: drawerWidth, [theme.breakpoints.up("sm")]: { width: `calc(100% - ${drawerWidth}px)` } }, menuButton: { marginRight: 20, [theme.breakpoints.up("sm")]: { display: "none" } }, toolbar: theme.mixins.toolbar, drawerPaper: { width: drawerWidth }, content: { flexGrow: 1, padding: theme.spacing.unit * 3 } }); class ResponsiveDrawer extends React.Component { state = { mobileOpen: false }; handleDrawerToggle = () =&gt; { this.setState(state =&gt; ({ mobileOpen: !state.mobileOpen })); }; render() { const { classes, theme } = this.props; const drawer = ( &lt;div&gt; &lt;div className={classes.toolbar} /&gt; &lt;Divider /&gt; &lt;List&gt; {["Inbox", "Starred", "Send email", "Drafts"].map((text, index) =&gt; ( &lt;ListItem button key={text}&gt; &lt;ListItemIcon&gt; {index % 2 === 0 ? &lt;InboxIcon /&gt; : &lt;MailIcon /&gt;} &lt;/ListItemIcon&gt; &lt;ListItemText primary={text} /&gt; &lt;/ListItem&gt; ))} &lt;/List&gt; &lt;Divider /&gt; &lt;List&gt; {["All mail", "Trash", "Spam"].map((text, index) =&gt; ( &lt;ListItem button key={text}&gt; &lt;ListItemIcon&gt; {index % 2 === 0 ? &lt;InboxIcon /&gt; : &lt;MailIcon /&gt;} &lt;/ListItemIcon&gt; &lt;ListItemText primary={text} /&gt; &lt;/ListItem&gt; ))} &lt;/List&gt; &lt;/div&gt; ); return ( &lt;div className={classes.root}&gt; &lt;CssBaseline /&gt; &lt;AppBar position="fixed" className={classes.appBar}&gt; &lt;Toolbar&gt; &lt;IconButton color="inherit" aria-label="Open drawer" onClick={this.handleDrawerToggle} className={classes.menuButton} &gt; &lt;MenuIcon /&gt; &lt;/IconButton&gt; &lt;Typography variant="h6" color="inherit" noWrap&gt; Responsive drawer &lt;/Typography&gt; &lt;/Toolbar&gt; &lt;/AppBar&gt; &lt;nav className={classes.drawer}&gt; {/* The implementation can be swapped with js to avoid SEO duplication of links. */} &lt;Hidden smUp implementation="css"&gt; &lt;Drawer container={this.props.container} variant="temporary" anchor={theme.direction === "rtl" ? "right" : "left"} open={this.state.mobileOpen} onClose={this.handleDrawerToggle} classes={{ paper: classes.drawerPaper }} &gt; {drawer} &lt;/Drawer&gt; &lt;/Hidden&gt; &lt;Hidden xsDown implementation="css"&gt; &lt;Drawer classes={{ paper: classes.drawerPaper }} variant="permanent" open &gt; {drawer} &lt;/Drawer&gt; &lt;/Hidden&gt; &lt;/nav&gt; &lt;main className={classes.content}&gt; &lt;div className={classes.toolbar} /&gt; {this.props.children} &lt;/main&gt; &lt;/div&gt; ); } } ResponsiveDrawer.propTypes = { classes: PropTypes.object.isRequired, // Injected by the documentation to work in an iframe. // You won't need it on your project. container: PropTypes.object, theme: PropTypes.object.isRequired }; export default withStyles(styles, { withTheme: true })(ResponsiveDrawer); </code></pre> <p><strong>App.js</strong></p> <pre><code>import React from "react"; import ReactDOM from "react-dom"; import Table from "@material-ui/core/Table/Table"; import TableHead from "@material-ui/core/TableHead/TableHead"; import TableRow from "@material-ui/core/TableRow/TableRow"; import TableCell from "@material-ui/core/TableCell/TableCell"; import TableBody from "@material-ui/core/TableBody/TableBody"; import Paper from "@material-ui/core/Paper/Paper"; import ResponsiveDrawer from "./ResponsiveDrawer"; import Grid from "@material-ui/core/Grid/Grid"; import "./styles.css"; function App() { return ( &lt;div className="App"&gt; &lt;ResponsiveDrawer&gt; &lt;Grid container justify={"center"}&gt; &lt;Grid item xs={12} md={10} style={{ padding: "8px" }}&gt; &lt;Paper style={{ overflowX: "auto" }}&gt; &lt;Table style={{ minWidth: "340px" }}&gt; &lt;TableHead&gt; &lt;TableRow&gt; &lt;TableCell&gt;Name&lt;/TableCell&gt; &lt;TableCell&gt;Column&lt;/TableCell&gt; &lt;TableCell&gt;Operating System&lt;/TableCell&gt; &lt;TableCell&gt;Status&lt;/TableCell&gt; &lt;TableCell&gt;CPU Cores&lt;/TableCell&gt; &lt;TableCell&gt;Memory (MB)&lt;/TableCell&gt; &lt;TableCell&gt;IP Address&lt;/TableCell&gt; &lt;/TableRow&gt; &lt;/TableHead&gt; &lt;TableBody&gt; &lt;TableRow&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;TableCell&gt;Content&lt;/TableCell&gt; &lt;/TableRow&gt; &lt;/TableBody&gt; &lt;/Table&gt; &lt;/Paper&gt; &lt;/Grid&gt; &lt;/Grid&gt; &lt;/ResponsiveDrawer&gt; &lt;/div&gt; ); } const rootElement = document.getElementById("root"); ReactDOM.render(&lt;App /&gt;, rootElement); </code></pre> <p>I just can't seem to figure out what it is inside the <code>ResponsiveDrawer</code> container that is causing the responsiveness to break. </p> <p>All help appreciated. </p> <p>UPDATE (1/7/2019): It looks like removing <code>display: flex</code> from the root solves the issue, but then I have the issue of it not honoring the left drawer.</p> <p>UPDATE (1/9/2019): As suggested by @Gaurav Rana, <a href="https://codesandbox.io/s/6zl7r2lx0r" rel="noreferrer">I have added</a> <code>width: 100%;</code> to the main element and it has half solved the problem. Now, the table will overflow / scroll properly when the sidebar is not visible. But, when the sidebar is still visible but the screen isn't wide enough for the whole table, the table scrolls under the sidebar.</p>
0
5,840
Finding files with Perl
<h2><a href="http://perldoc.perl.org/File/Find.html" rel="noreferrer"><code>File::Find</code></a> <strong>and the</strong> <code>wanted</code> <strong>subroutine</strong></h2> <p>This question is much simpler than the original title ("prototypes and forward declaration of subroutines"!) lets on. I'm hoping the answer, however simple, will help me understand subroutines/functions, prototypes and scoping and the <code>File::Find</code> module.</p> <p>With Perl, subroutines can appear pretty much anywhere and you normally don't need to make forward declarations (except if the sub declares a prototype, which I'm not sure how to do in a "standard" way in Perl). For what I usually do with Perl there's little difference between these different ways of running <code>somefunction</code>:</p> <pre><code>sub somefunction; # Forward declares the function &amp;somefunction; somefunction(); somefunction; # Bare word warning under `strict subs` </code></pre> <p>I often use <a href="https://metacpan.org/pod/distribution/perl/x2p/find2perl.PL" rel="noreferrer"><code>find2perl</code></a> to generate code which I crib/hack into parts of scripts. This could well be bad style and now my dirty laundry is public, but so be it :-) For <code>File::Find</code> the <code>wanted</code> function is a required subroutine - <code>find2perl</code> creates it and adds <code>sub wanted;</code> to the resulting script it creates. Sometimes, when I edit the script I'll remove the "<code>sub</code>" from <code>sub wanted</code> and it ends up as <code>&amp;wanted;</code> or <code>wanted();</code>. But without the <code>sub wanted;</code> forward declaration form I get this warning:</p> <pre><code>Use of uninitialized value $_ in lstat at findscript.pl line 29 </code></pre> <p>My question is: why does this happen and is it a real problem? It is "just a warning", but I want to understand it better.</p> <ul> <li>The documentation and code say <code>$_</code> is localized inside of <code>sub wanted {}</code>. Why would it be undefined if I use <code>wanted();</code> instead of <code>sub wanted;</code>? </li> <li>Is <code>wanted</code> using prototypes somewhere? Am I missing something obvious in <code>Find/File.pm</code>?</li> <li>Is it because <code>wanted</code> returns a code reference? (???)</li> </ul> <p>My guess is that the forward declaration form "initializes" <code>wanted</code> in some way so that the first use doesn't have an empty default variable. I guess this would be how prototypes - even Perl prototypes, such as they exist - would work as well. I tried grepping through the Perl source code to get a sense of what <code>sub</code> is doing when a function is called using <code>sub function</code> instead of <code>function()</code>, but that may be beyond me at this point.</p> <p>Any help deepening (and speeding up) my understanding of this is much appreciated.</p> <p><strong>EDIT:</strong> Here's a <a href="https://stackoverflow.com/a/17734132/2019415">recent example script here on Stack&nbsp;Overflow</a> that I created using <code>find2perl</code>'s output. If you remove the <code>sub</code> from <code>sub wanted;</code> you should get the same error.</p> <p><strong>EDIT:</strong> As I noted in a comment below (but I'll flag it here too): for several months I've been using <a href="https://metacpan.org/pod/Path::Iterator::Rule" rel="noreferrer"><code>Path::Iterator::Rule</code></a> instead of <code>File::Find</code>. It requires <code>perl &gt;5.10</code>, but I never have to deploy production code at sites with odd, "never upgrade", <code>5.8.*</code> only policies so <code>Path::Iterator::Rule</code> has become one of those modules I never want to do with out. Also useful is <a href="https://metacpan.org/pod/Path::Class" rel="noreferrer"><code>Path::Class</code></a>. Cheers.</p>
0
1,148
lsync configuration for using non-root logins
<p>I have searched for > 5 days, tried numerous tricks and tips and even tried to get the author of lsync to help but all in vain.</p> <p>I have 2 Red Hat 6.3 web servers that need to sync up their image directories when an image is uploaded. We can't control which server it gets uploaded to but it does not get loaded to the other one when it's uploaded.</p> <p>I simply need to be able to tell lsync to use another user's credentials other than root. Our information security team will not allow passwordless root access. Can't say that I blame them.</p> <p>I have an account that has sudo access to perform everything it needs to get the files to their destination. Although I can get rsync to perform the sync just fine, it fails with a permission denied error when run from lsync.</p> <p>I can even copy the command that is executed by lsync from the log, remove the square brackets and it syncs up successfully. So, I'm pretty sure it's lsync that is causing the problem. Simply because it is being run as root. The shell script forces it to run as root. I've even tried to change it to a non-root account and all the supporting files were changed along with the script and it still refuses to sync up.</p> <p>Here's the details on the scripts and files that I have: OS: Red Hat Linux version 6.3 (Santiago) lsyncd config file:</p> <pre><code> ---- -- User configuration file for lsyncd. -- -- Simple example for default rsync, but executing moves through on the target. -- -- For more examples, see /usr/share/doc/lsyncd*/examples/ -- -- sync{default.rsyncssh, source="/var/www/html", host="localhost", targetdir="/tmp/htmlcopy/"} settings{ logfile = "/var/log/lsyncd.log", statusFile = "/var/log/lsyncd-status.log", delay = 1, } sync { default.rsyncssh, source="&lt;Absolute path to source directory&gt;", host = "&lt;Host IP&gt;", targetdir = "&lt;Absolute path to target directory&gt;", rsync = { binary = "/usr/bin/rsync", rsh = "sudo -u &lt;Domain&gt;\\&lt;User ID&gt; ssh", sparse = true, update = true, links = true, times = true, } } </code></pre> <p>rsyncd.conf file:</p> <pre><code>log file = /var/log/rsyncd.log pid file = /var/log/rsyncd.pid allow = localhost deny = * list = true uid = 16777218 gid = 16777222 read only = false timeout=600 use chroot = true [Test1] path = "&lt;Absolute path to target/source&gt;" comment = Test for remote transfer </code></pre> <p>The rsyncd.conf file was changed to use a different uid/gid as this is what I wanted it to be changed to.</p> <p>Here is the error log from lsyncd.log:</p> <pre><code>Thu Aug 22 07:58:57 2013 Debug: daemonizing now. Thu Aug 22 07:58:57 2013 Function: Inotify.addWatch(&lt;Absolute Path to Source&gt; ) Thu Aug 22 07:58:57 2013 Inotify: addwatch( &lt;Absolute Path to Source&gt; )-&gt; 1 Thu Aug 22 07:58:57 2013 Call: getAlarm( ) Thu Aug 22 07:58:57 2013 Alarm: runner.getAlarm returns: (true) Thu Aug 22 07:58:57 2013 Masterloop: immediately handling delays. Thu Aug 22 07:58:57 2013 Call: cycle( ) Thu Aug 22 07:58:57 2013 Function: invokeActions( "Sync1", (Timestamp: 5491559.47) ) Thu Aug 22 07:58:57 2013 Normal: recursive startup rsync: &lt;Absolute Path to Target&gt; -&gt; &lt;Host IP&gt;:&lt;Absolute Path to Target&gt; Thu Aug 22 07:58:57 2013 Exec: /usr/bin/rsync [--delete] [--ignore-errors] [-usltS] [--rsh=sudo -u &lt;Domain&gt;\&lt;User ID&gt; ssh] [-r] [&lt;Absolute Path to Source&gt;] [&lt;Host IP&gt;:&lt;Absolute Path to Target&gt;] Thu Aug 22 07:58:57 2013 Function: write( (Timestamp: 5491559.47) ) Thu Aug 22 07:58:57 2013 Statusfile: writing now Thu Aug 22 07:58:57 2013 Call: getAlarm( ) Thu Aug 22 07:58:57 2013 Alarm: runner.getAlarm returns: (false) Thu Aug 22 07:58:57 2013 Masterloop: going into select ( no timeout ) rsync: Failed to exec sudo: Permission denied (13) rsync error: error in IPC code (code 14) at pipe.c(84) [sender=3.0.6] rsync: connection unexpectedly closed (0 bytes received so far) [sender] rsync error: error in IPC code (code 14) at io.c(600) [sender=3.0.6] Thu Aug 22 07:58:57 2013 Call: collectProcess( ) Thu Aug 22 07:58:57 2013 Delay: collected an event Thu Aug 22 07:58:57 2013 Error: Temporary or permanent failure on startup of "&lt;Absolute Path to Target&gt;". Terminating since "insist" is not set. </code></pre> <p>NOTE: I sanitized the files and assumed I understood all of the intent of the application as to where the source and targets should be.</p> <p>So, just so we're clear on the objective:</p> <ol> <li>I have 2 web servers that are load balanced.</li> <li>Images will be uploaded without control as to which server they go to.</li> <li>I'm designing a sync architecture using lsyncd/rsync as a daemon to update both servers when the upload occurs. This means that both servers will need to run lsyncd/rsyncd with no delete. No delete assumes that if both servers got a different image at the same time then which ever server checked the target first, it would delete the file on the target since it wasn't on the source.</li> </ol> <p>They were talking about trying to figure out how to direct the images to one server and then we could use the delete option to make both servers sync accurately without worrying about having the sync services on both servers and maybe missing one because of timing. Also, don't know what will happen if one file is open and the other server tries to delete it.</p> <p>I am desperate since I can't even get the author to help. Maybe it can't be done but it would seem that an app this powerful would have this one silly little flaw that would make it completely unusable by those that have security concerns.</p> <p>Thanks!</p>
0
1,832
Adding scikit-learn (sklearn) prediction to pandas data frame
<p>I am trying to add a sklearn prediction to a pandas dataframe, so that I can make a thorough evaluation of the prediction. The relavant piece of code is the following:</p> <pre><code>clf = linear_model.LinearRegression() clf.fit(Xtrain,ytrain) ypred = pd.DataFrame({'pred_lin_regr': pd.Series(clf.predict(Xtest))}) </code></pre> <p>The dataframes look like this:</p> <p><strong>Xtest</strong></p> <pre><code> axial_MET cos_theta_r1 deltaE_abs lep1_eta lep1_pT lep2_eta 8000 1.383026 0.332365 1.061852 0.184027 0.621598 -0.316297 8001 -1.054412 0.046317 1.461788 -1.141486 0.488133 1.011445 8002 0.259077 0.429920 0.769219 0.631206 0.353469 1.027781 8003 -0.096647 0.066200 0.411222 -0.867441 0.856115 -1.357888 8004 0.145412 0.371409 1.111035 1.374081 0.485231 0.900024 </code></pre> <p><strong>ytest</strong></p> <pre><code>8000 1 8001 0 8002 0 8003 0 8004 0 </code></pre> <p><strong>ypred</strong></p> <pre><code> pred_lin_regr 0 0.461636 1 0.314448 2 0.363751 3 0.291858 4 0.416056 </code></pre> <p>Concatenating Xtest and ytest works fine:</p> <pre><code>df_total = pd.concat([Xtest, ytest], axis=1) </code></pre> <p>but the event information is lost on ypred.</p> <p>What would be the must python/pandas/numpy-like way to do this?</p> <p>I am using the following versions:</p> <pre><code>argparse==1.2.1 cycler==0.9.0 decorator==4.0.4 ipython==4.0.0 ipython-genutils==0.1.0 matplotlib==1.5.0 nose==1.3.7 numpy==1.10.1 pandas==0.17.0 path.py==8.1.2 pexpect==4.0.1 pickleshare==0.5 ptyprocess==0.5 py==1.4.30 pyparsing==2.0.5 pytest==2.8.2 python-dateutil==2.4.2 pytz==2015.7 scikit-learn==0.16.1 scipy==0.16.1 simplegeneric==0.8.1 six==1.10.0 sklearn==0.0 traitlets==4.0.0 wsgiref==0.1.2 </code></pre> <p>I tried the following:</p> <pre><code>df_total["pred_lin_regr"] = clf.predict(Xtest) </code></pre> <p>seems to do the job, but I think I can't be sure that the events are matched correctly</p>
0
1,055
Spring-Boot @Autowired in main class is getting null
<p>I want to connect to a Sonic Broker Topic and Listen for any incoming XML message. I did something like below;</p> <p>Application.java</p> <pre><code>@SpringBootApplication @ComponentScan({"com.mainpack", "com.msgpack.jms"}) @EnableJms public class Application extends SpringBootServletInitializer { @Autowired private JmsTopicListener jmsTopicListener; @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } @Override public void onStartup(final ServletContext servletContext) throws ServletException { try { LogService.info(Application.class.getName(), "Starting Service..."); super.onStartup(servletContext); jmsTopicListener.listenMessage(); LogService.info(Application.class.getName(), "Service Started"); } catch (Exception ex) { LogService.error(this.getClass().getName(), ex); } } public static void main(String[] args) { ApplicationContext context = SpringApplication.run(Application.class, args); LogService.info(Application.class.getName(), "Service Started..."); } } </code></pre> <p>JmsTopicListener.java</p> <pre><code>@Component public class JmsTopicListener { @Autowired private ApplicationProperties properties; @Autowired private MsgListener msgListener; public void listenMessage() { TopicConnectionFactory factory; TopicConnection connection = null; LogService.info(this.getClass().getName(), "Registering Broker Connection"); try { factory = new progress.message.jclient.TopicConnectionFactory(properties.getBrokerURL()); connection = factory.createTopicConnection(properties.getUserName(), properties.getPass()); javax.jms.TopicSession subSession = (TopicSession) connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Topic topic = subSession.createTopic(properties.getTopicName()); MessageConsumer subscriber = subSession.createSubscriber(topic); subscriber.setMessageListener(msgListener); connection.start(); LogService.info(this.getClass().getName(), "Broker connected"); } catch (Exception ex) { LogService.error(this.getClass().getName(), ex); } } } </code></pre> <p>MsgListener.java</p> <pre><code>@Component public class MsgListener implements MessageListener { @Override public void onMessage(Message msg) { if (msg instanceof XMLMessage) { try { XMLMessage m = (XMLMessage) msg; if (m.getText().contains("Applications")) { LogService.info(this.getClass().getName(), "Recieved A Applications Message"); } else { LogService.info(this.getClass().getName(), "Recieved Message Does not contain Applications Tag"); } } catch (Exception ex) { LogService.info(this.getClass().getName(), "Exception: " + ex.getMessage()); } } } } </code></pre> <p>When, i run this code i get nullPointer at line <code>jmsTopicListener.listenMessage()</code> in <code>Application.java</code>.</p> <p>What mistake i have made here? Is there a way i can improve this (I mean get the work done in less code maybe)?.</p> <p>NOTE: com.mainpack have classes <code>Application.java</code> and <code>ApplicationProp.java</code> com.msgpack.jms have <code>JmsTopicListener.java</code> and <code>MsgListner.java</code></p> <p>Error From Logger:</p> <pre><code>ERROR [2015-07-14 14:34:52] [com.mainpack.Application] [localhost-startStop-1] - [Exception: ]java.lang.NullPointerException at com.mainpack.Application.onStartup(Application.java:33) at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5156) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717) at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:945) at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1768) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) </code></pre>
0
1,625
Building OpenCV as static libraries
<p>Maybe I'm missing something but I'm not able to build the static libraries of opencv.</p> <p>Setup: </p> <p>Kubuntu 12.04</p> <p>gcc 4.6.3</p> <p>make 3.81</p> <p>cmake 2.8.7</p> <p>opencv 2.4.6.1 (last available on site)</p> <p>I do all the job manually. I tried with cmake-gui with no more success.</p> <p>I do what it is written.</p> <p>$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_PYTHON_SUPPORT=ON -D WITH_QT=ON -D BUILD_SHARED_LIBRARIES=OFF ..</p> <p>(I also tried with BUILD_SHARED_LIBRARIES=NO)</p> <p>What I get is (for core for example):</p> <ul> <li>libopencv_core.so</li> <li>libopencv_core.so.2.4</li> <li>libopencv_core.so.2.4.6</li> <li><strong>libopencv_core_pch_dephelp.a</strong></li> </ul> <p>To say the truth, I expected <strong>libopencv_core.a</strong>.</p> <p>I'm a newbie with package/libs building on Linux. I'm sure there is something I did wrong but I don't know what. Also I don't want to use dynamic libraries...</p> <p>Thanks for your help!</p> <p><strong>EDIT</strong> Removed the blank space between -D ... in cmake command line</p> <pre><code>Result: -- General configuration for OpenCV 2.4.6.1 ===================================== -- Version control: unknown -- -- Platform: -- Host: Linux 3.2.0-51-generic x86_64 -- CMake: 2.8.7 -- CMake generator: Unix Makefiles -- CMake build tool: /usr/bin/make -- Configuration: RELEASE -- -- C/C++: -- Built as dynamic libs?: YES -- C++ Compiler: /usr/bin/c++ (ver 4.6) -- C++ flags (Release): -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -msse3 -ffunction-sections -O3 -DNDEBUG -DNDEBUG -- C++ flags (Debug): -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -msse3 -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -ggdb3 -- C Compiler: /usr/bin/gcc -- C flags (Release): -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -msse3 -ffunction-sections -O3 -DNDEBUG -DNDEBUG -- C flags (Debug): -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -msse3 -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -ggdb3 -- Linker flags (Release): -- Linker flags (Debug): -- Precompiled headers: YES -- -- OpenCV modules: -- To be built: core imgproc flann highgui features2d calib3d ml video objdetect contrib photo legacy gpu nonfree java python stitching superres ts videostab </code></pre> <p>...</p> <pre><code>-- Configuring done -- Generating done CMake Warning: Manually-specified variables were not used by the project: BUILD_PYTHON_SUPPORT BUILD_SHARED_LIBRARIES </code></pre> <p>I still see <strong>Built as dynamic libs?: YES</strong> and it tells me that it doesn't care about the <strong>BUILD_SHARED_LIBRARIES</strong> variable!</p>
0
1,789
Angular Material Table Dynamic Columns without model
<p>I need to use angular material table without model, because I don't know what will come from service.</p> <p>So I am initializing my <code>MatTableDataSource</code> and <code>displayedColumns</code> dynamically in component like that :</p> <p><strong>TableComponent :</strong></p> <pre class="lang-ts prettyprint-override"><code>ngOnInit() { this.vzfPuanTablo = [] //TABLE DATASOURCE //GET SOMETHING FROM SERVICE this.listecidenKisi = this.listeciServis.listecidenKisi; this.listecidenVazife = this.listeciServis.listecidenVazife; //FILL TABLE DATASOURCE var obj = {}; for (let i in this.listecidenKisi ){ for( let v of this.listecidenVazife[i].vazifeSonuclar){ obj[v.name] = v.value; } this.vzfPuanTablo.push(obj); obj={}; } //CREATE DISPLAYED COLUMNS DYNAMICALLY this.displayedColumns = []; for( let v in this.vzfPuanTablo[0]){ this.displayedColumns.push(v); } //INITIALIZE MatTableDataSource this.dataSource = new MatTableDataSource(this.vzfPuanTablo); } </code></pre> <hr /> <p>The most important part of code is here :</p> <blockquote> <pre class="lang-ts prettyprint-override"><code>for( let v in this.vzfPuanTablo[0]) { this.displayedColumns.push(v); } </code></pre> </blockquote> <p>I am creating <code>displayedColumns</code> here dynamically, it means; even I don't know what will come from service, I can show it in table.</p> <p>For example <code>displayedColumns</code> can be like that:</p> <ul> <li>[&quot;one&quot;, &quot;two&quot; , &quot;three&quot; , &quot;four&quot; , &quot;five&quot; ]</li> </ul> <p>or</p> <ul> <li>[&quot;stack&quot;,&quot;overflow&quot;,&quot;help&quot;,&quot;me]</li> </ul> <p>But it is not problem because I can handle it.</p> <hr /> <p>But when I want to show it in HTML, I can't show properly because of <code>matCellDef</code> thing:</p> <p><strong>TableHtml :</strong></p> <pre class="lang-xml prettyprint-override"><code> &lt;mat-table #table [dataSource]=&quot;dataSource&quot; class=&quot;mat-elevation-z8&quot;&gt; &lt;ng-container *ngFor=&quot;let disCol of displayedColumns; let colIndex = index&quot; matColumnDef=&quot;{{disCol}}&quot;&gt; &lt;mat-header-cell *matHeaderCellDef&gt;{{disCol}}&lt;/mat-header-cell&gt; &lt;mat-cell *matCellDef=&quot;let element &quot;&gt; {{element.disCol}} &lt;/mat-cell&gt; &lt;/ng-container&gt; &lt;mat-header-row *matHeaderRowDef=&quot;displayedColumns&quot;&gt;&lt;/mat-header-row&gt; &lt;mat-row *matRowDef=&quot;let row; columns: displayedColumns;&quot;&gt;&lt;/mat-row&gt; &lt;/mat-table&gt; </code></pre> <p>My problem is here:</p> <blockquote> <pre class="lang-xml prettyprint-override"><code>&lt;mat-cell *matCellDef=&quot;let element &quot;&gt; {{element.disCol}} &lt; / mat-cell&gt; </code></pre> </blockquote> <p>In fact, I want to display <code>element.&quot;disCol's value&quot;</code> in the cell, but I don't know how can I do that.</p> <p>Otherwise, everything is ok except this <code>element.&quot;disCol's value&quot;</code> thing.</p> <hr /> <p>When I use <code>{{element.disCol}}</code> to display <code>value of element that has disCols's value</code> , all cells are empty like that:</p> <p><a href="https://i.stack.imgur.com/XzB68.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XzB68.png" alt="enter image description here" /></a></p> <p>Other example that using <code>{{element}}</code> only:</p> <p><a href="https://i.stack.imgur.com/Upb14.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Upb14.png" alt="enter image description here" /></a></p> <hr /> <p><strong>Also as you can see:</strong></p> <ol> <li><p>Table datasource is changing dynamically. It means I can't use <code>{{element.ColumnName}}</code> easily, because I don't know even what is it.</p> <ul> <li>First Example's displayedColumns = ['Vazife', 'AdSoyad', 'Kirmizi', 'Mavi', 'Yesil', 'Sari'];</li> <li>Second Example's displayedColumns = ['Muhasebe', 'Ders', 'Egitim', 'Harici'];</li> </ul> </li> <li><p><code>matHeaderCellDef</code> is correct , because it is using {{disCol}} directly.</p> </li> </ol> <p><em>But I need to read disCol's value, and display <code>element.(disCol's value)</code> in the cell.</em></p> <p><strong>How can I do that ?</strong></p>
0
1,733
window.URL.revokeObjectURL() doesn't release memory immediately (or not at all)?
<p>I'm making an html interface to upload images on a server with Drag &amp; Drop and multiple selection files. I want to display the pictures before sending them to the server. So I first try to use <code>FileReader</code> but I have had some problems like in <a href="https://stackoverflow.com/questions/6217652/html5-file-api-crashes-chrome-when-using-readasdataurl-to-load-a-selected-image/6298889#6298889">this post</a>. so I change my way and I decided to use blob:url like ebidel recommends in the post, with <code>window.URL.createObjectURL()</code> and <code>window.URL.revokeObjectURL()</code> to release memory.</p> <p>But now, I've got another problem, which is similar to <a href="https://stackoverflow.com/questions/7167180/understanding-object-urls-for-client-side-files-and-how-to-free-the-memory">this one</a>. I want that a client could upload 200 images at time if he wants. But the browser crashed and the ram used was very high! So I thought that maybe too much images were displayed at the same time, and I set up a system with a waiting queue of files using an array, in order to treat only 10 files at time. But the problem still occurs.</p> <p>On Google Chrome, if I check <code>chrome://blob-internals/</code> the files (which are normally already released by <code>window.URL.revokeObjectURL()</code>) are released approximately after a 8 seconds delay. On Firefox I'm not sure but it seems like if the files were not released (I check on <code>about:memory</code> -&gt; images for that)</p> <p>Is my code which is bad, or is it a problem independent of me? Is there a solution to force the navigators to release immediately the memory? If it can help, this is the part of JavaScripton which the problems occurs: <strong>link expired because code was not included in question</strong>.</p> <p><strong>EDIT</strong></p> <p><em>This is a kind of own answer + an answer to bennlich (too long text for a comment)</em></p> <p>I understood from the answer of user1835582 that I could indeed remove the Blob/File but while the browser needs images it keeps them somewhere in memory (which is logical). So it's the fact to display images (many &amp; heavy) that gave me crashes &amp; slow downs, not the <code>revokeObjectURL</code> method. Moreover, each browser manages the memory by its own way, leading to different behaviors. Here is how I came to this conclusion.</p> <p>First, let's try that <code>revokeObjectURL</code> works well, with a simple example using the source code of <a href="https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example.3A_Using_object_URLs_to_display_images" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example.3A_Using_object_URLs_to_display_images</a>. Using Chrome you can verify that Blob are well revoked, by checking <code>chrome://blob-internals/</code> or trying to open displayed images into a new tab that will be blank. Note : to fully release Blob references, add <code>document.getElementById(&quot;fileElem&quot;).value = &quot;&quot;</code>. When I posted my question some years ago, it was about 8 seconds to release blob, now it's almost immediate (probably due to improvements in Chrome &amp; / or to a better computer)</p> <p>Then, time for a charge test. I did it with a hundred of jpg of ~2.5 Mo each. After that images have been displayed, I scrolled the page. Chrome crashed and Firefox was slow (not tested on others browsers). However, when I commented <code>li.appendChild(img)</code> all went well, even with a huge bunch of images. This shows that problems are not coming from <code>revokeObjectURL</code> method which in fact works properly, but from displaying lot of heavy images. You can also test to create a simple html page with hundreds of heavy images and scroll it =&gt; same result (crash / slow down).</p> <p>Finally to look deeper about images memory management, it's interesting on Firefox to look into about:memory. For example I saw that when the window is active, Firefox uncompresses the images (images -&gt; uncompressed-heap goes up), while raw (images -&gt; raw) is always stable (relative to the the quantity of images loaded). There is a good discussion about memory management here : <a href="http://jeff.ecchi.ca/blog/2010/09/19/free-my-memory" rel="nofollow noreferrer">http://jeff.ecchi.ca/blog/2010/09/19/free-my-memory</a>.</p>
0
1,241
An algorithm to calculate probability of a sum of the results happening
<p>The algorithm I'm talking about using would allow you to present it with x number of items with each having a range of a to b with the result being y. I would like to have an algorithm which would, when presented with the values as described would output the possibility of it happening.</p> <p>For example, for two die. Since I already know them(due to the possible results being so low). It'd be able to tell you each of the possibilities.</p> <p>The setup would be something like. x=2 a=1 b=6. If you wanted to know the chance of having it result in a 2. Then it'd simply spit out 1/36(or it's float value). If you put in 7 as the total sum, it'd tell you 6.</p> <p>So my question is, is there a simple way to implement such a thing via an algorithm that is already written. Or does one have to go through every single iteration of each and every item to get the total number of combinations for each value.</p> <p>The exact formula would also, give you the combinations to make each of the values from 1-12.</p> <p>So it'd give you a distribution array with each one's combinations at each of the indexes. If it does 0-12. Then 0 would have 0, 1 would have 0, and 2 would have 1.</p> <p>I feel like this is the type of problem that someone else has had and wanted to work with and has the algorithm already done. If anyone has an easy way to do this beyond simply just looping through every possible value would be awesome.</p> <p>I have no idea why I want to have this problem solved, but for some reason today I just had this feeling of wanting to solve it. And since I've been googling, and using wolfram alpha, along with trying it myself. I think it's time to concede defeat and ask the community.</p> <p>I'd like the algorithm to be in c, or maybe PHP(even though I'd rather it not be since it's a lot slower). The reason for c is simply because I want raw speed, and I don't want to have to deal with classes or objects.</p> <p>Pseudo code, or C is the best ways show your algorithm.</p> <p>Edit:</p> <p>Also, if I offended the person with a 'b' in his name due to the thing about mathematics I'm sorry. Since I didn't mean to offend, but I wanted to just state that <strong>I</strong> didn't understand it. But the answer could've stayed on there since I'm sure there are people who might come to this question and understand the mathematics behind it.</p> <p>Also I cannot decide which way that I want to code this up. I think I'll try using both and then decide which one I like more to see/use inside of my little library.</p> <p>The final thing that I forgot to say is that, calculus is about four going on five years ago. My understanding of probability, statistics, and randomness come from my own learning via looking at code/reading wikipedia/reading books. </p> <p>If anyone is curious what sparked this question. I had a book that I was putting off reading called <em>The Drunkards Walk</em> and then once I say XKCD 904, I decided it was time to finally get around to reading it. Then two nights ago, whilst I was going to sleep... I had pondered how to solve this question via a simple algorithm and was able to think of one. </p> <p>My coding understanding of code comes from tinkering with other programs, seeing what happened when I broke something, and then trying my own things whilst looking over the documentation for the build in functions. I do understand big O notation from reading over wikipedia(as much as one can from that), and pseudo code was because it's so similar to python. I myself, cannot write pseudo code(or says the teachers in college). I kept getting notes like "make it less like real code make it more like pseudo code." That thing hasn't changed.</p> <p>Edit 2: Incase anyone searching for this question just quickly wanted the code. I've included it below. It is licensed under the LGPLv3 since I'm sure that there exists closed-source equivalents of this code.</p> <p>It should be fairly portable since it is written entirely in c. If one was wanting to make it into an extension in any of the various languages that are written in c, it should take very little effort to do so. I chose to 'mark' the first one that linked to "Ask Dr. Math" as the answer since it was the implementation that I have used for this question.</p> <p>The first file's name is "sum_probability.c"</p> <pre><code>#include &lt;math.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;limits.h&gt; /*! * file_name: sum_probability.c * * Set of functions to calculate the probabilty of n number of items adding up to s * with sides x. The question that this program relates to can be found at the url of * http://stackoverflow.com/questions/6394120/ * * Copyright 2011-2019, Macarthur Inbody * * This program is free software: you can redistribute it and/or modify * it under the terms of the Lesser GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the Lesser GNU General Public License * along with this program. If not, see &lt;http://www.gnu.org/licenses/lgpl-3.0.html&gt;. * * 2011-06-20 06:03:57 PM -0400 * * These functions work by any input that is provided. For a function demonstrating it. * Please look at the second source file at the post of the question on stack overflow. * It also includes an answer for implenting it using recursion if that is your favored * way of doing it. I personally do not feel comfortable working with recursion so that is * why I went with the implementation that I have included. * */ /* * The following functions implement falling factorials so that we can * do binomial coefficients more quickly. * Via the following formula. * * K * PROD (n-(k-i))/i * i=1; * */ //unsigned int return unsigned int m_product_c( int k, int n){ int i=1; float result=1; for(i=1;i&lt;=k;++i){ result=((n-(k-i))/i)*result; } return result; } //float return float m_product_cf(float n, float k){ int i=1; float result=1; for(i=1;i&lt;=k;++i){ result=((n-(k-i))/i)*result; } return result; } /* * The following functions calculates the probability of n items with x sides * that add up to a value of s. The formula for this is included below. * * The formula comes from. http://mathforum.org/library/drmath/view/52207.html * *s=sum *n=number of items *x=sides *(s-n)/x * SUM (-1)^k * C(n,k) * C(s-x*k-1,n-1) * k=0 * */ float chance_calc_single(float min, float max, float amount, float desired_result){ float range=(max-min)+1; float series=ceil((desired_result-amount)/range); float i; --amount; float chances=0.0; for(i=0;i&lt;=series;++i){ chances=pow((-1),i)*m_product_cf(amount,i)*m_product_cf(desired_result-(range*i)-1,amount)+chances; } return chances; } </code></pre> <p>And here is the file that shows the implementation as I said in the previous file.</p> <pre><code>#include "sum_probability.c" /* * * file_name:test.c * * Function showing off the algorithms working. User provides input via a cli * And it will give you the final result. * */ int main(void){ int amount,min,max,desired_results; printf("%s","Please enter the amount of items.\n"); scanf("%i",&amp;amount); printf("%s","Please enter the minimum value allowed.\n"); scanf("%i",&amp;min); printf("%s","Please enter the maximum value allowed.\n"); scanf("%i",&amp;max); printf("%s","Please enter the value you wish to have them add up to. \n"); scanf("%i",&amp;desired_results); printf("The total chances for %i is %f.\n", desired_results, chance_calc_single(min, max, amount, desired_results)); } </code></pre>
0
2,517
Custom Error Handling with Rails 4.0
<p>I'm building a Ruby on Rails api using Ruby 2.0 and Rails 4.0. My app is almost solely a JSON API, so if an error occurs (500, 404), I want to capture that error and return a nicely formatted JSON error message.</p> <p>I've tried <a href="https://coderwall.com/p/w3ghqq">this</a> and also:</p> <pre><code>rescue_from ActionController::RoutingError, :with =&gt; :error_render_method def error_render_method puts "HANDLING ERROR" render :json =&gt; { :errors =&gt; "Method not found." }, :status =&gt; :not_found true end </code></pre> <p>In my ApplicationController.</p> <p>Neither of these do the trick (the exceptions are not captured at all). My Googling shows that this changed a lot between 3.1, 3.2, and I can't find any good documentation on how to do this in Rails 4.0.</p> <p>Anybody know?</p> <p><strong>Edit</strong> Here's the stack trace when I go to a 404 page:</p> <pre><code>Started GET "/testing" for 127.0.0.1 at 2013-08-21 09:50:42 -0400 ActionController::RoutingError (No route matches [GET] "/testing"): actionpack (4.0.0) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call' actionpack (4.0.0) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' railties (4.0.0) lib/rails/rack/logger.rb:38:in `call_app' railties (4.0.0) lib/rails/rack/logger.rb:21:in `block in call' activesupport (4.0.0) lib/active_support/tagged_logging.rb:67:in `block in tagged' activesupport (4.0.0) lib/active_support/tagged_logging.rb:25:in `tagged' activesupport (4.0.0) lib/active_support/tagged_logging.rb:67:in `tagged' railties (4.0.0) lib/rails/rack/logger.rb:21:in `call' actionpack (4.0.0) lib/action_dispatch/middleware/request_id.rb:21:in `call' rack (1.5.2) lib/rack/methodoverride.rb:21:in `call' rack (1.5.2) lib/rack/runtime.rb:17:in `call' activesupport (4.0.0) lib/active_support/cache/strategy/local_cache.rb:83:in `call' rack (1.5.2) lib/rack/lock.rb:17:in `call' actionpack (4.0.0) lib/action_dispatch/middleware/static.rb:64:in `call' railties (4.0.0) lib/rails/engine.rb:511:in `call' railties (4.0.0) lib/rails/application.rb:97:in `call' rack (1.5.2) lib/rack/lock.rb:17:in `call' rack (1.5.2) lib/rack/content_length.rb:14:in `call' rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service' /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service' /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run' /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread' Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms) Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/routes/_route.html.erb (2.9ms) Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/routes/_route.html.erb (0.9ms) Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/routes/_table.html.erb (1.1ms) Rendered /Library/Ruby/Gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/routing_error.erb within rescues/layout (38.3ms) </code></pre> <p>I don't think I want it to ever get this far, something should catch it and return the appropriate json error response.</p>
0
1,378
java.lang.StackOverflowError: stack size 8MB
<p>I am using <a href="https://github.com/500px/500px-android-blur" rel="nofollow">this library</a> to blur the area beneath my layout in android. I am getting stackoverflowerror and activity crashes when the blur view is called. Please help. Thanks.</p> <p><strong><em>Here is the code with logcat</em></strong></p> <p><strong><em>BlurringView Activity</em></strong></p> <pre><code>import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v8.renderscript.Allocation; import android.support.v8.renderscript.Element; import android.support.v8.renderscript.RenderScript; import android.support.v8.renderscript.ScriptIntrinsicBlur; import android.util.AttributeSet; import android.view.View; /** * A custom view for presenting a dynamically blurred version of another view's content. * &lt;p/&gt; * Use {@link #setBlurredView(android.view.View)} to set up the reference to the view to be blurred. * After that, call {@link #invalidate()} to trigger blurring whenever necessary. */ public class BlurringView extends View { public BlurringView(Context context) { this(context, null); } public BlurringView(Context context, AttributeSet attrs) { super(context, attrs); final Resources res = getResources(); final int defaultBlurRadius = res.getInteger(R.integer.default_blur_radius); final int defaultDownsampleFactor = res.getInteger(R.integer.default_downsample_factor); final int defaultOverlayColor = res.getColor(R.color.default_overlay_color); initializeRenderScript(context); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PxBlurringView); setBlurRadius(a.getInt(R.styleable.PxBlurringView_blurRadius, defaultBlurRadius)); setDownsampleFactor(a.getInt(R.styleable.PxBlurringView_downsampleFactor, defaultDownsampleFactor)); setOverlayColor(a.getColor(R.styleable.PxBlurringView_overlayColor, defaultOverlayColor)); a.recycle(); } public void setBlurredView(View blurredView) { mBlurredView = blurredView; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mBlurredView != null) { if (prepare()) { // If the background of the blurred view is a color drawable, we use it to clear // the blurring canvas, which ensures that edges of the child views are blurred // as well; otherwise we clear the blurring canvas with a transparent color. if (mBlurredView.getBackground() != null &amp;&amp; mBlurredView.getBackground() instanceof ColorDrawable) { mBitmapToBlur.eraseColor(((ColorDrawable) mBlurredView.getBackground()).getColor()); } else { mBitmapToBlur.eraseColor(Color.TRANSPARENT); } mBlurredView.draw(mBlurringCanvas); blur(); mBlurredView.invalidate(); canvas.save(); canvas.translate(mBlurredView.getX() - getX(), mBlurredView.getY() - getY()); canvas.scale(mDownsampleFactor, mDownsampleFactor); canvas.drawBitmap(mBlurredBitmap, 0, 0, null); canvas.restore(); } canvas.drawColor(mOverlayColor); } } public void setBlurRadius(int radius) { mBlurScript.setRadius(radius); } public void setDownsampleFactor(int factor) { if (factor &lt;= 0) { throw new IllegalArgumentException("Downsample factor must be greater than 0."); } if (mDownsampleFactor != factor) { mDownsampleFactor = factor; mDownsampleFactorChanged = true; } } public void setOverlayColor(int color) { mOverlayColor = color; } private void initializeRenderScript(Context context) { mRenderScript = RenderScript.create(context); mBlurScript = ScriptIntrinsicBlur.create(mRenderScript, Element.U8_4(mRenderScript)); } protected boolean prepare() { final int width = mBlurredView.getWidth(); final int height = mBlurredView.getHeight(); if (mBlurringCanvas == null || mDownsampleFactorChanged || mBlurredViewWidth != width || mBlurredViewHeight != height) { mDownsampleFactorChanged = false; mBlurredViewWidth = width; mBlurredViewHeight = height; int scaledWidth = width / mDownsampleFactor; int scaledHeight = height / mDownsampleFactor; // The following manipulation is to avoid some RenderScript artifacts at the edge. scaledWidth = scaledWidth - scaledWidth % 4 + 4; scaledHeight = scaledHeight - scaledHeight % 4 + 4; if (mBlurredBitmap == null || mBlurredBitmap.getWidth() != scaledWidth || mBlurredBitmap.getHeight() != scaledHeight) { mBitmapToBlur = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888); if (mBitmapToBlur == null) { return false; } mBlurredBitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888); if (mBlurredBitmap == null) { return false; } } mBlurringCanvas = new Canvas(mBitmapToBlur); mBlurringCanvas.scale(1f / mDownsampleFactor, 1f / mDownsampleFactor); mBlurInput = Allocation.createFromBitmap(mRenderScript, mBitmapToBlur, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT); mBlurOutput = Allocation.createTyped(mRenderScript, mBlurInput.getType()); } return true; } protected void blur() { mBlurInput.copyFrom(mBitmapToBlur); mBlurScript.setInput(mBlurInput); mBlurScript.forEach(mBlurOutput); mBlurOutput.copyTo(mBlurredBitmap); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mRenderScript != null) { mRenderScript.destroy(); } } private int mDownsampleFactor; private int mOverlayColor; private View mBlurredView; private int mBlurredViewWidth, mBlurredViewHeight; private boolean mDownsampleFactorChanged; private Bitmap mBitmapToBlur, mBlurredBitmap; private Canvas mBlurringCanvas; private RenderScript mRenderScript; private ScriptIntrinsicBlur mBlurScript; private Allocation mBlurInput, mBlurOutput; } </code></pre> <p><strong><em>MyActivity class</em></strong></p> <pre><code>BlurringView blurringView = (BlurringView) addView.findViewById(R.id.circle); blurringView.setBlurredView(blurringView); blurringView.invalidate(); </code></pre> <p><strong><em>Logcat Error</em></strong></p> <blockquote> <pre><code>E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.user.designsample, PID: 19998 java.lang.StackOverflowError: stack size 8MB at android.graphics.Canvas.drawOval(Canvas.java:1155) at android.graphics.Canvas.drawOval(Canvas.java:1147) at android.graphics.drawable.GradientDrawable.draw(GradientDrawable.java:615) at android.view.View.drawBackground(View.java:16376) at android.view.View.draw(View.java:16175) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundredpx.android.blur.BlurringView.onDraw(BlurringView.java:65) at android.view.View.draw(View.java:16184) at com.fivehundred 05-05 23:16:31.323 19998-19998/com.example.user.humandesignsample E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 6333780) 05-05 23:16:31.361 19998-19998/com.example.user.humandesignsample E/AndroidRuntime: Error reporting crash android.os.TransactionTooLargeException: data parcel size 6333780 bytes at android.os.BinderProxy.transactNative(Native Method) at android.os.BinderProxy.transact(Binder.java:503) at android.app.ActivityManagerProxy.handleApplicationCrash(ActivityManagerNative.java:4425) at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:90) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690) </code></pre> </blockquote>
0
4,829
How to disable SSL certificate checking with Spring RestTemplate?
<p>I am trying to write an integration test where our test launches an embedded HTTPS server using <a href="http://www.simpleframework.org/" rel="noreferrer">Simple</a>. I <a href="https://www.sslshopper.com/article-how-to-create-a-self-signed-certificate-using-java-keytool.html" rel="noreferrer">created a self-signed certificate using <code>keytool</code></a> and am able to access the server using a browser (specifically Chrome, and I do get a warning about the self-signed certificate).</p> <p>However, when I try to connect using <a href="http://docs.spring.io/spring/docs/4.0.4.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html" rel="noreferrer">Spring RestTemplate</a>, I get a <a href="http://docs.spring.io/spring/docs/4.0.4.RELEASE/javadoc-api/org/springframework/web/client/ResourceAccessException.html" rel="noreferrer">ResourceAccessException</a>: </p> <pre><code>org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://localhost:8088":sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:557) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:502) at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:444) at net.initech.DummySslServer.shouldConnect(DummySslServer.java:119) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.junit.runner.JUnitCore.run(JUnitCore.java:160) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134) Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1917) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:301) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:295) at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1369) at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:156) at sun.security.ssl.Handshaker.processLoop(Handshaker.java:925) at sun.security.ssl.Handshaker.process_record(Handshaker.java:860) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1043) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355) at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153) at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:78) at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:52) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:541) ... 33 more Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387) at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292) at sun.security.validator.Validator.validate(Validator.java:260) at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324) at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229) at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124) at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1351) ... 47 more Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145) at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131) at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280) at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382) ... 53 more </code></pre> <p>From <a href="https://stackoverflow.com/questions/4072585/disabling-ssl-certificate-validation-in-spring-resttemplate">other questions</a> and <a href="http://www.jroller.com/jurberg/entry/using_a_hostnameverifier_with_spring" rel="noreferrer">blog</a> <a href="http://www.jroller.com/hasant/entry/no_subject_alternative_names_matching" rel="noreferrer">posts</a> I've seen the advice to replace the <code>HostnameVerifier</code> with something like </p> <pre><code>private static final HostnameVerifier PROMISCUOUS_VERIFIER = ( s, sslSession ) -&gt; true; </code></pre> <p>And I've set it both globally and on the <code>RestTemplate</code> itself:</p> <pre><code>HttpsURLConnection.setDefaultHostnameVerifier( PROMISCUOUS_VERIFIER ); </code></pre> <p>...and on the <code>RestTemplate</code> itself:</p> <pre><code>final RestTemplate restTemplate = new RestTemplate(); restTemplate.setRequestFactory( new SimpleClientHttpRequestFactory() { @Override protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { if(connection instanceof HttpsURLConnection ){ ((HttpsURLConnection) connection).setHostnameVerifier(PROMISCUOUS_VERIFIER); } super.prepareConnection(connection, httpMethod); } }); </code></pre> <p>Yet, I am still getting the above error. How can I get around it? </p> <ol> <li>Installing the certificate locally <em>outside</em> of the unit test is <em>not</em> an option as then it would need to get installed manually on every dev machine and build server and would cause an avalanche of red tape.</li> <li>We need SSL since we are testing a library that sits on top of <code>RestTemplate</code> and that we are configuring it correctly.</li> </ol> <p>I am using Java 8 (but could use 7) and Spring 4.0.3 .</p>
0
3,003
RFCOMM without pairing using PyBluez on Debian?
<p>I am trying to create an RFCOMM server process with Python that can be used without the need for pairing. Initially, I grabbed the two example scripts from the PyBluez documentation:</p> <p>Server:</p> <pre><code># file: rfcomm-server.py # auth: Albert Huang &lt;albert@csail.mit.edu&gt; # desc: simple demonstration of a server application that uses RFCOMM sockets # # $Id: rfcomm-server.py 518 2007-08-10 07:20:07Z albert $ from bluetooth import * server_sock=BluetoothSocket( RFCOMM ) server_sock.bind(("",PORT_ANY)) server_sock.listen(1) port = server_sock.getsockname()[1] uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee" advertise_service( server_sock, "SampleServer", service_id = uuid, service_classes = [ uuid, SERIAL_PORT_CLASS ], profiles = [ SERIAL_PORT_PROFILE ], # protocols = [ OBEX_UUID ] ) print "Waiting for connection on RFCOMM channel %d" % port client_sock, client_info = server_sock.accept() print "Accepted connection from ", client_info try: while True: data = client_sock.recv(1024) if len(data) == 0: break print "received [%s]" % data except IOError: pass print "disconnected" client_sock.close() server_sock.close() print "all done" </code></pre> <p>Client:</p> <pre><code># file: rfcomm-client.py # auth: Albert Huang &lt;albert@csail.mit.edu&gt; # desc: simple demonstration of a client application that uses RFCOMM sockets # intended for use with rfcomm-server # # $Id: rfcomm-client.py 424 2006-08-24 03:35:54Z albert $ from bluetooth import * import sys addr = None if len(sys.argv) &lt; 2: print "no device specified. Searching all nearby bluetooth devices for" print "the SampleServer service" else: addr = sys.argv[1] print "Searching for SampleServer on %s" % addr # search for the SampleServer service uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee" service_matches = find_service( uuid = uuid, address = addr ) if len(service_matches) == 0: print "couldn't find the SampleServer service =(" sys.exit(0) first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] print "connecting to \"%s\" on %s" % (name, host) # Create the client socket sock=BluetoothSocket( RFCOMM ) sock.connect((host, port)) print "connected. type stuff" while True: data = raw_input() if len(data) == 0: break sock.send(data) sock.close() </code></pre> <p>When I ran the server script on Windows everything worked just how I had hoped - no pairing was necessary. At this stage everything was looking very promising.</p> <p>However, I need the server process to run under Debian Squeeze. When I test on Debian the client connection is refused. In the syslog there are messages from bluetoothd for a failed link key request and PIN request.</p> <p>Version information:</p> <ul> <li>PyBluez 0.18</li> <li>Python 2.6</li> <li>Bluez 4.66</li> <li>Bluetooth v2.0 hardware on both ends of the connection</li> </ul> <p><a href="http://permalink.gmane.org/gmane.linux.bluez.kernel/13828" rel="noreferrer">This discussion</a> seems to suggest that if I can adjust the security level on the server socket then pairing will be disabled and everything will just work as expected. It is not apparent to me how to do this with PyBluez though, or even if it is possible.</p> <p>I have experimented with calls to setsockopt() using various BT_SECURITY* constants, as well as grabbing the last PyBluez and calling setl2capsecurity() but have not been able to make any progress.</p> <p>Is this going to be achievable with PyBluez?</p>
0
1,355
How to use Exception Handling in Selenium Webdriver?
<p>The Scenario is as follows: When the code <strong><code>driver.get(url);</code></strong> runs, if the URL is not able to access (if server is not reachable) then it should throw an exception that server is not reachable and the code should stop executing the next line </p> <pre class="lang-java prettyprint-override"><code>driver.findElement(By.id("loginUsername")).sendKeys(username); </code></pre> <p>The following code I'm running in eclipse as follows:</p> <pre class="lang-java prettyprint-override"><code>import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.Select; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class A { static Properties p= new Properties(); String url=p.getProperty("url"); private static Logger Log = Logger.getLogger(A.class.getName()); public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, InterruptedException { WebDriver driver = new FirefoxDriver(); A a = new A(); Actions actions = new Actions(driver); DOMConfigurator.configure("src/log4j.xml"); String url = a.readXML("logindetails","url"); String username = a.readXML("logindetails","username"); String password = a.readXML("logindetails","password"); //use username for webdriver specific actions Log.info("Sign in to the OneReports website"); driver.manage().window().maximize(); driver.get(url);// In this line after opens the browser it gets the URL from my **D://NewFile.xml* file and try to open in the browser. If the Server is not reachable then it should stop here. else it takes the username and password from the same file then it will open the page in browser. Thread.sleep(5000); Log.info("Enter Username"); driver.findElement(By.id("loginUsername")).sendKeys(username); Log.info("Enter Password"); driver.findElement(By.id("loginPassword")).sendKeys(password); //submit Log.info("Submitting login details"); waitforElement(driver,120 , "//*[@id='submit']"); driver.findElement(By.id("submit")).submit(); Thread.sleep(5000); } private static void waitforElement(WebDriver driver, int i, String string) { // TODO Auto-generated method stub } public String readXML(String searchelement,String tag) throws SAXException, IOException, ParserConfigurationException{ String ele = null; File fXmlFile = new File("D://NewFile.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName(searchelement); Node nNode = nList.item(0); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; ele=eElement.getElementsByTagName(tag).item(0).getTextContent(); } return ele; } } </code></pre> <p>I tried this try block method as well. But it's not catching the exception just moving to the</p> <p>driver.findElement(By.id("loginUsername")).sendKeys(username);</p> <p>Error in code</p> <blockquote> <p>line and I'm getting error as follows in the console:Unable to locate element: {"method":"id","selector":"loginUsername"} Command duration or timeout: 262 milliseconds</p> </blockquote> <pre class="lang-java prettyprint-override"><code>try { driver.get(url); } catch(Exception e) { Reporter.log("network server is slow..check internet connection"); Log.info("Unable to open the website"); throw new Error("network server is slow..check internet connection"); } </code></pre>
0
1,608
PIC Interrupt driven UART with circular buffer at high baud rate
<p>I am trying to read from a sensor with PIC 18f4550 at baud rate=38400. With a FIFO Circular buffer, I am able to store data from the sensor to an array. </p> <p>The sensor will respond to a request command and return a measurement of 15 bytes (<strong>the same as the circular buffer I created</strong>). I have to grab all <strong>15 bytes</strong> and put \r\n at the end to separate each measurement since there is no deliminator.</p> <p>So I used two pointers, <strong>inputpointer</strong> and <strong>outputpointer</strong> to store bytes and transmit byte out. Because 18f4550 only has one hard UART, I use it to read data and send commands to sensor and at the same time use a software UART to output to a laptop via RS232.</p> <p>I request a new measurement when the buffer is read and sent to serial port.</p> <p>It works well but I just want to know if there is a better way to avoid FIFO overrun when the head pointer overruns tail pointer, ie when there is a lot of data getting buffered but they cannot get output in time. </p> <p>Here is the code: 16MHZ PIC 18f4550 mikroC compiler</p> <pre><code>char dataRx[15]; char unsigned inputpointer=0; char unsigned outputpointer=0; // initialize pointers and buffer. void main() { ADCON1=0x0F; //turn analog off UART1_Init(115200); //initialize hardware UART @baudrate=115200, the same setting for the sensor Soft_UART_Init(&amp;PORTD,7,6,38400,0); //Initialize soft UART to commnuicate with a laptop Delay_ms(100); //let them stablize PIE1.RCIE = 1; //enable interrupt source INTCON.PEIE = 1; INTCON.GIE = 1; UART1_Write(0x00); //request a measurement. UART1_Write(0xE1); //each request is 2 bytes while(1){ Soft_UART_Write(dataRx[outputpointer]); //output one byte from the buffer to laptop outputpointer++; //increment output pointer if(outputpointer==0x0F) //reset pointer if it's at the end of the array { outputpointer=0x00; Soft_UART_Write(0x0D); //if it's at the end, that means the buffer is filled with exactly one measurement and it has been output to the laptop. So I can request another measurement. Soft_UART_Write(0x0A); //add \r\n UART1_Write(0x00); //request another measurement UART1_Write(0xE1); } } void interrupt(void){ //interrupt routine when a byte arrives dataRx[inputpointer]=UART1_Read(); //put a byte to a buffer inputpointer++; if (inputpointer==0x0F){inputpointer=0;} //reset pointer. </code></pre> <p>}</p>
0
1,074
Sending form using Ajax - Spring MVC
<p>I have problems with sending my form using Ajax.</p> <p>Here is form:</p> <pre><code>&lt;form method="POST" id="add-card-form" action="${pageContext.request.contextPath}/card/add" class="form-horizontal"&gt; &lt;select name="type" class="form-control"&gt; &lt;c:forEach items="${cardTypes}" var="cardType"&gt; &lt;option value="${cardType.id}"&gt;${cardType.name}&lt;/option&gt; &lt;/c:forEach&gt; &lt;/select&gt; &lt;select name="category" class="form-control"&gt; &lt;c:forEach items="${cardCategories}" var="cardCategory"&gt; &lt;option value="${cardCategory.id}"&gt;${cardCategory.name}&lt;/option&gt; &lt;/c:forEach&gt; &lt;/select&gt; &lt;textarea type="text" name="description" class="form-control" rows="6"&gt;&lt;/textarea&gt; &lt;input type="submit" id="add-card-submit" value="Add card" class="btn btn-primary"/&gt; </code></pre> <p></p> <p>Here is Ajax function:</p> <pre><code>$(document).on('submit', '#add-card-form', function(e) { var frm = $('#add-card-form'); e.preventDefault(); var Form = this; var data = {}; $.each(this, function(i, v){ var input = $(v); data[input.attr("name")] = input.val(); delete data["undefined"]; }); //temporary solution data["type"] = parseInt(data["type"]); data["category"] = parseInt(data["category"]); console.log(data); if(frm.valid()) { $.ajax({ contentType: "application/json; charset=utf-8", dataType: "json", type: frm.attr('method'), url: frm.attr('action'), data: JSON.stringify(data), success: reloadBoard, error: function (callback) { console.log(callback); } }); refreshForm(frm); } }); </code></pre> <p>And here is a controller action:</p> <pre><code>@RequestMapping(value="/add", method = RequestMethod.POST) public @ResponseBody Card addCard(@RequestBody Integer type, @RequestBody Integer category, @RequestBody String description) { Card card = new Card(); card.setType(cardTypeService.findById(type)); card.setCategory(cardCategoryService.findById(category)); card.setDescription(description); card.setOwner(1); cardService.saveCard(card); System.out.println("Card with id " + card.getId() + " added!"); return card; } </code></pre> <p>Variable data values:</p> <pre><code>Object {type: 1, category: 1, description: "New Card"} </code></pre> <p>When I try to send this form I always get error 400: <code>http://localhost:8080/card/add 400 (Bad Request)</code></p> <p>Can you tell me what is wrong with this code? I've ridden few posts, articles about sending data using Spring MVC + Ajax but no one helped.</p> <p><strong>EDIT:</strong></p> <p>I changed @RequestBody into three @RequestParams:</p> <pre><code> @RequestMapping(value="/add", method = RequestMethod.POST) public @ResponseBody Card addCard(@RequestParam("type") Integer type, @RequestParam("description") String description, @RequestParam("category") Integer category) { </code></pre> <p>I still get 400 error. Here is raw HTTP request: </p> <p><code>POST /card/add HTTP/1.1 Host: localhost:8080 Connection: keep-alive Content-Length: 48 Cache-Control: no-cache Pragma: no-cache Origin: http://localhost:8080 X-Requested-With: XMLHttpRequest Content-Type: application/json; charset=UTF-8 Accept: application/json, text/javascript, */*; q=0.01 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36 Referer: http://localhost:8080/ Accept-Encoding: gzip,deflate,sdch Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4 Cookie: JSESSIONID=ABAD895C419A9175EAB4D0833C543724</code></p> <p>And data object: </p> <pre><code>category: 1 description: "New Card" type: 1 </code></pre>
0
1,676
Changing background-color property of a class with javascript/jQuery
<p>This seems like a simple problem but nothing nothing is fixing it. I'm trying to dynamically change the background-color (from white or pink to green) on some text with javascript/jQuery but for some reason it's not working. The text is styled with a CSS class called ".novice".</p> <p>Here's the CSS. It's simple. I've also tried removing background-color completely so it does not already have a set background-color.</p> <pre><code>&lt;style type="text/css"&gt; .novice { background-color: pink; } &lt;/style&gt; </code></pre> <p>Here is an array with items I wrote out using a loop. The first item has the class "novice"</p> <pre><code>var achievements = ['&lt;span class="novice"&gt;novice - 10 or more guesses &lt;/span&gt;', ...] </code></pre> <p>Below is an if statement, which if true, is supposed to make the ".novice" class have a "background-color: green" property and make "novice - 10 or more guesses" be highlighted in green. I'm positive that I have the variable timesguessed set up correctly and spelled right. However when timesguessed is greater than 10, "novice..." will still not be highlighted in green. </p> <pre><code>if (timesguessed &gt; 10) { $('.novice').css('background-color', 'green'); } </code></pre> <p><strong>Am I typing this above portion right?</strong> I've also tried replacing $('.novice').css('background-color', 'green'); with $('.novice').background-color(green); , though that's probably wrong.</p> <p>Even if I print out another line with the supposedly newly modified "novice" class the text will still not be highlighted in green.</p> <pre><code>document.write('&lt;span class="novice"&gt;novice - 10 or more guesses &lt;/span&gt;'); </code></pre> <p>I know that the original CSS .novice class is working because the text will be highlighted in pink if no matter if timesguessed is greater or less than 10.</p> <p>I'm not sure if the Javascript is not modifying the CSS class, or what. Or maybe it does just something else is overriding it?</p> <p>Thanks for the help. Yeah I'm a beginner at javascript/jQuery.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;style type="text/css"&gt; .novice { } &lt;/style&gt; &lt;script type="text/javascript" src="../MM_JAVASCRIPT2E/MM_JAVASCRIPT2E/_js/jquery-1.6.3.min.js"&gt;&lt;/script&gt; &lt;title&gt;Number Guessing Game&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1 style="text-align:center;"&gt; Number Game &lt;/br&gt; Try to guess my number that is between 0-1000 &lt;/h1&gt; &lt;script&gt; // BEGIN LONG BLOCK OF CODE WITH GUESSING GAME MECHANISMS. You can ignore this part I think, this part works. var realnumber = prompt('Player 1, please enter a number for Player 2 to guess then hand it off to Player 2.', ''); while (isNaN(realnumber)) { realnumber = prompt('Player 1, please enter a NUMBER, dimwit, for Player 2 to guess.', '');} var timesguessed=0; while (numbertoguess != 0) { var numbertoguess = prompt("Player 2, guess a number", ""); while (isNaN(numbertoguess)) { numbertoguess = prompt('Please, type in a number');} // why don't I need an "else" here? numbertoguess = Math.abs(numbertoguess - realnumber); if ( numbertoguess &gt;= 50 ) { alert("Tundra cold"); timesguessed++; } else if ( 30 &lt;= numbertoguess &amp;&amp; numbertoguess &lt; 50) { alert("cold"); timesguessed++; } else if ( 20 &lt;= numbertoguess &amp;&amp; numbertoguess &lt; 30 ) { alert("warm"); timesguessed++; } else if ( 10 &lt;= numbertoguess &amp;&amp; numbertoguess&lt; 20 ) { alert("hot"); timesguessed++; } else if ( 5 &lt;= numbertoguess &amp;&amp; numbertoguess &lt; 10 ) { alert("Steaming hot!"); timesguessed++; } else if ( 3 &lt;= numbertoguess &amp;&amp; numbertoguess &lt; 5 ) { alert("SCALDING HOT!"); timesguessed++; } else if ( 1 &lt; numbertoguess &amp;&amp; numbertoguess &lt; 3 ) { alert("FIRE!"); timesguessed++; } else if ( numbertoguess == 1 ) { alert("Face Melting!"); timesguessed++; } else if ( numbertoguess == 0 ) { alert("BINGO!"); timesguessed++; } } document.write('&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;h2 style="text-align:center; font-size: 18px;"&gt; The number was ' + realnumber + '.'); if (timesguessed == 1) { document.write('&lt;/span&gt;&lt;h2 style="text-align:center;"&gt;It took you ' + timesguessed + ' guess.&lt;/h2&gt;'); } else { document.write('&lt;h2 style="text-align:center;"&gt;It took you ' + timesguessed + ' guesses.&lt;/h2&gt;'); } // END LONG BLOCK OF CODE WITH GUESSING GAME MECHANISMS document.write('&lt;/br&gt;&lt;/br&gt;') //below is the array written out with a loop var achievements = ['&lt;span class="novice"&gt;novice - 10 or more guesses &lt;/span&gt;',bronze - 7-10 guesses', 'silver', 'gold', 'titanium', 'platinum', 'diamond', ] var counter = 0; while (counter &lt; achievements.length) { document.write('&lt;h2 style="text-align:center;"&gt;' + achievements[counter] + ' '); counter++; } //below is the "if" function of question if (timesguessed &gt; 10) { $('.novice').css('background-color', '#00FF00'); //why does this not work? } document.write('&lt;span class="novice"&gt;novice - 10 or more guesses &lt;/span&gt;'); //why does this not work? &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
0
2,300
GDB Cannot insert breakpoint, Cannot access memory at address XXX?
<p>I wrote a really simple program:</p> <pre><code>ebrahim@ebrahim:~/test$ cat main.c int main() { int i = 0; return i; } </code></pre> <p>And the I compiled it with <code>-s</code> for <em>stripped</em> mode:</p> <pre class="lang-none prettyprint-override"><code>ebrahim@ebrahim:~/test$ gcc -s main.c -o f3 ebrahim@ebrahim:~/test$ file f3 f3: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=4dc6b893fbae8b418ca41ddeef948df1fcb26d3d, stripped </code></pre> <p>Now, I'm trying to find out the main function start address using GDB:</p> <pre class="lang-none prettyprint-override"><code>ebrahim@ebrahim:~/test$ gdb -nh f3 GNU gdb (Ubuntu 7.11.90.20161005-0ubuntu2) 7.11.90.20161005-git Copyright (C) 2016 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later &lt;http://gnu.org/licenses/gpl.html&gt; This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: &lt;http://www.gnu.org/software/gdb/bugs/&gt;. Find the GDB manual and other documentation resources online at: &lt;http://www.gnu.org/software/gdb/documentation/&gt;. For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from f3...(no debugging symbols found)...done. </code></pre> <p>As there is no <em>Symbol</em> info inside the file, I need to put a break at the file entry point and the disassemble it and find the start address of <code>main</code> function. So I used <code>info file</code> command to find the file <code>entry point</code> address:</p> <pre class="lang-none prettyprint-override"><code>(gdb) info file Symbols from "/home/ebrahim/test/f3". Local exec file: `/home/ebrahim/test/f3', file type elf64-x86-64. Entry point: 0x530 &lt;&lt;&lt;&lt;============= 0x0000000000000238 - 0x0000000000000254 is .interp 0x0000000000000254 - 0x0000000000000274 is .note.ABI-tag 0x0000000000000274 - 0x0000000000000298 is .note.gnu.build-id 0x0000000000000298 - 0x00000000000002b4 is .gnu.hash 0x00000000000002b8 - 0x0000000000000360 is .dynsym 0x0000000000000360 - 0x00000000000003f1 is .dynstr 0x00000000000003f2 - 0x0000000000000400 is .gnu.version 0x0000000000000400 - 0x0000000000000420 is .gnu.version_r 0x0000000000000420 - 0x00000000000004f8 is .rela.dyn 0x00000000000004f8 - 0x000000000000050f is .init 0x0000000000000510 - 0x0000000000000520 is .plt 0x0000000000000520 - 0x0000000000000528 is .plt.got 0x0000000000000530 - 0x00000000000006e2 is .text 0x00000000000006e4 - 0x00000000000006ed is .fini 0x00000000000006f0 - 0x00000000000006f4 is .rodata 0x00000000000006f4 - 0x0000000000000728 is .eh_frame_hdr 0x0000000000000728 - 0x000000000000081c is .eh_frame 0x0000000000200de0 - 0x0000000000200de8 is .init_array 0x0000000000200de8 - 0x0000000000200df0 is .fini_array 0x0000000000200df0 - 0x0000000000200df8 is .jcr 0x0000000000200df8 - 0x0000000000200fb8 is .dynamic 0x0000000000200fb8 - 0x0000000000201000 is .got 0x0000000000201000 - 0x0000000000201010 is .data 0x0000000000201010 - 0x0000000000201018 is .bss </code></pre> <p>As we expected the entry point is the start of <code>.text</code> section. So I put a breakpoint on this address:</p> <pre class="lang-none prettyprint-override"><code>(gdb) b *0x0000000000000530 Breakpoint 1 at 0x530 (gdb) r Starting program: /home/ebrahim/test/f3 Warning: Cannot insert breakpoint 1. Cannot access memory at address 0x530 (gdb) </code></pre> <p>The question is why GDB cannot insert this breakpoint?</p>
0
1,441
How to zoom a textview in android?
<p>Can anyone guide me to perform zoom in&amp;out operations on multiple views in android ? I need to perform zoom in&amp;out operations on touch of image, text views . What should be my parent layout? Here is the code to zoom an image on touch of imageview. How do i zoom a textview? Please help me. </p> <pre><code> // These matrices will be used to scale points of the image Matrix matrix = new Matrix(); Matrix savedMatrix = new Matrix(); // The 3 states (events) which the user is trying to perform static final int NONE = 0; static final int DRAG = 1; static final int ZOOM = 2; int mode = NONE; // these PointF objects are used to record the point(s) the user is touching PointF start = new PointF(); PointF mid = new PointF(); float oldDist = 1f; private void zoom(View v, MotionEvent event) { ImageView view = (ImageView) v; view.setScaleType(ImageView.ScaleType.MATRIX); float scale; // dumpEvent(event); // Handle touch events here... switch (event.getAction() &amp; MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: // first finger down only savedMatrix.set(matrix); start.set(event.getX(), event.getY()); mode = DRAG; break; case MotionEvent.ACTION_UP: // first finger lifted case MotionEvent.ACTION_POINTER_UP: // second finger lifted mode = NONE; break; case MotionEvent.ACTION_POINTER_DOWN: // first and second finger down oldDist = spacing(event); if (oldDist &gt; 5f) { savedMatrix.set(matrix); midPoint(mid, event); mode = ZOOM; } break; case MotionEvent.ACTION_MOVE: if (mode == DRAG) { matrix.set(savedMatrix); matrix.postTranslate(event.getX() - start.x, event.getY() - start.y); // create the transformation in the matrix of points } else if (mode == ZOOM) { // pinch zooming float newDist = spacing(event); if (newDist &gt; 5f) { matrix.set(savedMatrix); scale = newDist / oldDist; // setting the scaling of the // matrix...if scale &gt; 1 means // zoom in...if scale &lt; 1 means // zoom out matrix.postScale(scale, scale, mid.x, mid.y); } } break; } view.setImageMatrix(matrix); // display the transformation on screen } /* * -------------------------------------------------------------------------- * Method: spacing Parameters: MotionEvent Returns: float Description: * * checks the spacing between the two fingers on touch * ---------------------------------------------------- */ private float spacing(MotionEvent event) { float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return FloatMath.sqrt(x * x + y * y); } /* * -------------------------------------------------------------------------- * Method: midPoint Parameters: PointF object, MotionEvent Returns: void * Description: calculates the midpoint between the two fingers * ------------------------------------------------------------ */ private void midPoint(PointF point, MotionEvent event) { float x = event.getX(0) + event.getX(1); float y = event.getY(0) + event.getY(1); point.set(x / 2, y / 2); } </code></pre>
0
1,303
The source attachment does not contain the source for the file Layoutinflater.class
<p>I'm trying to write an android application that uses google maps api version 2.<br> In Debug the application crashes when it executes the instruction:</p> <pre><code> setContentView(R.layout.activity_poi_map); </code></pre> <p>This is the error:</p> <blockquote> <p>the source attachment does not contain the source for the file Layoutinflater.class</p> </blockquote> <p>I don't understand the reason. In headers I imported the whole class </p> <pre><code>android.view.* </code></pre> <p>Thank you in advance for any answer.</p> <p>This is the code:</p> <pre><code>public class PoiMap extends FragmentActivity { private GoogleMap pMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent callerIntent = getIntent(); final LatLng userCoord = callerIntent.getParcelableExtra("userCoord"); final Poi poi = (Poi) callerIntent.getSerializableExtra("poi"); setContentView(R.layout.activity_poi_map); setUpMapIfNeeded(userCoord); // Sets a callback that's invoked when the camera changes. pMap.setOnCameraChangeListener(new OnCameraChangeListener() { @Override /* Only use the simpler method newLatLngBounds(boundary, padding) to generate * a CameraUpdate if it is going to be used to move the camera *after* the map * has undergone layout. During layout, the API calculates the display boundaries * of the map which are needed to correctly project the bounding box. * In comparison, you can use the CameraUpdate returned by the more complex method * newLatLngBounds(boundary, width, height, padding) at any time, even before the * map has undergone layout, because the API calculates the display boundaries * from the arguments that you pass. * @see com.google.android.gms.maps.GoogleMap.OnCameraChangeListener#onCameraChange(com.google.android.gms.maps.model.CameraPosition) */ public void onCameraChange(CameraPosition arg0) { // Move camera. if (poi != null){ LatLng poiCoord = poi.getLatLng(); pMap.addMarker(new MarkerOptions() .position(poiCoord) .title(poi.getName()) .snippet(poi.getCategory()) .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_star))); Log.d("userCoord", userCoord.toString()); Log.d("poiCoord", poiCoord.toString()); double minY = Math.min(userCoord.latitude, poiCoord.latitude); double minX = Math.min(userCoord.longitude, poiCoord.longitude); double maxY = Math.max(userCoord.latitude, poiCoord.latitude); double maxX = Math.max(userCoord.longitude, poiCoord.longitude); Log.d("minY", " " + minY); Log.d("minX", " " + minX); Log.d("maxY", " " + maxY); Log.d("maxX", " " + maxX); LatLng northEast = new LatLng(maxY, maxX); LatLng southWest = new LatLng(minY, minX); LatLngBounds bounds = new LatLngBounds(southWest, northEast); // move camera pMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 40)); // Remove listener to prevent position reset on camera move. pMap.setOnCameraChangeListener(null); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_poi_map, menu); return true; } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(new LatLng(0.0, 0.0)); } private void setUpMapIfNeeded(LatLng coord) { // Do a null check to confirm that we have not already instantiated the map. if (pMap == null) { // Try to obtain the map from the SupportMapFragment. pMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (pMap != null) { setUpMap(coord); } } } private void setUpMap(LatLng userCoord) { pMap.addMarker(new MarkerOptions() .position(userCoord) .title("Your location") .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_user))); pMap.animateCamera(CameraUpdateFactory.newLatLng(userCoord)); /* public static CameraUpdate newLatLngZoom (LatLng latLng, float zoom) * Returns a CameraUpdate that moves the center of the screen to a latitude * and longitude specified by a LatLng object, and moves to the given zoom * level. * Parameters * latLng a LatLng object containing the desired latitude and longitude. * zoom the desired zoom level, in the range of 2.0 to 21.0. * Values below this range are set to 2.0, and values above it are set to 21.0. * Increase the value to zoom in. Not all areas have tiles at the largest zoom levels. * Returns * a CameraUpdate containing the transformation. */ pMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userCoord, 15)); } } </code></pre>
0
2,575
justify-content: space-between failing to align elements as expected
<p>I needed to use flexbox to center my navigation and hence I came up with the following:</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-css lang-css prettyprint-override"><code>.navbar-brand &gt; img { width: 100px; } .navbar-default { background-color: #fff; border-color: #fff; -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, .3); box-shadow: 0 0 3px rgba(0, 0, 0, .3); } .navbar-default .navbar-nav &gt; li &gt; a { color: #464646; text-transform: uppercase; } .navbar-default .navbar-nav &gt; li &gt; a:hover, .navbar-default .navbar-nav &gt; li &gt; a:focus, .navbar-default .navbar-nav &gt; li &gt; a:active { color: #727272; } .navbar-default .navbar-nav &gt; li:not(.active) &gt; a:before { content: ''; position: absolute; bottom: 0; left: 30%; right: 30%; height: 1px; background: #ed1c24; opacity: 0; -webkit-transform: translateY(10px); -ms-transform: translateY(10px); -o-transform: translateY(10px); transform: translateY(10px); -webkit-transition: all .3s; -o-transition: all .3s; transition: all .3s; } .navbar-default .navbar-nav &gt; li &gt; a:hover:before { opacity: 1; -webkit-transform: none; -ms-transform: none; -o-transform: none; transform: none; } .navbar-default .navbar-nav &gt; li:first-child &gt; a { font-weight: 700; } .navbar-default .navbar-nav &gt; li.active &gt; a { background: #ed1c24; color: #fff; padding-top: 25px; padding-bottom: 25px; position: relative; -webkit-transition: all .3s; -o-transition: all .3s; transition: all .3s; } .navbar-default .navbar-nav &gt; li.active &gt; a:hover, .navbar-default .navbar-nav &gt; li.active &gt; a:focus, .navbar-default .navbar-nav &gt; li.active &gt; a:active { background: #e0222a; color: #fff; } .navbar-default .navbar-nav &gt; li.active:hover &gt; a:after { bottom: 0; } .navbar-default .navbar-nav &gt; li.active &gt; a:after { font-family: FontAwesome; content: '\f078'; position: absolute; bottom: 5px; font-size: 0.6em; /*opacity: 0.8;*/ left: 50%; -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); -o-transform: translateX(-50%); transform: translateX(-50%); -webkit-transition: all .3s; -o-transition: all .3s; transition: all .3s; } /* use flexbox to center align nav elements above 992px */ @media (max-width: 992px) { .navbar-default .navbar-nav &gt; li &gt; a { text-align: center; } .navbar-collapse { max-height: 350px; overflow-y: hidden; } } @media (min-width: 992px) { .navbar-default { display: flex; align-items: center; justify-content: space-between; } .navbar-default { min-height: 100px; } .navbar-default .navbar-right { display: flex; align-items: center; } .navbar-default &gt; .container { display: flex; align-items: center; justify-content: space-between; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;nav role="navigation" class="navbar navbar-default navbar-fixed-top"&gt; &lt;div class="container"&gt; &lt;!-- Brand and toggle get grouped for better mobile display --&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a href="index.html" class="navbar-brand"&gt; &lt;img src="https://upload.wikimedia.org/wikipedia/commons/4/48/EBay_logo.png" alt="Logo"&gt; &lt;/a&gt; &lt;/div&gt; &lt;!-- Collection of nav links and other content for toggling --&gt; &lt;div id="navbarCollapse" class="collapse navbar-collapse"&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; &lt;li class="active"&gt;&lt;a href="index.html"&gt;Home&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="consulting.html"&gt;CONSULTING&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="devices.html"&gt;Medical Devices&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Servises&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;News&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Contact Us&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt;</code></pre> </div> </div> </p> <p><strong><a href="https://jsfiddle.net/7xL3ph5L/1/" rel="noreferrer">FIDDLE HERE</a></strong></p> <p>As you can see from the HTML , the <code>.container</code> has two child elements.</p> <p>I have the following CSS applied to the <code>.container</code> element:</p> <pre><code>.navbar-default &gt; .container{ display: flex; align-items:center; justify-content:space-between; } </code></pre> <p>The problem is <code>space-between</code> doesn't make the two child elements of the container to be at the left and right edges of the container. </p> <p>The behaviour that I want is that the two child elements should be on the left and right edge, this can be achieved using floats, I.E., I float one child to the left and one to the right.</p> <p>Also if you apply <code>flex-start</code> and <code>flex-end</code> the elements will be pulled to the edge but, with <code>flex-start</code> and <code>flex-end</code>, both elements will be pulled to one side. Hence I need to use <code>space-between</code>.</p> <p>Can somebody tell me why is <code>space-between</code> not working ? This bug is causing a huge alignment issue on my whole site, please somebody tell me what am I doing wrong.</p>
0
2,507
Converting XML file to another XML file using XSLT
<p>XML file 1:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;rentalProperties&gt; &lt;property contact ="1"&gt; &lt;type&gt;House &lt;/type&gt; &lt;price&gt;420&lt;/price&gt; &lt;address&gt; &lt;streetNo&gt;1&lt;/streetNo&gt; &lt;street&gt;Wavell Street&lt;/street&gt; &lt;suburb&gt;Box Hill&lt;/suburb&gt; &lt;state&gt;VIC&lt;/state&gt; &lt;zipcode&gt;3128&lt;/zipcode&gt; &lt;/address&gt; &lt;numberOfBedrooms&gt;3&lt;/numberOfBedrooms&gt; &lt;numberOfBathrooms&gt;1&lt;/numberOfBathrooms&gt; &lt;garage&gt;1&lt;/garage&gt; &lt;/property&gt; </code></pre> <p>XML file 2:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;rentalProperties&gt; &lt;property contact ="1"&gt; &lt;type&gt;House &lt;/type&gt; &lt;price&gt;420&lt;/price&gt; &lt;address&gt;1 wavell street,Box Hill,VIC,Australia&lt;/address&gt; &lt;numberOfBedrooms&gt;3&lt;/numberOfBedrooms&gt; &lt;numberOfBathrooms&gt;1&lt;/numberOfBathrooms&gt; &lt;garage&gt;1&lt;/garage&gt; &lt;/property&gt; </code></pre> <p>How should i convert xml file 1 to xml fle 2 using xslt? i want to represent the address as the single line and add a new attribute [country- Australia] to end of the line. i did the rest of it . i'm struggling with address line</p> <p>XSLT file:</p> <pre><code>&lt;?xml version="1.0" encoding="iso-8859-1"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" type="text/css" href="style.css"&gt; &lt;xsl:template match="/"&gt; &lt;rentalProperties&gt; &lt;property&gt; &lt;xsl:attribute name="contact"&gt;&lt;xsl:value-of select='@contact'/&gt;&lt;/xsl:attribute&gt; &lt;type&gt;&lt;xsl:value-of select="type"/&gt;&lt;/type&gt; &lt;price&gt;&lt;xsl:value-of select="price"/&gt;&lt;/price&gt; &lt;numberOfBedrooms&gt;&lt;xsl:value-of select="numberOfBedrooms"/&gt;&lt;/numberOfBedrooms&gt; &lt;numberOfBathrooms&gt;&lt;xsl:value-of select="numberOfBathrooms"/&gt;&lt;/numberOfBathrooms&gt; &lt;garage&gt;&lt;xsl:value-of select="garage"/&gt;&lt;/garage&gt; &lt;/property&gt; &lt;/rentalProperties&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre>
0
1,292
GridView.setOnItemClickListener is not working
<p>I have been suffering with one problem since 2days.I have a grid view in that i need to display images.When I click on grid item it has to go to next activity.I am able to display images in gridview but the thing is when I click on that item it is not responding..(OnItemClickListener is not working).I couldn't able to trace my problem where I have done wrong.</p> <pre><code> package com.logictreeit.mobilezop.fragments; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import com.logictreeit.mobilezop.adapters.PhotoAdapter; import com.logictreeit.mobilezop.custom.Utils; public class Dup_AlbumPhotosFragment extends Fragment implements OnItemClickListener { private static final String TAG = "AlbumPhotos Fragment"; private GridView gridView; private Context mContext; private PhotoAdapter photoAdapter; public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.v(TAG, "on Activity Created "); } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public void onAttach(Activity activity) { super.onAttach(activity); this.mContext = activity; } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.v(TAG, "OnCreateView"); gridView = new GridView(mContext); gridView.setNumColumns(GridView.AUTO_FIT); gridView.setClickable(true); gridView.setOnItemClickListener(this); photoAdapter = new PhotoAdapter(mContext, -1,Utils.getALbumList().get(0).getPhotosList()); gridView.setAdapter(photoAdapter); return gridView; } @Override public void onItemClick(AdapterView&lt;?&gt; arg0, View arg1, int arg2, long arg3) { Log.v(TAG, "on ItemClikced"); } } </code></pre> <p>This is my Fragment..</p> <pre><code> package com.logictreeit.mobilezop.adapters; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import com.logictreeit.mobilezop.R; import com.logictreeit.mobilezop.models.Photo; public class DupPhotoAdapter extends ArrayAdapter&lt;Photo&gt; { private static final String TAG = "PhotoAdapter"; private Context context; private List&lt;Photo&gt; photoList; public DupPhotoAdapter(Context context, int textViewResourceId, List&lt;Photo&gt; objects) { super(context, textViewResourceId, objects); this.context = context; this.photoList = objects; } public int getCount() { return photoList.size(); } public View getView(int position, View convertView, ViewGroup parent) { convertView = LayoutInflater.from(context).inflate( R.layout.grid_item_image_layout, null); ImageView imageView = (ImageView) convertView .findViewById(R.id.grid_item_imageview); final CheckBox checkBox = (CheckBox) convertView .findViewById(R.id.grid_item_checkbox); final Photo photo = photoList.get(position); if (photo.isSelected()) { checkBox.setChecked(true); } else { checkBox.setChecked(false); } imageView.setImageResource(Integer.parseInt(photo.getFileUrl())); checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { photo.setSelected(true); } else { photo.setSelected(false); } } }); return convertView; } } </code></pre> <p>This is my Adapter.</p> <p>If you guys know.Can u please tell me...</p> <p>Thanks, Chaitanya</p>
0
1,702
JSF FacesContext#addMessage is not displayed
<p>In my <a href="https://stackoverflow.com/questions/10367152/jsf-authentication-cannot-intercept-error-messages">previous question</a> I had the problem of displaying validation messages from a Login form. That issue is now solved, but this time I am not able to display a custom message with <code>FacesContex#addMessage</code>.</p> <p>Using JSF + PrimeFaces.</p> <pre><code>&lt;p:dialog header="Login" widgetVar="loginDlg"&gt; &lt;h:form id="loginForm"&gt; &lt;h:panelGrid columns="3" cellpadding="5"&gt; &lt;h:outputLabel for="username" value="Username:" /&gt; &lt;p:inputText value="#{loginBean.username}" id="username" required="true" label="username" /&gt; &lt;p:message for="username" /&gt; &lt;h:outputLabel for="password" value="Password:" /&gt; &lt;h:inputSecret value="#{loginBean.password}" id="password" required="true" label="password" /&gt; &lt;p:message for="password" /&gt; &lt;f:facet name="footer"&gt; &lt;p:commandButton value="Login" id="loginDlgButton" update=":loginForm,:welcomeMsg" actionListener="#{loginBean.login}" oncomplete="handleLoginRequest(xhr, status, args)"/&gt; &lt;p:message for="loginDlgButton" /&gt; &lt;/f:facet&gt; &lt;/h:panelGrid&gt; &lt;/h:form&gt; &lt;/p:dialog&gt; </code></pre> <p>In <strong>LoginBean</strong> (a <code>SessionScoped</code> <code>ManagedBean</code>):</p> <pre><code>public void login() { FacesContext context = FacesContext.getCurrentInstance(); RequestContext rContext = RequestContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); try { request.login(this.username, this.password); rContext.addCallbackParam("loggedIn", true); } catch (ServletException e) { rContext.addCallbackParam("loggedIn", false); context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid credentials")); } } </code></pre> <p>This code, when validation succeeds and login fails, should display the "Invalid credential" message, but doesn't. Moreover, somewhere in the body of my web page, I have also added this line:</p> <pre><code>&lt;p:messages autoUpdate="true" /&gt; </code></pre> <p>but my message isn't displayed even there.</p> <p><a href="http://docs.oracle.com/cd/E17802_01/j2ee/javaee/javaserverfaces/2.0/docs/api/javax/faces/context/FacesContext.html#addMessage%28java.lang.String,%20javax.faces.application.FacesMessage%29" rel="nofollow noreferrer">Javadocs</a> say that</p> <blockquote> <p>If clientId is null, this FacesMessage is assumed to not be associated with any specific component instance</p> </blockquote> <p>But I can't understand what this means.</p>
0
1,149
Restful API service
<p>I'm looking to make a service which I can use to make calls to a web-based REST API.</p> <p>Basically I want to start a service on app init then I want to be able to ask that service to request a url and return the results. In the meantime I want to be able to display a progress window or something similar.</p> <p>I've created a service currently which uses IDL, I've read somewhere that you only really need this for cross app communication, so think these needs stripping out but unsure how to do callbacks without it. Also when I hit the <code>post(Config.getURL("login"), values)</code> the app seems to pause for a while (seems weird - thought the idea behind a service was that it runs on a different thread!)</p> <p>Currently I have a service with post and get http methods inside, a couple of AIDL files (for two way communication), a ServiceManager which deals with starting, stopping, binding etc to the service and I'm dynamically creating a Handler with specific code for the callbacks as needed.</p> <p>I don't want anyone to give me a complete code base to work on, but some pointers would be greatly appreciated.</p> <p>Code in (mostly) full:</p> <pre><code>public class RestfulAPIService extends Service { final RemoteCallbackList&lt;IRemoteServiceCallback&gt; mCallbacks = new RemoteCallbackList&lt;IRemoteServiceCallback&gt;(); public void onStart(Intent intent, int startId) { super.onStart(intent, startId); } public IBinder onBind(Intent intent) { return binder; } public void onCreate() { super.onCreate(); } public void onDestroy() { super.onDestroy(); mCallbacks.kill(); } private final IRestfulService.Stub binder = new IRestfulService.Stub() { public void doLogin(String username, String password) { Message msg = new Message(); Bundle data = new Bundle(); HashMap&lt;String, String&gt; values = new HashMap&lt;String, String&gt;(); values.put("username", username); values.put("password", password); String result = post(Config.getURL("login"), values); data.putString("response", result); msg.setData(data); msg.what = Config.ACTION_LOGIN; mHandler.sendMessage(msg); } public void registerCallback(IRemoteServiceCallback cb) { if (cb != null) mCallbacks.register(cb); } }; private final Handler mHandler = new Handler() { public void handleMessage(Message msg) { // Broadcast to all clients the new value. final int N = mCallbacks.beginBroadcast(); for (int i = 0; i &lt; N; i++) { try { switch (msg.what) { case Config.ACTION_LOGIN: mCallbacks.getBroadcastItem(i).userLogIn( msg.getData().getString("response")); break; default: super.handleMessage(msg); return; } } catch (RemoteException e) { } } mCallbacks.finishBroadcast(); } public String post(String url, HashMap&lt;String, String&gt; namePairs) {...} public String get(String url) {...} }; </code></pre> <p>A couple of AIDL files:</p> <pre><code>package com.something.android oneway interface IRemoteServiceCallback { void userLogIn(String result); } </code></pre> <p>and </p> <pre><code>package com.something.android import com.something.android.IRemoteServiceCallback; interface IRestfulService { void doLogin(in String username, in String password); void registerCallback(IRemoteServiceCallback cb); } </code></pre> <p>and the service manager:</p> <pre><code>public class ServiceManager { final RemoteCallbackList&lt;IRemoteServiceCallback&gt; mCallbacks = new RemoteCallbackList&lt;IRemoteServiceCallback&gt;(); public IRestfulService restfulService; private RestfulServiceConnection conn; private boolean started = false; private Context context; public ServiceManager(Context context) { this.context = context; } public void startService() { if (started) { Toast.makeText(context, "Service already started", Toast.LENGTH_SHORT).show(); } else { Intent i = new Intent(); i.setClassName("com.something.android", "com.something.android.RestfulAPIService"); context.startService(i); started = true; } } public void stopService() { if (!started) { Toast.makeText(context, "Service not yet started", Toast.LENGTH_SHORT).show(); } else { Intent i = new Intent(); i.setClassName("com.something.android", "com.something.android.RestfulAPIService"); context.stopService(i); started = false; } } public void bindService() { if (conn == null) { conn = new RestfulServiceConnection(); Intent i = new Intent(); i.setClassName("com.something.android", "com.something.android.RestfulAPIService"); context.bindService(i, conn, Context.BIND_AUTO_CREATE); } else { Toast.makeText(context, "Cannot bind - service already bound", Toast.LENGTH_SHORT).show(); } } protected void destroy() { releaseService(); } private void releaseService() { if (conn != null) { context.unbindService(conn); conn = null; Log.d(LOG_TAG, "unbindService()"); } else { Toast.makeText(context, "Cannot unbind - service not bound", Toast.LENGTH_SHORT).show(); } } class RestfulServiceConnection implements ServiceConnection { public void onServiceConnected(ComponentName className, IBinder boundService) { restfulService = IRestfulService.Stub.asInterface((IBinder) boundService); try { restfulService.registerCallback(mCallback); } catch (RemoteException e) {} } public void onServiceDisconnected(ComponentName className) { restfulService = null; } }; private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() { public void userLogIn(String result) throws RemoteException { mHandler.sendMessage(mHandler.obtainMessage(Config.ACTION_LOGIN, result)); } }; private Handler mHandler; public void setHandler(Handler handler) { mHandler = handler; } } </code></pre> <p>Service init and bind:</p> <pre><code>// this I'm calling on app onCreate servicemanager = new ServiceManager(this); servicemanager.startService(); servicemanager.bindService(); application = (ApplicationState)this.getApplication(); application.setServiceManager(servicemanager); </code></pre> <p>service function call:</p> <pre><code>// this lot i'm calling as required - in this example for login progressDialog = new ProgressDialog(Login.this); progressDialog.setMessage("Logging you in..."); progressDialog.show(); application = (ApplicationState) getApplication(); servicemanager = application.getServiceManager(); servicemanager.setHandler(mHandler); try { servicemanager.restfulService.doLogin(args[0], args[1]); } catch (RemoteException e) { e.printStackTrace(); } ...later in the same file... Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case Config.ACTION_LOGIN: if (progressDialog.isShowing()) { progressDialog.dismiss(); } try { ...process login results... } } catch (JSONException e) { Log.e("JSON", "There was an error parsing the JSON", e); } break; default: super.handleMessage(msg); } } }; </code></pre>
0
3,022
Whenever gem 'failed to load command: rake'
<p>looking for some help.</p> <p>I am running a rails app (v3.2.5) with the <code>whenever</code> gem (v0.9.7) and <code>rake</code> (v11.2.2). I am also doing this in a docker container image <code>ruby:2.3</code> (<code>cron</code> was installed and <code>bundle install</code> was ran)</p> <p>Here is my <code>schedule.rb</code></p> <pre><code>set :environment, ENV['RAILS_ENV'] every '*/2 9,10,11,12,13,14,15,16 * * 1-5' do rake "import_csv", output: {:error =&gt; 'log/import_csv_errors.log', :standard =&gt; 'log/import_csv.log'}' end </code></pre> <p><em>note</em> <code>RAILS_ENV</code> is set at container launch to <code>development</code></p> <p>Here is my cron job that is on the container after build (<code>crontab -l</code>):</p> <pre><code># Begin Whenever generated tasks for: /usr/src/app/config/schedule.rb */2 9,10,11,12,13,14,15,16 * * 1-5 /bin/bash -l -c 'cd /usr/src/app &amp;&amp; RAILS_ENV=development bundle exec rake import_csv --silent &gt;&gt; log/import_csv.log 2&gt;&gt; log/import_csv_errors.log' # End Whenever generated tasks for: /usr/src/app/config/schedule.rb </code></pre> <p>When this cron job runs, the logs return:</p> <p><strong>import_csv_errors.log</strong></p> <pre><code>Bundler::GemNotFound: Could not find rake-11.2.2 in any of the sources /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/spec_set.rb:95:in `block in materialize' /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/spec_set.rb:88:in `map!' /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/spec_set.rb:88:in `materialize' /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/definition.rb:140:in `specs' /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/definition.rb:185:in `specs_for' /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/definition.rb:174:in `requested_specs' /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/environment.rb:19:in `requested_specs' /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:14:in `setup' /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler.rb:95:in `setup' /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/setup.rb:19:in `&lt;top (required)&gt;' /usr/local/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' /usr/local/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' </code></pre> <p><strong>import_csv.log</strong></p> <pre><code>bundler: failed to load command: rake (/usr/local/bin/rake) </code></pre> <p>Now here is the odd thing. If I copy the cron job command: </p> <pre><code>/bin/bash -l -c 'cd /usr/src/app &amp;&amp; RAILS_ENV=development bundle exec rake import_csv --silent &gt;&gt; log/import_csv.log 2&gt;&gt; log/import_csv_errors.log' </code></pre> <p>and run this in the container, it works fine, but if the cron job runs it, I get thos errors in the logs!!! I am at a lost here...</p> <p>I've tried adding </p> <pre><code>env :PATH, ENV['PATH'] env :GEM_PATH, '/usr/local/bundle' </code></pre> <p>to the top of <code>schedule.rb</code> and I tried doing</p> <pre><code>command 'cd /usr/src/app &amp;&amp; RAILS_ENV=development bundle exec rake import_csv --silent &gt;&gt; log/import_csv.log 2&gt;&gt; log/import_csv_errors.log' </code></pre> <p>Instead of using <code>rake</code> in the task and I get the same errors..</p> <p>Any help is appriciated</p>
0
1,524
React native :Unable to resolve module Indeed, none of these files exist:
<p>I'm following <a href="https://medium.com/@farid12ansari7/floating-title-or-placeholder-text-input-field-react-native-5fb5932669d" rel="noreferrer">this medium article</a> to use <code>FloatingTitleTextInputField</code> in my react-native project</p> <p>below is my project structure</p> <p><a href="https://i.stack.imgur.com/FW8o2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FW8o2.png" alt="enter image description here"></a></p> <p>Here is my code for <code>HomeScreen.js</code></p> <pre><code>import React, {Component} from 'react'; import {Text, View, TextInput, StyleSheet} from 'react-native'; import FloatingTitleTextInputField from './customComponents/floating_title_text_input_field'; export default class HomeScreen extends Component { render() { return ( // &lt;View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}&gt; // &lt;Text&gt;My First React App&lt;/Text&gt; // &lt;TextInput style={{height: 40, borderColor: 'gray', borderWidth: 1}} /&gt; // &lt;/View&gt; &lt;View style={styles.container}&gt; &lt;View style={styles.container}&gt; &lt;Text style={styles.headerText}&gt;Its Amazing&lt;/Text&gt; &lt;FloatingTitleTextInputField attrName="firstName" title="First Name" value={this.state.firstName} updateMasterState={this._updateMasterState} /&gt; &lt;FloatingTitleTextInputField attrName="lastName" title="Last Name" value={this.state.lastName} updateMasterState={this._updateMasterState} /&gt; &lt;/View&gt; &lt;/View&gt; ); } } var styles = StyleSheet.create({ container: { flex: 1, paddingTop: 65, backgroundColor: 'white', }, labelInput: { color: '#673AB7', }, formInput: { borderBottomWidth: 1.5, marginLeft: 20, borderColor: '#333', }, input: { borderWidth: 0, }, }); </code></pre> <p>When i try to use <code>FloatingTitleTextInputField</code> inside <code>HomeScreen.js</code> I'm getting below error</p> <pre><code> error Unable to resolve module `./floating_title_text_input_field` from `React Native/AwesomeProject/screens/ HomeScreen.js`: The module `./floating_title_text_input_field` could not be found from `/React Native/AwesomeProject/screens/HomeScreen.js`. Indeed, none of these files exist: * `/React Native/AwesomeProject/screens/floating_title_text_input_field(.native||.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)` * `/React Native/AwesomeProject/screens/floating_title_text_input_field/index(.native||.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)`. Run CLI with --verbose flag for more details. Error: Unable to resolve module `./floating_title_text_input_field` from `React Native/AwesomeProject/screens/HomeScreen.js`: The module `./floating_title_text_input_field` could not be found from `/React Native/AwesomeProject/screens/HomeScreen.js`. Indeed, none of these files exist: </code></pre> <p>Can anybody help me to solve this issue</p> <p>If need more information please do let me know. Thanks in advance. Your efforts will be appreciated.</p>
0
1,321
jboss eap-6.1 Failed to process phase POST_MODULE of deployment \"education.war\"
<p>Used hibernate, spring mvc. Files:</p> <p>web.xml</p> <pre><code> &lt;web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt; &lt;display-name&gt;Spring MVC Application&lt;/display-name&gt; &lt;filter&gt; &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt; &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;servlet&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;url-pattern&gt;*.css&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;url-pattern&gt;*.js&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;url-pattern&gt;*.gif&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;url-pattern&gt;*.jpg&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;url-pattern&gt;*.png&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt; </code></pre> <p>main context file</p> <pre><code>&lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd" &gt; &lt;context:component-scan base-package="com.education"/&gt; &lt;context:component-scan base-package="com.education.controllers"/&gt; &lt;bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/WEB-INF/pages/"/&gt; &lt;property name="suffix" value=".jsp"/&gt; &lt;/bean&gt; &lt;mvc:annotation-driven /&gt; &lt;mvc:resources mapping="/resources/**" location="/resources/" /&gt; &lt;import resource="root-context.xml" /&gt; &lt;/beans&gt; </code></pre> <p>root-context.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"&gt; &lt;context:annotation-config /&gt; &lt;context:component-scan base-package="com.education.Dao" /&gt; &lt;context:component-scan base-package="com.education.Service" /&gt; &lt;import resource="data.xml" /&gt; &lt;import resource="security.xml" /&gt; &lt;/beans&gt; </code></pre> <p>Before i successuly compile and run this application, then add hibernate code and this xml files and meet error.</p> <p>Error code</p> <blockquote> <p>16:40:50,403 ERROR [org.jboss.as.server] (management-handler-thread - 12) JBAS015870: Deploy of deployment "education.war" was rolled back with the following failure message: {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"education.war\".POST_MODULE" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"education.war\".POST_MODULE: JBAS018733: Failed to process phase POST_MODULE of deployment \"education.war\" Caused by: java.lang.LinkageError: Failed to link org/springframework/web/filter/GenericFilterBean (Module \"deployment.education.war:main\" from Service Module Loader) Caused by: java.lang.NoClassDefFoundError: org/springframework/context/EnvironmentAware Caused by: java.lang.ClassNotFoundException: org.springframework.context.EnvironmentAware from [Module \"deployment.education.war:main\" from Service Module Loader]"}} 16:40:50,533 INFO [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015877: Stopped deployment education.war (runtime-name: education.war) in 130ms</p> </blockquote>
0
2,798
Js Date object to python datetime
<p>I am working with dhtmlxscheduler and I am sending dates to the django server for processing.</p> <p>Dhtmlxscheduler provides me with the following date object, the methods provided start from the second line below:</p> <pre><code>end_date: Sat Nov 19 2011 01:00:00 GMT-0500 (EST) __proto__: Invalid Date constructor: function Date() { [native code] } getDate: function getDate() { [native code] } getDay: function getDay() { [native code] } getFullYear: function getFullYear() { [native code] } getHours: function getHours() { [native code] } getMilliseconds: function getMilliseconds() { [native code] } getMinutes: function getMinutes() { [native code] } getMonth: function getMonth() { [native code] } getSeconds: function getSeconds() { [native code] } getTime: function getTime() { [native code] } getTimezoneOffset: function getTimezoneOffset() { [native code] } getUTCDate: function getUTCDate() { [native code] } getUTCDay: function getUTCDay() { [native code] } getUTCFullYear: function getUTCFullYear() { [native code] } getUTCHours: function getUTCHours() { [native code] } getUTCMilliseconds: function getUTCMilliseconds() { [native code] } getUTCMinutes: function getUTCMinutes() { [native code] } getUTCMonth: function getUTCMonth() { [native code] } getUTCSeconds: function getUTCSeconds() { [native code] } getYear: function getYear() { [native code] } setDate: function setDate() { [native code] } setFullYear: function setFullYear() { [native code] } setHours: function setHours() { [native code] } setMilliseconds: function setMilliseconds() { [native code] } setMinutes: function setMinutes() { [native code] } setMonth: function setMonth() { [native code] } setSeconds: function setSeconds() { [native code] } setTime: function setTime() { [native code] } setUTCDate: function setUTCDate() { [native code] } setUTCFullYear: function setUTCFullYear() { [native code] } setUTCHours: function setUTCHours() { [native code] } setUTCMilliseconds: function setUTCMilliseconds() { [native code] } setUTCMinutes: function setUTCMinutes() { [native code] } setUTCMonth: function setUTCMonth() { [native code] } setUTCSeconds: function setUTCSeconds() { [native code] } setYear: function setYear() { [native code] } toDateString: function toDateString() { [native code] } toGMTString: function toGMTString() { [native code] } toISOString: function toISOString() { [native code] } toJSON: function toJSON() { [native code] } toLocaleDateString: function toLocaleDateString() { [native code] } toLocaleString: function toLocaleString() { [native code] } toLocaleTimeString: function toLocaleTimeString() { [native code] } toString: function toString() { [native code] } toTimeString: function toTimeString() { [native code] } toUTCString: function toUTCString() { [native code] } valueOf: function valueOf() { [native code] } __proto__: Object </code></pre> <p>What is the easiest method for choosing one of these toString methods and then parsing it on the python server side using datetime.strptime() to create a python datetime object?</p> <p>The simple toString method returns me a datetime in the format:</p> <pre><code>Sat Nov 19 2011 00:00:00 GMT-0500 (EST) </code></pre> <p>Trying the different format directives proves unsuccessful.</p> <p>ie:</p> <pre><code>datetime.strptime("Sat Nov 19 2011 00:00:00 GMT-0500 (EST)", "%a %b %d %Y %H:%M:%S %Z") ---&gt; unconverted data remains: -0500 (EST) </code></pre> <p>and:</p> <pre><code>datetime.strptime("Sat Nov 19 2011 00:00:00 GMT-0500 (EST)", "%a %b %d %Y %H:%M:%S %z") ---&gt; ValueError: 'z' is a bad directive in format '%a %b %d %Y %H:%M:%S %z' </code></pre>
0
1,180
How to create Select List for Country and States/province in MVC
<p>Hi I am new to MVC and even asp.. </p> <p>I want to create a form in MVC. With the help of some examples I am able to create TextBoxes, but I now I don't understand how to create Select List./</p> <p>I tried searching many examples for implementing Select List in MVC, but I am not able to understand.</p> <p>I have a Form which is half coded in HTML and half in MVC.</p> <p>Here is my Code:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MedAvail.Applications.MedProvision.Web.Models { public class AddressViewModel { public string Street1 { get; set; } public string Street2 { get; set; } public string City { get; set; } public string Province { get; set; } public string Country { get; set; } public string PostalCode { get; set; } public string PhoneNumber { get; set; } } } &lt;form id="locationInfo"&gt; &lt;h1&gt;Location Information&lt;/h1&gt; &lt;table width="80%" id="locInfo"&gt; &lt;colgroup&gt; &lt;col width="20%" /&gt; &lt;col /&gt; &lt;/colgroup&gt; &lt;tr&gt; &lt;th&gt;@Html.Label("Country")&lt;/th&gt; &lt;td&gt; &lt;select required=""&gt; &lt;option&gt;Select Country&lt;/option&gt; &lt;option&gt;Canada&lt;/option&gt; &lt;option&gt;United States&lt;/option&gt; &lt;/select&gt; &lt;span class="required"&gt;*&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;@Html.LabelFor(x=&gt;x.State)&lt;/th&gt; &lt;td&gt; &lt;select required=""&gt; &lt;option&gt;Select State&lt;/option&gt; &lt;option&gt;State 1&lt;/option&gt; &lt;option&gt;State 2&lt;/option&gt; &lt;option&gt;State 3&lt;/option&gt; ............... &lt;/select&gt;&lt;span class="required"&gt;*&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;@Html.LabelFor(x=&gt;x.PostalCode)&lt;/th&gt; &lt;td&gt;@Html.TextBoxFor(x=&gt;x.PostalCode)&lt;span class="required"&gt;*&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;@Html.LabelFor(x=&gt;x.City)&lt;/th&gt; &lt;td&gt;@Html.TextBoxFor(x=&gt;x.City)&lt;span class="required"&gt;*&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;@Html.LabelFor(x=&gt;x.StreetAddress1)&lt;/th&gt; &lt;td&gt;@Html.TextBoxFor(x=&gt;x.StreetAddress1)&lt;span class="required"&gt;*&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;@Html.LabelFor(x=&gt;x.StreetAddress2)&lt;/th&gt; &lt;td&gt;@Html.TextBoxFor(x=&gt;x.StreetAddress2)&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;@Html.LabelFor(x=&gt;x.PhoneNumber)&lt;/th&gt; &lt;td&gt;@Html.TextBoxFor(x=&gt;x.PhoneNumber)&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;div role="button" class="marginTop50 marginBottom"&gt; &lt;input type="button" id="step3Back" value="Back" class="active" /&gt; &lt;input type="button" id="step3confirmNext" value="Next" class="active marginLeft50" /&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>Please guide me on how to create the Select List for this kind of form.</p>
0
1,941
how to bind control to json model in sapui
<blockquote> <p>why can't i use these <code>sap.ui.getCore().setModel(oModel) and this.getView().setModel("oModel","someModel")</code> in functions other than life cycle hooks of controller in sapui5.</p> <p>I am trying to bind model to the controls of my view without giving it an id. so i want to make a model and set that model to the view where i will bind.</p> </blockquote> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge" /&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Handler Context in JavaScript Views&lt;/title&gt; &lt;script id="sap-ui-bootstrap" type="text/javascript" src="https://sapui5.netweaver.ondemand.com/resources/sap-ui-core.js" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-libs="sap.m" data-sap-ui-xx-bindingSyntax="complex" &gt; &lt;/script&gt; &lt;script&gt; jQuery.sap.require("sap.m.MessageToast"); sap.ui.jsview("local.view", { getControllerName: function() { return "local.controller"; }, createContent: function(oController) { var oText=new sap.m.Text(); oText.bindProperty("text","oModel&gt;/myData"); var oInput=new sap.m.Input(); oInput.bindValue("oModel&gt;/myData"); var oIn=new sap.m.Input(); oIn.bindValue("oModel&gt;/myData"); var oBar=new sap.m.Bar({contentLeft:oIn,contentMiddle:oText}); var oButton=new sap.m.Button({text:"press to reset", press:function(){ oController.resetModel(); } }); var oPage=new sap.m.Page({headerContent:[oInput],footer:oBar,showNavButton:true,content:[oButton]}); var oShell=new sap.m.App({pages:oPage}); return oShell; } }); sap.ui.controller("local.controller", { onInit:function(){ var aData={"myData":"enter!!"}; var oModel=new sap.ui.model.json.JSONModel(); oModel.setData(aData); sap.ui.getCore().setModel(oModel,"oModel"); }, resetModel:function(){ var oModel=sap.ui.getCore().getModel("oModel"); oModel.oData.myData="Reset"; } }); sap.ui.view({ type: sap.ui.core.mvc.ViewType.JS, viewName: "local.view" }).placeAt("uiArea"); &lt;/script&gt; &lt;/head&gt; &lt;body class="sapUiBody" role="application"&gt; &lt;div id="uiArea"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>how can i update my model which is bound to other controls on button press</p> <p>Is there any way to access controls in controller of my view without giving it an id?<br> Regards, Ajaay </p>
0
1,494
Hibernate - ManyToOne & Inheritance / JOINED / mappedBy
<p>I have some problems with inheritance mapping. Here my database structure:</p> <p><img src="https://i.stack.imgur.com/9PPZS.png" alt="enter image description here"></p> <p>And associated entities:</p> <h3>AbstractEntity:</h3> <pre><code>@MappedSuperclass public abstract class AbstractEntity&lt;ID extends Serializable&gt; implements Serializable { @Id @GeneratedValue(strategy = IDENTITY) @Column(unique = true, updatable = false, nullable = false) private ID id; public ID getId() { return id; } @SuppressWarnings("unused") public void setId(ID id) { this.id = id; } </code></pre> <h3>UserAcitvity entity:</h3> <pre><code>@Entity @Table(name = "user_activity") @Inheritance(strategy = JOINED) @AttributeOverride(name = "id", column = @Column(name = "ua_id")) public abstract class UserActivity extends AbstractEntity&lt;Long&gt; { @ManyToOne(cascade = { MERGE, PERSIST }, fetch = LAZY) @JoinColumn(name = "ua_user_id") private User user; ... } </code></pre> <h3>Comment entity:</h3> <pre><code>@Entity @Table(name = "comment") @PrimaryKeyJoinColumn(name = "cm_id") public class Comment extends UserActivity { @ManyToOne(cascade = { MERGE, PERSIST }, fetch = LAZY) @JoinColumn(name = "cm_question_id") private Question question; ... } </code></pre> <h3>Question entity:</h3> <pre><code>@Entity @Table(name = "question") @PrimaryKeyJoinColumn(name = "qs_id") public class Question extends UserActivity { ... @OneToMany(fetch = LAZY, cascade = ALL, mappedBy = "question") private List&lt;Answer&gt; answers = new ArrayList&lt;&gt;(); @OneToMany(fetch = LAZY, cascade = ALL, mappedBy = "question") private List&lt;Comment&gt; comments = new ArrayList&lt;&gt;(); ... } </code></pre> <h3>Answer entity:</h3> <pre><code>@Entity @Table(name = "answer") @PrimaryKeyJoinColumn(name = "asw_id") public class Answer extends UserActivity { @ManyToOne(cascade = { MERGE, PERSIST }, fetch = LAZY) @JoinColumn(name = "asw_question_id") private Question question; ... } </code></pre> <h3>and User entity:</h3> <pre><code>@Entity @Table(name = "user") @AttributeOverride(name = "id", column = @Column(name = "user_id")) public class User extends AbstractEntity&lt;Long&gt; { ... @OneToMany(cascade = REMOVE) private List&lt;Question&gt; questions = new ArrayList&lt;&gt;(); @OneToMany(cascade = REMOVE) private List&lt;Answer&gt; answers = new ArrayList&lt;&gt;(); @OneToMany(cascade = REMOVE) private List&lt;Comment&gt; comments = new ArrayList&lt;&gt;(); ... } </code></pre> <h3>Problem:</h3> <p>When I try to save or delete a <code>User</code> I get an exceptions:</p> <pre><code>org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [insert into user_question (user_user_id, questions_qs_id) values (?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement </code></pre> <p>and:</p> <pre><code>org.hibernate.engine.jdbc.spi.SqlExceptionHelper : 147 = user lacks privilege or object not found: USER_ANSWER </code></pre> <p>Hibernate is trying to create a table: <code>user_question</code> and <code>user_answer</code> which me <strong>do not need</strong>.</p> <p>What I should doing for fixes ?</p>
0
1,161
Connection.Start().Done() SignalR Issue
<p>I am designing a real-time document editor web application similar to google docs using SignalR connections. </p> <p>It is working ok i.e. when I am writing in one editor in a browser, text is being displayed on the other open browsers I have. The only problem I have is that when at first I write some text it is not being displayed, then I delete and write again and everything is ok.</p> <p>When I debug using F12 in Chrome I am getting this error:</p> <pre><code>Uncaught Error: SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started. </code></pre> <p>I don't understand this since in my code I am actually using $.connection.hub.start.done(). Here is the hub I am using:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; namespace Write.ly { [HubName("editor")] public class EditorHub : Hub { public void Send(string message) { Clients.Others.broadcastMessage(message); } } } </code></pre> <p>And this is the JavaScript and html associated with this. Please note that I am using tinyMCE as a plug-in for the editor.</p> <pre><code>@{ ViewBag.Title = "- Editor"; ViewBag.ContentStyle = "/Content/CSS/editor.css"; } &lt;script src="~/Scripts/jquery.signalR-1.0.1.min.js"&gt;&lt;/script&gt; &lt;script src="~/signalr/hubs"&gt;&lt;/script&gt; &lt;script src="~/Content/TinyMCE/tiny_mce.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(function () { var hub = $.connection.editor; tinyMCE.init({ mode: "textareas", theme: "advanced", plugins: "emotions,spellchecker,advhr,insertdatetime,preview", // Theme options - button# indicated the row# only theme_advanced_buttons1: "newdocument,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,fontselect,fontsizeselect,formatselect", theme_advanced_buttons2: "cut,copy,paste,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,|,code,preview,|,forecolor,backcolor", theme_advanced_buttons3: "insertdate,inserttime,|,spellchecker,advhr,,removeformat,|,sub,sup,|,charmap,emotions", theme_advanced_toolbar_location: "top", theme_advanced_toolbar_align: "left", theme_advanced_statusbar_location: "bottom", theme_advanced_resizing: false, setup: function (ed) { ed.onKeyUp.add(function (ed, e) { hub.client.broadcastMessage = function (message) { var bookmark = ed.selection.getBookmark(2, true); tinyMCE.activeEditor.setContent(message); ed.selection.moveToBookmark(bookmark); }; $.connection.hub.start().done(function () { var text = tinyMCE.activeEditor.getContent(); hub.server.send(text); }); }); } }); }); &lt;/script&gt; &lt;form method="post" action="somepage"&gt; &lt;textarea id="editor" name="content" cols="100" rows="30"&gt;&lt;/textarea&gt; &lt;/form&gt; &lt;button class="btn" onclick="ajaxSave();"&gt;&lt;span&gt;Save&lt;/span&gt;&lt;/button&gt; </code></pre> <p>Any ideas?</p>
0
1,525
save arraylist in shared preference
<p>I am storing values in <code>ArrayList</code> and pass it to using bundle to next <code>Fragment</code>, and there I set values to my <code>TextView</code>, till here it works fine, now when go to another page and proceed to app and come back again to that <code>Fragment</code>, my all data goes, so I am trying to store it in preferences but preference don't allow to access <code>ArrayList</code>, following is my code</p> <pre><code> public class Add_to_cart extends Fragment { private Button continue_shopping; private Button checkout; ListView list; private TextView _decrease,mBTIncrement,_value; private CustomListAdapter adapter; private ArrayList&lt;String&gt; alst; private ArrayList&lt;String&gt; alstimg; private ArrayList&lt;String&gt; alstprc; private String bname; private ArrayList&lt;String&gt; alsttitle; private ArrayList&lt;String&gt; alsttype; public static ArrayList&lt;String&gt; static_Alst; public Add_to_cart(){} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.list_view_addtocart, container, false); alst=new ArrayList&lt;String&gt;(); alstimg=new ArrayList&lt;String&gt;(); Bundle bundle = this.getArguments(); alst = bundle.getStringArrayList("prducts_id"); alsttype = bundle.getStringArrayList("prducts_type"); alstimg=bundle.getStringArrayList("prducts_imgs"); alsttitle=bundle.getStringArrayList("prducts_title"); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); System.out.println("TEst--" + alst); // Toast.makeText(getActivity(),"Testing"+alstimg,Toast.LENGTH_LONG).show(); list=(ListView)rootView.findViewById(R.id.list_addtocart); adapter = new CustomListAdapter(getActivity(),alst,alstimg,alsttitle,alsttype); list.setAdapter(adapter); adapter.notifyDataSetChanged(); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view,int position, long id) { // TODO Auto-generated method stub } }); return rootView; } public class CustomListAdapter extends BaseAdapter { private Context context; private ArrayList&lt;String&gt; listData; private ArrayList&lt;String&gt; listDataimg; private ArrayList&lt;String&gt; listDatatitle; private ArrayList&lt;String&gt; listDatatype; private AQuery aQuery; String dollars="\u0024"; public CustomListAdapter(Context context,ArrayList&lt;String&gt; listData,ArrayList&lt;String&gt; listDataimg,ArrayList&lt;String&gt; listDatatitle,ArrayList&lt;String&gt; listDatatype) { this.context = context; this.listData=listData; this.listDataimg=listDataimg; this.listDatatitle=listDatatitle; this.listDatatype=listDatatype; aQuery = new AQuery(this.context); } public void save_User_To_Shared_Prefs(Context context) { SharedPreferences appSharedPrefs = PreferenceManager .getDefaultSharedPreferences(context.getApplicationContext()); SharedPreferences.Editor prefsEditor = appSharedPrefs.edit(); Gson gson = new Gson(); String json = gson.toJson(listData); Add_to_cart.static_Alst=listData; prefsEditor.putString("user", json); prefsEditor.commit(); } @Override public int getCount() { return listData.size(); } @Override public Object getItem(int position) { return listData.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_addtocart, null); holder.propic = (ImageView) convertView.findViewById(R.id.img_addtocart); holder.txtproname = (TextView) convertView.findViewById(R.id.proname_addtocart); holder.txtprofilecast = (TextView) convertView.findViewById(R.id.proprice_addtocart); holder.txtsize = (TextView) convertView.findViewById(R.id.txt_size); _decrease = (TextView) convertView.findViewById(R.id.minuss_addtocart); mBTIncrement = (TextView) convertView.findViewById(R.id.plus_addtocart); _value = (EditText)convertView.findViewById(R.id.edt_procount_addtocart); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } mBTIncrement.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { increment(); } }); _decrease.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { decrement(); } }); holder.txtprofilecast.setText(dollars+listData.get(position)); holder.txtproname.setText(listDatatitle.get(position)); holder.txtsize.setText(listDatatype.get(position)); System.out.println("Image ka array " + listDataimg.get(position)); //Picasso.with(mContext).load(mThumbIds[position]).centerCrop().into(imageView); // Picasso.with(context).load(listDataimg.get(position)).into(holder.propic); aQuery.id(holder.propic).image(listDataimg.get(position), true, true, 0, R.drawable.ic_launcher); return convertView; } class ViewHolder{ ImageView propic; TextView txtproname; TextView txtprofilecast; TextView txtsize; } } } </code></pre>
0
2,807
JdbcTemplate query close database connection
<p>I use jpa with hibernate. I have following method:</p> <pre><code>@Transactional public void myMethod(){ ... firstJDBCTemplateQuery(); secondJDBCTemplateQuery(); ... } </code></pre> <p><code>firstJDBCTemplateQuery</code> works, but it closes connection to database. When second <code>secondJDBCTempolateQuery</code> is executed </p> <p><code>java.sql.SQLException: Connection is closed exception</code></p> <p>is thrown what causes</p> <p><code>org.springframework.transaction.TransactionSystemException: Could not roll back JPA transaction ...</code> </p> <p>My configuration: <strong>EDIT</strong> </p> <pre><code> &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"&gt; &lt;property name="driverClassName" value="${jdbc.driverClassName}" /&gt; &lt;property name="url" value="${jdbc.url}" /&gt; &lt;property name="username" value="${jdbc.username}" /&gt; &lt;property name="password" value="${jdbc.password}" /&gt; &lt;/bean&gt; &lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt; &lt;property name="entityManagerFactory" ref="emf" /&gt; &lt;/bean&gt; &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; &lt;bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="jpaVendorAdapter"&gt; &lt;bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" /&gt; &lt;/property&gt; &lt;property name="packagesToScan" value="com.emisoft.ami.user.domain" /&gt; &lt;property name="jpaProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.PostgreSQLDialect&lt;/prop&gt; &lt;prop key="hibernate.max_fetch_depth"&gt;3&lt;/prop&gt; &lt;prop key="hibernate.jdbc.fetch_size"&gt;50&lt;/prop&gt; &lt;prop key="hibernate.jdbc.batch_size"&gt;10&lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;false&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;jpa:repositories base-package="com.emisoft.ami.user.repository" entity-manager-factory-ref="emf" transaction-manager-ref="transactionManager" /&gt; ... </code></pre> <p>I don't know why 'firstJDBCTemplateQuery' close db connection. How to resolve this problem?</p> <p><strong>StackTrace:</strong></p> <pre><code> org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is java.sql.SQLException: Connection is closed. at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:296) at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:320) at org.springframework.jdbc.support.SQLErrorCodesFactory.getErrorCodes(SQLErrorCodesFactory.java:214) at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.setDataSource(SQLErrorCodeSQLExceptionTranslator.java:140) at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.&lt;init&gt;(SQLErrorCodeSQLExceptionTranslator.java:103) at org.springframework.jdbc.support.JdbcAccessor.getExceptionTranslator(JdbcAccessor.java:99) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:639) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:668) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:676) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:731) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:747) at org.springframework.jdbc.core.JdbcTemplate.queryForInt(JdbcTemplate.java:782) at org.springframework.security.provisioning.JdbcUserDetailsManager.findGroupId(JdbcUserDetailsManager.java:373) at org.springframework.security.provisioning.JdbcUserDetailsManager.addUserToGroup(JdbcUserDetailsManager.java:301) //////////////////////////////////////////////////This is secondJDBCTemplateQuery/////////// at com.emisoft.ami.user.service.impl.UserServiceImpl.insert(UserServiceImpl.java:42) /////////////////////////////////////////////////////////////////////////////////////////// at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at com.sun.proxy.$Proxy46.insert(Unknown Source) at com.kulig.test.service.PaymentServiceContext.main(PaymentServiceContext.java:28) Caused by: java.sql.SQLException: Connection is closed. at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.checkOpen(PoolingDataSource.java:185) at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.getMetaData(PoolingDataSource.java:244) at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:285) ... 29 more DEBUG: org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator - Unable to translate SQLException with Error code '0', will now try the fallback translator DEBUG: org.springframework.orm.jpa.JpaTransactionManager - Initiating transaction rollback DEBUG: org.springframework.orm.jpa.JpaTransactionManager - Rolling back JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@76c741] DEBUG: org.hibernate.engine.transaction.spi.AbstractTransactionImpl - rolling back DEBUG: org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction - re-enabling autocommit DEBUG: org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction - Could not toggle autocommit java.sql.SQLException: Connection is closed. at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.checkOpen(PoolingDataSource.java:185) at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.setAutoCommit(PoolingDataSource.java:327) at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.releaseManagedConnection(JdbcTransaction.java:127) at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doRollback(JdbcTransaction.java:170) at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.rollback(AbstractTransactionImpl.java:209) at org.hibernate.ejb.TransactionImpl.rollback(TransactionImpl.java:106) at org.springframework.orm.jpa.JpaTransactionManager.doRollback(JpaTransactionManager.java:539) at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:846) at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:823) at org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionAspectSupport.java:493) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:264) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at com.sun.proxy.$Proxy46.insert(Unknown Source) at com.kulig.test.service.PaymentServiceContext.main(PaymentServiceContext.java:28) DEBUG: org.springframework.orm.jpa.JpaTransactionManager - Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@76c741] after transaction DEBUG: org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Releasing JDBC connection DEBUG: org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Released JDBC connection ERROR: org.springframework.transaction.interceptor.TransactionInterceptor - Application exception overridden by rollback exception org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [select id from groups where group_name = ?]; SQL state [null]; error code [0]; Connection is closed.; nested exception is java.sql.SQLException: Connection is closed. at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:639) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:668) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:676) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:731) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:747) at org.springframework.jdbc.core.JdbcTemplate.queryForInt(JdbcTemplate.java:782) at org.springframework.security.provisioning.JdbcUserDetailsManager.findGroupId(JdbcUserDetailsManager.java:373) at org.springframework.security.provisioning.JdbcUserDetailsManager.addUserToGroup(JdbcUserDetailsManager.java:301) at com.emisoft.ami.user.service.impl.UserServiceImpl.insert(UserServiceImpl.java:42) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at com.sun.proxy.$Proxy46.insert(Unknown Source) at com.kulig.test.service.PaymentServiceContext.main(PaymentServiceContext.java:28) Caused by: java.sql.SQLException: Connection is closed. at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.checkOpen(PoolingDataSource.java:185) at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.prepareStatement(PoolingDataSource.java:312) at org.springframework.jdbc.core.JdbcTemplate$SimplePreparedStatementCreator.createPreparedStatement(JdbcTemplate.java:1446) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:583) ... 23 more Exception in thread "main" org.springframework.transaction.TransactionSystemException: Could not roll back JPA transaction; nested exception is javax.persistence.PersistenceException: unexpected error when rollbacking at org.springframework.orm.jpa.JpaTransactionManager.doRollback(JpaTransactionManager.java:543) at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:846) at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:823) at org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionAspectSupport.java:493) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:264) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at com.sun.proxy.$Proxy46.insert(Unknown Source) at com.kulig.test.service.PaymentServiceContext.main(PaymentServiceContext.java:28) Caused by: javax.persistence.PersistenceException: unexpected error when rollbacking at org.hibernate.ejb.TransactionImpl.rollback(TransactionImpl.java:109) at org.springframework.orm.jpa.JpaTransactionManager.doRollback(JpaTransactionManager.java:539) ... 9 more Caused by: org.hibernate.TransactionException: rollback failed at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.rollback(AbstractTransactionImpl.java:215) at org.hibernate.ejb.TransactionImpl.rollback(TransactionImpl.java:106) ... 10 more Caused by: org.hibernate.TransactionException: unable to rollback against JDBC connection at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doRollback(JdbcTransaction.java:167) at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.rollback(AbstractTransactionImpl.java:209) ... 11 more Caused by: java.sql.SQLException: Connection is closed. at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.checkOpen(PoolingDataSource.java:185) at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.rollback(PoolingDataSource.java:322) at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doRollback(JdbcTransaction.java:163) ... 12 more </code></pre> <p><strong>EDIT</strong> I checked <code>secondJDBCTemplateQuery</code> in stacktrace.</p> <p><strong>EDIT</strong></p> <p>I use <code>org.springframework.security.provisioning.JdbcUserDetailsManager</code></p> <p><code>firstJDBCTemplateQuery</code> is <code>createUser(UserDetails user)</code> </p> <p><code>secondJDBCTemplateQuery</code> is <code>addUserToGroup(String username, String groupName)</code> </p> <pre><code>public void createUser(final UserDetails user) { validateUserDetails(user); getJdbcTemplate().update(createUserSql, new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, user.getUsername()); ps.setString(2, user.getPassword()); ps.setBoolean(3, user.isEnabled()); } }); if (getEnableAuthorities()) { insertUserAuthorities(user); } } public void addUserToGroup(final String username, final String groupName) { logger.debug("Adding user '" + username + "' to group '" + groupName + "'"); Assert.hasText(username); Assert.hasText(groupName); final int id = findGroupId(groupName); getJdbcTemplate().update(insertGroupMemberSql, new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException { ps.setInt(1, id); ps.setString(2, username); } }); userCache.removeUserFromCache(username); } </code></pre> <p><strong>EDIT DEBUG RESULT</strong>:</p> <p>Beigin transaction on startup <code>myMethod()</code>:</p> <pre><code>DEBUG: org.springframework.orm.jpa.JpaTransactionManager - Creating new transaction with name [com.emisoft.ami.user.service.impl.UserServiceImpl.insert]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; '' DEBUG: org.springframework.orm.jpa.JpaTransactionManager - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@b18ac9] for JPA transaction DEBUG: org.hibernate.engine.transaction.spi.AbstractTransactionImpl - begin DEBUG: org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Obtaining JDBC connection DEBUG: org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Obtained JDBC connection DEBUG: org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction - initial autocommit status: true DEBUG: org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction - disabling autocommit DEBUG: org.springframework.orm.jpa.JpaTransactionManager - Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@940dc4] </code></pre> <p>////////////////////////////////// <code>firstJDBCTemplateMethod</code>: //////////////////////////////////</p> <pre><code>DEBUG: org.springframework.jdbc.core.JdbcTemplate - Executing prepared SQL update DEBUG: org.springframework.jdbc.core.JdbcTemplate - Executing prepared SQL statement [insert into users (username, password, enabled) values (?,?,?)] DEBUG: org.springframework.jdbc.core.JdbcTemplate - SQL update affected 1 rows </code></pre> <p>///////////////////////////////////////// <code>secondJDBCTemplateMethod</code>: ////////////////////////////////////</p> <pre><code>DEBUG: org.springframework.jdbc.core.JdbcTemplate - Executing prepared SQL query DEBUG: org.springframework.jdbc.core.JdbcTemplate - Executing prepared SQL statement [select id from groups where group_name = ?] INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml] INFO : org.springframework.jdbc.support.SQLErrorCodesFactory - SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase] DEBUG: org.springframework.jdbc.support.SQLErrorCodesFactory - Looking up default SQLErrorCodes for DataSource [org.apache.commons.dbcp.BasicDataSource@150f6f] WARN : org.springframework.jdbc.support.SQLErrorCodesFactory - Error while extracting database product name - falling back to empty error codes org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is java.sql.SQLException: Connection is closed. ///This is the beginning of stacktrace which is located above. </code></pre> <p><strong>EDIT</strong> <code>PaymentServiceContext</code> :</p> <pre><code>public class PaymentServiceContext { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "com/kulig/test/service/PaymentServiceTest-context.xml"); UserService userService = context.getBean(UserService.class); ///CREATE POJO OBJECTS credentials and p ... userService.insert(credentials, p); } } </code></pre>
0
7,450
Cannot insert explicit value for identity column when IDENTITY_INSERT is set to OFF. (Entity Framework Core)
<p>I'm getting this error when I attempt to add a new entity into the Database. The entity name is <code>DestuffedContainer</code>. The definition of this entity and related entities is below:</p> <p>DestuffedContainer:</p> <pre><code>[Table("DestuffedContainer")] public class DestuffedContainer { public long DestuffedContainerId { get; set; } public int Index { get; set; } public string Description { get; set; } public int? PackageQuantity { get; set; } public string PackageType { get; set; } public double? CBM { get; set; } public string Location { get; set; } public string MarksAndNumber { get; set; } public int? ManifestWeight { get; set; } public int? FoundWeight { get; set; } public int? ManifestQuantity { get; set; } public string ConsigneeName { get; set; } public string Remarks { get; set; } public string InvoiceFound { get; set; } public string PackageFound { get; set; } public long TellySheetId { get; set; } public TellySheet TellySheet { get; set; } public long ContainerIndexId { get; set; } public ContainerIndex ContainerIndex { get; set; } } </code></pre> <p>TellySheet:</p> <pre><code>[Table("TellySheet")] public class TellySheet { public TellySheet() { DestuffedContainers = new List&lt;DestuffedContainer&gt;(); } public long TellySheetId { get; set; } public string TellyClerk { get; set; } public DateTime? DestuffDate { get; set; } public string DayNight { get; set; } public long ShippingAgentId { get; set; } public ShippingAgent ShippingAgent { get; set; } public List&lt;DestuffedContainer&gt; DestuffedContainers { get; set; } } </code></pre> <p>ContainerIndex:</p> <pre><code>[Table("ContainerIndex")] public class ContainerIndex { public long ContainerIndexId { get; set; } public string BLNo { get; set; } public int? IndexNo { get; set; } public double? BLGrossWeight { get; set; } public string Description { get; set; } public string MarksAndNumber { get; set; } public string ShippingLine { get; set; } public bool? IsDestuffed { get; set; } public string AuctionLotNo { get; set; } public long? ContainerId { get; set; } public Container Container { get; set; } public DeliveryOrder DeliveryOrder { get; set; } public OrderDetail OrderDetail { get; set; } public DestuffedContainer DestuffedContainer { get; set; } public Auction Auction { get; set; } } </code></pre> <p>The error occurs in the below lines of code when I try to add the list of destuffed containers:</p> <pre><code> var dstfContainers = new List&lt;DestuffedContainer&gt;(); _tellySheetRepo.Add(tellySheet); foreach (var container in containers) { var destuff = new DestuffedContainer { TellySheetId = tellySheet.TellySheetId, ContainerIndexId = container.ContainerIndexId, Index = container.IndexNumber ?? 0, Description = container.Description, PackageQuantity = container.Package, PackageType = container.PackageType, CBM = container.CBM, ManifestWeight = container.ManifestWeight &gt; 0 ? Convert.ToInt32(container.ManifestWeight) : 0, FoundWeight = container.FoundWeight &gt; 0 ? Convert.ToInt32(container.FoundWeight) : 0, MarksAndNumber = container.MarksAndNumber, Location = container.Location, Remarks = container.Remarks, InvoiceFound = container.InvoiceFoud, PackageFound = container.PackageFoud }; dstfContainers.Add(destuff); var index = _cIndexRepo.Find(container.ContainerIndexId); if (index != null) { index.IsDestuffed = true; _cIndexRepo.Update(index); } } _destuffRepo.AddRange(dstfContainers); </code></pre> <p>I'm not sure what this error means as I'm not explicitly specifying the primary key value of the destuffedcontainer entity and by default it's 0. Entity Framework should pick this up as an insert but instead it throws an error.</p> <p>It was working fine few days ago but I'm not sure what has changed since causing this error. </p> <p>I'm using Entity Framework Core for modeling my entities. I've tried several solutions but none of them seem to work. I'd appreciate any help to resolve this issue.</p> <p><strong>EDIT</strong></p> <p>It seems that when I assign the ContainerIndexId value which is the foreign key in DestuffedContainer table to the entity, I get this error. I'm not sure how it's relevant.</p>
0
1,674
Android Resources - which resolutions should go into the hdpi, ldpi, mdpi and xhdpi directories
<p>I'm trying to write an application that will work well on all screen sizes, for that I have my graphic designer produce images that are in the requested dpis for each directory (Low density (120), ldpi, Medium density (160), mdpi, High density (240), hdpi, Extra high density (320), xhdpi) however, they want to know at which resolution and aspect ratio each image should be, after looking around the android documenation, namely: 1)http://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources 2)http://developer.android.com/guide/practices/screens_support.html I came up with the following information: It is not exact that android supports 3 screen sizes, android is an OS that can run virtually on any screen size but there are some screen sizes that are more common than others, these are demonstrated in the table below (taken from <a href="http://developer.android.com/guide/practices/screens_support.html" rel="nofollow">http://developer.android.com/guide/practices/screens_support.html</a>)</p> <p>Table 1. Screen sizes and densities of emulator skins included in the Android SDK. Low density (120), ldpi Medium density (160), mdpi High density (240), hdpi Extra high density (320), xhdpi Small screen QVGA (240x320)<br> Normal screen WQVGA400 (240x400) WQVGA432 (240x432) HVGA (320x480) WVGA800 (480x800) WVGA854 (480x854)<br> Large screen WVGA800* (480x800) WVGA854* (480x854)<br> Extra Large screen </p> <p>It’s worth noting here that even though it seems that there is no correlation between these screen sizes, there is a 3:4:6 scaling ratio between the three densities, so a 9x9 bitmap in ldpi is 12x12 in mdpi and 18x18 in hdpi (see <a href="http://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources" rel="nofollow">http://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources</a>).</p> <p>We can see some more information on what the screen sizes mean here:</p> <p>Screen size • small: Screens based on the space available on a low-density QVGA screen. Considering a portrait HVGA display, this has the same available width but less height—it is 3:4 vs. HVGA's 2:3 aspect ratio. Examples are QVGA low density and VGA high density. • normal: Screens based on the traditional medium-density HVGA screen. A screen is considered to be normal if it is at least this size (independent of density) and not larger. Examples of such screens a WQVGA low density, HVGA medium density, WVGA high density. • large: Screens based on the space available on a medium-density VGA screen. Such a screen has significantly more available space in both width and height than an HVGA display. Examples are VGA and WVGA medium density screens. • xlarge: Screens that are considerably larger than the traditional medium-density HVGA screen. In most cases, devices with extra large screens would be too large to carry in a pocket and would most likely be tablet-style devices. Added in API Level 9.</p> <p>We can also support specific aspect ratios, as defined here:</p> <p>Screen aspect • long: Long screens, such as WQVGA, WVGA, FWVGA • notlong: Not long screens, such as QVGA, HVGA, and VGA</p> <p>-- All of this however, is not enough to answer the simple question of what the resolution should be on those images - can they all be cut from the same high res image or should they be re-done for each dpi since the aspect ratio is different? please help, this is holding up my project Thanks!</p>
0
1,055
Setting up a TCP/IP Client and Server to communicate over a network
<p>I am trying to learn a little about socket programming and I have stumbled across TcpListener and TcpClient to use as I read they are slightly easier for beginners. The basic jist of what I want to accomplish is to have a small form that can be run on my laptop and another laptop on the same network and for them to be able to communicate i.e. send a string of text to each other. Once I have this I will hopefully develop it further :)</p> <p>So far I have created both a Client and a Server program using msdn and various guides found on the internet. I can get them to communicate when both running on one laptop however when I move the client to another laptop I get nowhere. I think my main issue is I do not understand quite how the client finds the Servers IP as I think I could hard code it but when I come back at another time I'm sure the IP will have changed. Is there any way to get the two to connect in a more dynamic way to encompass the changing IP? My current Client code:</p> <pre><code> public void msg(string mesg) { lstProgress.Items.Add("&gt;&gt; " + mesg); } private void btnConnect_Click(object sender, EventArgs e) { string message = "Test"; try { // Create a TcpClient. // Note, for this client to work you need to have a TcpServer // connected to the same address as specified by the server, port // combination. Int32 port = 1333; TcpClient client = new TcpClient(&lt;not sure&gt;, port); //Unsure of IP to use. // Translate the passed message into ASCII and store it as a Byte array. Byte[] data = System.Text.Encoding.ASCII.GetBytes(message); // Get a client stream for reading and writing. // Stream stream = client.GetStream(); NetworkStream stream = client.GetStream(); // Send the message to the connected TcpServer. stream.Write(data, 0, data.Length); lstProgress.Items.Add(String.Format("Sent: {0}", message)); // Receive the TcpServer.response. // Buffer to store the response bytes. data = new Byte[256]; // String to store the response ASCII representation. String responseData = String.Empty; // Read the first batch of the TcpServer response bytes. Int32 bytes = stream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); lstProgress.Items.Add(String.Format("Received: {0}", responseData)); // Close everything. stream.Close(); client.Close(); } catch (ArgumentNullException an) { lstProgress.Items.Add(String.Format("ArgumentNullException: {0}", an)); } catch (SocketException se) { lstProgress.Items.Add(String.Format("SocketException: {0}", se)); } } </code></pre> <p>My current Server code:</p> <pre><code> private void Prog_Load(object sender, EventArgs e) { bw.WorkerSupportsCancellation = true; bw.WorkerReportsProgress = true; bw.DoWork += new DoWorkEventHandler(bw_DoWork); bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged); if (bw.IsBusy != true) { bw.RunWorkerAsync(); } } private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e) { lstProgress.Items.Add(e.UserState); } private void bw_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; if ((worker.CancellationPending == true)) { e.Cancel = true; } else { try { // Set the TcpListener on port 1333. Int32 port = 1333; //IPAddress localAddr = IPAddress.Parse("127.0.0.1"); TcpListener server = new TcpListener(IPAddress.Any, port); // Start listening for client requests. server.Start(); // Buffer for reading data Byte[] bytes = new Byte[256]; String data = null; // Enter the listening loop. while (true) { bw.ReportProgress(0, "Waiting for a connection... "); // Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. TcpClient client = server.AcceptTcpClient(); bw.ReportProgress(0, "Connected!"); data = null; // Get a stream object for reading and writing NetworkStream stream = client.GetStream(); int i; // Loop to receive all the data sent by the client. while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) { // Translate data bytes to a ASCII string. data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); bw.ReportProgress(0, String.Format("Received: {0}", data)); // Process the data sent by the client. data = String.Format("I Have Received Your Message: {0}", data); byte[] mssg = System.Text.Encoding.ASCII.GetBytes(data); // Send back a response. stream.Write(mssg, 0, mssg.Length); bw.ReportProgress(0, String.Format("Sent: {0}", data)); } // Shutdown and end connection client.Close(); } } catch (SocketException se) { bw.ReportProgress(0, String.Format("SocketException: {0}", se)); } } } </code></pre> <p>As you can probably tell I am brand new to this so if there is a better way to implement this I am more than happy to learn! Thanks for any help in advance :)</p> <p>My solution thanks to the answers below:</p> <pre><code>private String IPAddressCheck() { var IPAddr = Dns.GetHostEntry("HostName"); IPAddress ipString = null; foreach (var IP in IPAddr.AddressList) { if(IPAddress.TryParse(IP.ToString(), out ipString) &amp;&amp; IP.AddressFamily == AddressFamily.InterNetwork) { break; } } return ipString.ToString(); } private void btnConnect_Click(object sender, EventArgs e) { string message = "Test"; try { Int32 port = 1337; string IPAddr = IPAddressCheck(); TcpClient client = new TcpClient(IPAddr, port); </code></pre> <p>I'm not sure if it is the neatest solution but it is working well so thank you for the answers :)</p>
0
3,168
java - The process cannot access the file because it is being used by another process
<p>I have a piece of code that monitors a directory for addition of files. Whenever a new file is added to the directory, the contents of the file are picked and published on kafka and then the file is deleted. </p> <p>This works when I make a single request but as soon as I subject my code to 5 or 10 user request from jMeter, the contents are published on kafka successfully but the code isn't able to delete the file. I get a <code>FileSystemException</code> with a message that <code>The process cannot access the file because it is being used by another process.</code>.</p> <p>I guess there is some concurrency issue which I am unable to see.</p> <pre><code>public void monitor() throws IOException, InterruptedException { Path faxFolder = Paths.get(TEMP_FILE_LOCATION); WatchService watchService = FileSystems.getDefault().newWatchService(); faxFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); boolean valid = true; do { WatchKey watchKey = watchService.take(); for (WatchEvent&lt;?&gt; event : watchKey.pollEvents()) { if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) { String fileName = event.context().toString(); publishToKafka(new File(TEMP_FILE_LOCATION + fileName).toPath(), "topic"); } } valid = watchKey.reset(); } while (valid); } private void publishToKafka(Path path, String topic) { try (BufferedReader reader = Files.newBufferedReader(path)) { String input = null; while ((input = reader.readLine()) != null) { kafkaProducer.publishMessageOnTopic(input, topic); } } catch (IOException e) { LOG.error("Could not read buffered file to send message on kafka.", e); } finally { try { Files.deleteIfExists(path); // This is where I get the exception } catch (IOException e) { LOG.error("Problem in deleting the buffered file {}.", path.getFileName(), e); } } } </code></pre> <p>Exception Log : </p> <pre><code>java.nio.file.FileSystemException: D:\upload\notif-1479974962595.csv: The process cannot access the file because it is being used by another process. at sun.nio.fs.WindowsException.translateToIOException(Unknown Source) at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) at sun.nio.fs.WindowsFileSystemProvider.implDelete(Unknown Source) at sun.nio.fs.AbstractFileSystemProvider.deleteIfExists(Unknown Source) at java.nio.file.Files.deleteIfExists(Unknown Source) at com.panasonic.mdw.core.utils.MonitorDirectory$FileContentPublisher.publishToKafka(MonitorDirectory.java:193) at com.panasonic.mdw.core.utils.MonitorDirectory$FileContentPublisher.sendData(MonitorDirectory.java:125) at com.panasonic.mdw.core.utils.MonitorDirectory$FileContentPublisher.run(MonitorDirectory.java:113) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) </code></pre>
0
1,120
Save streaming data to a WAV file using NAudio
<p>I want to save the incoming stream data to a WAV file on my hard disk drive. How can I change the code below to be able to record the stream into a valid WAV file?</p> <p>From the demo <a href="http://naudio.codeplex.com/SourceControl/changeset/view/a2092ffde43a#NAudioDemo/Mp3StreamingDemo/MP3StreamingPanel.cs" rel="nofollow">here</a>:</p> <pre><code>private void StreamMP3(object state) { this.fullyDownloaded = false; string url = (string)state; webRequest = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse resp = null; try { resp = (HttpWebResponse)webRequest.GetResponse(); } catch(WebException e) { if (e.Status != WebExceptionStatus.RequestCanceled) { ShowError(e.Message); } return; } byte[] buffer = new byte[16384 * 4]; // Needs to be big enough to hold a decompressed frame IMp3FrameDecompressor decompressor = null; try { using (var responseStream = resp.GetResponseStream()) { var readFullyStream = new ReadFullyStream(responseStream); do { if (bufferedWaveProvider != null &amp;&amp; bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes &lt; bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4) { Debug.WriteLine("Buffer getting full, taking a break"); Thread.Sleep(500); } else { Mp3Frame frame = null; try { frame = Mp3Frame.LoadFromStream(readFullyStream); } catch (EndOfStreamException) { this.fullyDownloaded = true; // Reached the end of the MP3 file / stream break; } catch (WebException) { // Probably we have aborted download from the GUI thread break; } if (decompressor == null) { // I don't think these details matter too much - just help ACM select the right codec. // However, the buffered provider doesn't know what sample rate it is working at // until we have a frame. WaveFormat waveFormat = new Mp3WaveFormat( frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate); decompressor = new AcmMp3FrameDecompressor(waveFormat); this.bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat); this.bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20); // Allow us to get well ahead of ourselves //this.bufferedWaveProvider.BufferedDuration = 250; } int decompressed = decompressor.DecompressFrame(frame, buffer, 0); //Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed)); bufferedWaveProvider.AddSamples(buffer, 0, decompressed); } } while (playbackState != StreamingPlaybackState.Stopped); Debug.WriteLine("Exiting"); // I was doing this in a finally block, but for some reason // we are hanging on response stream .Dispose, so we never get there. decompressor.Dispose(); } } finally { if (decompressor != null) { decompressor.Dispose(); } } } </code></pre>
0
2,089
Signature trust establishment failed for SAML metadata entry
<p>In order to fetch metadata from a remote source, I defined an <code>ExtendedMetadataDelegate</code> bean as follows:</p> <pre><code>@Bean @Qualifier("replyMeta") public ExtendedMetadataDelegate replyMetadataProvider() throws MetadataProviderException { String metadataURL = "https://ststest.mydomain.it/FederationMetadata/2007-06/FederationMetadata.xml"; final Timer backgroundTaskTimer = new Timer(true); HTTPMetadataProvider provider = new HTTPMetadataProvider( backgroundTaskTimer, httpClient(), metadataURL); provider.setParserPool(parserPool()); ExtendedMetadataDelegate emd = new ExtendedMetadataDelegate( provider, new ExtendedMetadata()); return emd; } </code></pre> <p>To ensure the signature trust establishment, I added the related key both in JDK keystore and application keystore (the second step might not be enough); despite that, an error occurs by running the webapp.</p> <pre><code>[2014-08-18 14:36:47.200] boot - 6000 DEBUG [localhost-startStop-1] --- SignatureValidator: Attempting to validate signature using key from supplied credential [2014-08-18 14:36:47.200] boot - 6000 DEBUG [localhost-startStop-1] --- SignatureValidator: Creating XMLSignature object [2014-08-18 14:36:47.206] boot - 6000 DEBUG [localhost-startStop-1] --- SignatureValidator: Validating signature with signature algorithm URI: http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 [2014-08-18 14:36:47.207] boot - 6000 DEBUG [localhost-startStop-1] --- SignatureValidator: Validation credential key algorithm 'RSA', key instance class 'sun.security.rsa.RSAPublicKeyImpl' [2014-08-18 14:36:47.329] boot - 6000 DEBUG [localhost-startStop-1] --- SignatureValidator: Signature validated with key from supplied credential [2014-08-18 14:36:47.329] boot - 6000 DEBUG [localhost-startStop-1] --- BaseSignatureTrustEngine: Signature validation using candidate credential was successful [2014-08-18 14:36:47.330] boot - 6000 DEBUG [localhost-startStop-1] --- BaseSignatureTrustEngine: Successfully verified signature using KeyInfo-derived credential [2014-08-18 14:36:47.330] boot - 6000 DEBUG [localhost-startStop-1] --- BaseSignatureTrustEngine: Attempting to establish trust of KeyInfo-derived credential [2014-08-18 14:36:47.330] boot - 6000 DEBUG [localhost-startStop-1] --- BasicX509CredentialNameEvaluator: Supplied trusted names are null or empty, skipping name evaluation [2014-08-18 14:36:47.331] boot - 6000 DEBUG [localhost-startStop-1] --- MetadataCredentialResolver: Attempting PKIX path validation on untrusted credential: [subjectName='CN=ADFS Signing - ststest-replynet.reply.it'] [2014-08-18 14:36:47.346] boot - 6000 ERROR [localhost-startStop-1] --- MetadataCredentialResolver: PKIX path construction failed for untrusted credential: [subjectName='CN=ADFS Signing - ststest-replynet.reply.it']: unable to find valid certification path to requested target [2014-08-18 14:36:47.347] boot - 6000 DEBUG [localhost-startStop-1] --- PKIXSignatureTrustEngine: Signature trust could not be established via PKIX validation of signing credential [2014-08-18 14:36:47.347] boot - 6000 DEBUG [localhost-startStop-1] --- BaseSignatureTrustEngine: Failed to establish trust of KeyInfo-derived credential [2014-08-18 14:36:47.347] boot - 6000 DEBUG [localhost-startStop-1] --- BaseSignatureTrustEngine: Failed to verify signature and/or establish trust using any KeyInfo-derived credentials [2014-08-18 14:36:47.347] boot - 6000 DEBUG [localhost-startStop-1] --- PKIXSignatureTrustEngine: PKIX validation of signature failed, unable to resolve valid and trusted signing key [2014-08-18 14:36:47.347] boot - 6000 ERROR [localhost-startStop-1] --- SignatureValidationFilter: Signature trust establishment failed for metadata entry http://ststest-replynet.reply.it/adfs/services/trust [2014-08-18 14:36:47.349] boot - 6000 ERROR [localhost-startStop-1] --- AbstractReloadingMetadataProvider: Error filtering metadata from https://ststest-replynet.reply.it/FederationMetadata/2007-06/FederationMetadata.xml org.opensaml.saml2.metadata.provider.FilterException: Signature trust establishment failed for metadata entry </code></pre> <p>The error disappears by setting:</p> <pre><code>emd.setMetadataTrustCheck(false); </code></pre> <p>... but I'd like to check used metadata.</p> <p>Is there a way to resolve this error?</p> <hr> <h2>Update:</h2> <p>I tried to setup the <code>ExtendedMetadata</code> as follows but the error persists.</p> <pre><code>em.setAlias("defaultAlias"); em.setSigningKey("*.mydomain.it (Go Daddy Secure Certification Authority)"); </code></pre>
0
1,382
How to Style Template field in Grid View (aspx page and CSS attached)
<p>i am trying to style my second column "mentor name" as i used css it give style to whole Grid i also tried "control styl css class = (some other css file)" and "item styl horizontal align=right" and also change property align = right by using # in css file but template field do not allow "id" to implement css my .aspx page and css ar below,</p> <pre><code>.mGrid { width: 100%; background-color: #fff; margin: 0px 0 0px 0; border: 0px #525252; } .mGrid table { border:0px; } .mGrid td { padding: 2px; border-width: 0px ; background-color:#3A3F3E; color: #fff; text-align:left; } td#Mname { text-align:left; } .mGrid th { padding: 4px 2px; color: #fff; background-color:#3A3F3E; border-width: 0px ; font-size: 0.9em; text-align:center; } &lt;asp:GridView Width="300px" ID="GridView1" runat="server" AutoGenerateColumns="False" Font-Size="10pt" OnRowCreated="GridView1_RowCreated" CssClass="mGrid"&gt; &lt;Columns&gt; &lt;asp:BoundField DataField="mentor_id" HeaderText="Image" /&gt; &lt;asp:TemplateField HeaderText="Image"&gt; &lt;ItemTemplate&gt; &lt;asp:Image ID="Image2" runat="server" ImageUrl="~/images/small_image.png" /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="Mentor Name"&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label1" Text='&lt;%#Eval("mentor_FirstName")+ "&lt;/br&gt; " + "&lt;b&gt;Experience: &lt;/b&gt;"+Eval("mentor_experience") %&gt; ' runat="server"&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>hopes for your suggestions thanks in advance </p>
0
1,109
Angular 4 : how to pass an argument to a Service provided in a module file
<p>I'm calling to you for help on what method to use here : I have tested many things to solve my problem and I have at least 4 working solutions, but I don't know which one(s) would be the best and if some of them work only because of a side effect of something else I did and should not be used...</p> <p>I couldn't find anything in the documentation to point me to one of these solutions (or another one)</p> <p><strong>First, here's my situation</strong> : I'm building an app that connects to an API for data and builds different sections, each containing dataviz.</p> <p>I built the sections of the site to be modules, but they share a service named DataService (each of these modules will use the DataService to get and process the data).</p> <p>My DataService needs a config file with a number of options that are specific to each section and stored in it's own folder.</p> <p>So I need to provide DataService separately for each section, in the providers section of the module.ts file, and it seemed like good practice to avoid copying DataService to each module...</p> <p>So the architecture of the files would be :</p> <pre><code>--Dashboard module ----data.service.ts ----Section1 module ------Section1 config file ----Section2 module ------Section2 config file </code></pre> <p>I tried multiple things that all seem to work in the section module file :</p> <p><strong>Solution 1 : injection</strong></p> <p>(I couldn't get the injection to work without quotation marks, even if I didn't see this anywhere)</p> <p>Module file :</p> <pre><code>import { DataService } from '../services/data.service'; import viewConfig from './view.config.json'; @NgModule({ imports: [ ... ], declarations: [ ... ], providers: [ { provide: 'VIEW_CONFIG', useValue: viewConfig }, DataService, ]}) export class Section1Module { } </code></pre> <p>Section file : </p> <pre><code>@Injectable() export class DataService { constructor(@Inject('VIEW_CONFIG') private viewConfig : any) {} } </code></pre> <p><s><strong>Solution 2 : factory provider</strong></s></p> <p><strong><em>Not working after ng serve reboot (see update)</em></strong></p> <p><s> Inspired from <a href="https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#factory-provider" rel="noreferrer">https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#factory-provider</a></p> <p>Module file :</p> <pre><code>import { DataService } from '../services/data.service'; import viewConfig from './view.config.json'; export let VIEW_CONFIG = new InjectionToken&lt;any&gt;(''); let dataServiceFactory = (configObject):DataService =&gt; { return new DataService(configObject) } @NgModule({ imports: [ ... ], declarations: [ ... ], providers: [ { provide: VIEW_CONFIG, useValue: viewConfig }, { provide : DataService, useFactory : dataServiceFactory, deps : [VIEW_CONFIG] }, ]}) export class Section1Module { } </code></pre> <p>Section file : </p> <pre><code>@Injectable() export class DataService { constructor(private viewConfig : any) {} } </code></pre> <p></s> <s> <strong>Solution 3 : custom provider with direct instanciation</strong> </s></p> <p><strong><em>Not working after ng serve reboot (see update)</em></strong></p> <p><s> Module file :</p> <pre><code>import { DataService } from '../services/data.service'; import viewConfig from './view.config.json'; @NgModule({ imports: [ ... ], declarations: [ ... ], providers: [ { provide: DataService, useValue : new DataService(viewConfig) }, ]}) export class Section1Module { } </code></pre> <p>Section file : </p> <pre><code>@Injectable() export class DataService { constructor(private viewConfig : any) {} } </code></pre> <p></s> <s> <strong>Solution 4 : custom provider with factory</strong> </s></p> <p><strong><em>Not working after ng serve reboot (see update)</em></strong></p> <p><s> Very similar to Solution 3...</p> <p>Module file :</p> <pre><code>import { DataService } from '../services/data.service'; import viewConfig from './view.config.json'; let dataServiceFactory = (configObject) =&gt; { return new DataService(configObject) } @NgModule({ imports: [ ... ], declarations: [ ... ], providers: [ { provide: DataService, useValue : dataServiceFactory(viewConfig) } ]}) export class Section1Module { } </code></pre> <p>Section file : </p> <pre><code>@Injectable() export class DataService { constructor(private viewConfig : any) {} } </code></pre> <p></s></p> <p><strong>Solution 5</strong> Use of a factory exported from the service file AND and injection token</p> <p>Module file :</p> <pre><code>export const VIEW_CONFIG = new InjectionToken&lt;any&gt;(''); @NgModule({ imports: [ ... ], declarations: [ ... ], providers: [ { provide: VIEW_CONFIG, useValue: viewConfig }, { provide : DataService, useFactory: dataServiceFactory, deps : [VIEW_CONFIG] } ]}) export class Section1Module { } </code></pre> <p>Section file : </p> <pre><code>@Injectable() export class DataService { constructor(private viewConfig : any) {} } export function dataServiceFactory(configObject) { return new DataService(configObject); } </code></pre> <hr> <p>I'm open to any criticism, idea, new lead of any kind on "What would be the right solution ?" or even "Is the right solution among these ones ?"</p> <p>Thanks a lot ! :D</p> <hr> <p><strong>UPDATE</strong> At one point, I realised my Angular-CLI was behaving strangely, and that some of these methods weren't working if I killed my local server and did an "ng serve". What is even stranger is, it doesn't work juste after killing the CLI local server and rebooting it, but next time I save a file and the CLI recompiles, it works fine...</p> <p><strong>Solution 1</strong> : still working</p> <p><strong>Solution 2 / Solution 3</strong> : fails with error :</p> <pre><code>Error encountered resolving symbol values statically. Calling function 'DataService', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function </code></pre> <p><strong>Solution 4</strong> : fails with error:</p> <pre><code>Error encountered resolving symbol values statically. Reference to a non-exported function </code></pre> <p><strong>Added solution 5</strong></p>
0
2,149
How to create new PyQt4 windows from an existing window?
<p>I've been trying to call a new window from an existing one using python3 and Qt4.</p> <p>I've created two windows using Qt Designer (the main application and another one), and I've converted the .ui files generated by Qt Designer into .py scripts - but I can't seem to create new windows from the main application.</p> <p>I tried doing this:</p> <pre class="lang-py prettyprint-override"><code>############### MAIN APPLICATION SCRIPT ################ from PyQt4 import QtCore, QtGui import v2 try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(194, 101) self.button1 = QtGui.QPushButton(Form) self.button1.setGeometry(QtCore.QRect(50, 30, 99, 23)) self.button1.setObjectName(_fromUtf8("button1")) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8)) self.button1.setText(QtGui.QApplication.translate("Form", "Ventana", None, QtGui.QApplication.UnicodeUTF8)) self.button1.connect(self.button1, QtCore.SIGNAL(_fromUtf8("clicked()")), self.mbutton1) def mbutton1(self): v2.main() if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Form = QtGui.QWidget() ui = Ui_Form() ui.setupUi(Form) Form.show() sys.exit(app.exec_()) </code></pre> <pre class="lang-py prettyprint-override"><code>################## SECOND WINDOW ####################### from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(400, 300) self.label = QtGui.QLabel(Form) self.label.setGeometry(QtCore.QRect(160, 40, 57, 14)) self.label.setObjectName(_fromUtf8("label")) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("Form", "LABEL 2", None, QtGui.QApplication.UnicodeUTF8)) def main(): import sys app = QtGui.QApplication(sys.argv) Form = QtGui.QWidget() ui = Ui_Form() ui.setupUi(Form) Form.show() sys.exit(app.exec_()) </code></pre> <p>But I get this Error message:</p> <pre class="lang-none prettyprint-override"><code> QCoreApplication::exec: The event loop is already running QPixmap: Must construct a QApplication before a QPaintDevice </code></pre>
0
1,189
Flutter RenderFlex overflowed by 15 pixels on the right inside Column Widget
<p>I created a custom ListTile which should have two score centered in the middle and information on the left and right of this (<a href="https://i.stack.imgur.com/6daCP.png" rel="noreferrer">screenshot</a>).</p> <p>The information on the left can have arbitrary length and should use TextOverflow.ellipsis when it's too long. I cannot get this to work since the Text does not seem to know the width it is supposed to have and overflows. I have tried wrapping the Text widgets into SizedBox, Expanded, etc. This has not worked.</p> <pre><code> flutter: ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════ flutter: The following message was thrown during layout: flutter: A RenderFlex overflowed by 15 pixels on the right. flutter: flutter: The overflowing RenderFlex has an orientation of Axis.horizontal. flutter: The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and flutter: black striped pattern. This is usually caused by the contents being too big for the RenderFlex. flutter: Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the flutter: RenderFlex to fit within the available space instead of being sized to their natural size. flutter: This is considered an error condition because it indicates that there is content that cannot be flutter: seen. If the content is legitimately bigger than the available space, consider clipping it with a flutter: ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex, flutter: like a ListView. flutter: The specific RenderFlex in question is: flutter: RenderFlex#c64e4 relayoutBoundary=up11 OVERFLOWING flutter: creator: Row ← Expanded ← Row ← Column ← ConstrainedBox ← Container ← Listener ← _GestureSemantics flutter: ← RawGestureDetector ← GestureDetector ← InkWell ← ScopedModelDescendant&lt;BaseballModel&gt; ← ⋯ flutter: parentData: offset=Offset(0.0, 0.0); flex=1; fit=FlexFit.tight (can use size) flutter: constraints: BoxConstraints(w=143.0, 0.0&lt;=h&lt;=Infinity) flutter: size: Size(143.0, 70.0) flutter: direction: horizontal flutter: mainAxisAlignment: start flutter: mainAxisSize: max flutter: crossAxisAlignment: center flutter: textDirection: ltr flutter: verticalDirection: down flutter: ◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤ </code></pre> <p>My Code is the following:</p> <pre><code>@immutable class GameTile extends StatelessWidget { final Game game; Color highligtColor = Colors.red; GameTile({this.game}); @override Widget build(BuildContext context) { return InkWell( child: Container( height: 70.0, child: Column( children: &lt;Widget&gt;[ Row( children: &lt;Widget&gt;[ Expanded( child: Row( children: &lt;Widget&gt;[ Container( width: 8.0, height: 70.0, color: highligtColor, ), Padding( padding: EdgeInsets.only(left: 15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: &lt;Widget&gt;[ Text( game.awayTeam.name, overflow: TextOverflow.ellipsis, ), Text( game.homeTeam.name, overflow: TextOverflow.ellipsis, ), ], ), ), ], ), ), Padding( padding: const EdgeInsets.only(left: 8.0, right: 8.0), child: Column( children: [ Text( game.awayRuns, style: TextStyle(fontWeight: FontWeight.w900), ), Text( game.homeRuns, style: TextStyle(fontWeight: FontWeight.w900), ), ], ), ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.end, children: &lt;Widget&gt;[ Column( crossAxisAlignment: CrossAxisAlignment.end, children: &lt;Widget&gt;[ Text(game.getFormattedDate()), Text(game.getFormattedTime()), ]), Padding( padding: EdgeInsets.only(left: 8.0, right: 10.0), child: Container(), ) ], ), ) ], ) ], ), ), ); } } </code></pre>
0
2,924
nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76
<p>When i restart the nginx with, sudo service nginx restart,</p> <p>Iam facing with this error,</p> <p>Restarting nginx: nginx: [emerg] "location" directive is not allowed here in /etc/nginx/nginx.conf:76 nginx: configuration file /etc/nginx/nginx.conf test failed</p> <p>This is my nginx.conf file:</p> <pre><code>user www-data; worker_processes 4; pid /var/run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; ## # nginx-naxsi config ## # Uncomment it if you installed nginx-naxsi ## #include /etc/nginx/naxsi_core.rules; ## # nginx-passenger config ## # Uncomment it if you installed nginx-passenger ## #passenger_root /usr; #passenger_ruby /usr/bin/ruby; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; location / { /home/techcee/scrapbook/local/lib/python2.7/site-packages/django/__init__.pyc/ } } #mail { # # See sample authentication script at: # # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript # # # auth_http localhost/auth.php; # # pop3_capabilities "TOP" "USER"; # # imap_capabilities "IMAP4rev1" "UIDPLUS"; # # server { # listen localhost:110; # protocol pop3; # proxy on; # } # `enter code here` # server { # listen localhost:143; # protocol imap; # proxy on; # } #} </code></pre> <p>What is wrong in this ?</p>
0
1,042
Trying to connect to ASPX site using CURL?
<p>I am trying to log into this url:</p> <pre><code>http://www.kalahari.com/marketplace/default.aspx </code></pre> <p>The two fields that are being submitted are labelled:</p> <pre><code>ctl00$ctl00$ucMarketPlaceSupportNavigation$txtMPTopSignInEmail ctl00$ctl00$ucMarketPlaceSupportNavigation$txtMPTopSignInPasswordTextNormal </code></pre> <p>The code I've tried to use so far:</p> <pre><code>$username = 'XXXXXXX'; $password = 'XXXXXXX'; $loginUrl = 'http://www.kalahari.com/marketplace/default.aspx'; $cookie = 'cookies.txt'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $loginUrl ); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE ); curl_setopt($ch, CURLOPT_COOKIEJAR , $cookie); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); curl_setopt($ch, CURLOPT_HEADER, FALSE ); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $ret = curl_exec($ch); //access login page // Collecting all POST fields $postfields = array(); $postfields['ctl00$ctl00$ucMarketPlaceSupportNavigation$txtMPTopSignInEmail'] = $username; $postfields['ctl00$ctl00$ucMarketPlaceSupportNavigation$txtMPTopSignInPasswordTextNormal'] = $password; curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); $ret = curl_exec($ch);//Get result after login page. print $ret; </code></pre> <p>This however only takes me back to the original login page... not even with an error message.</p> <p>I then had a look at what is getting posted, and I saw:</p> <pre><code>Request URL:http://www.kalahari.com/marketplace/default.aspx Request Method:POST Status Code:302 Found Request Headersview source Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 Cache-Control:max-age=0 Connection:keep-alive Content-Length:2596 Content-Type:application/x-www-form-urlencoded Cookie:VISITORID=9840A7E31683480CB19A66FB8AA73BFC; ASP.NET_SessionId=foous3ftij3os2vvr1wbm3mm; __utma=160092839.590473234.1362995010.1362995010.1362995010.1; __utmc=160092839; __utmz=160092839.1362995010.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _SUPERFLY_nosample=1; shopperName=; signin=0; kalahariShopperId=922859656760417F99E83D5B1427115F; surfLang=ENG; prefLanguage=en-ZA; _chartbeat2=1yx62ww1m7xz1o84.1360134968807.1363000295875.00000000000001 Host:www.kalahari.com Origin:http://www.kalahari.com Referer:http://www.kalahari.com/marketplace/default.aspx User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.152 Safari/537.22 Form Dataview sourceview URL encoded __EVENTTARGET: __EVENTARGUMENT: __VIEWSTATE:/wEPDwULLTEzODYxODcwMTMPZBYCZg9kFgJmD2QWAgIBD2QWCAICD2QWBAIDDw8WAh4LTmF2aWdhdGVVcmwFNH4vcGlwZWxpbmUvc2lnbmluLmFzcHg/UmV0dXJuVVJMPS9zZWN1cmUvbWFya2V0cGxhY2VkZAIHDxYCHgdWaXNpYmxlaBYCAgEPDxYCHwFoZGQCBA9kFgICAQ9kFgICAQ8WAh8BaBYCAgEPZBYQAgEPDxYGHghDc3NDbGFzcwULYWN0aXZlX2xpbmseB0VuYWJsZWRnHgRfIVNCAgJkZAIDDw8WBh8CBQVsaW5rcx8DZx8EAgJkZAIFDw8WBh8CBQ1kaXNhYmxlX2xpbmtzHwNoHwQCAmRkAgcPDxYGHwIFDWRpc2FibGVfbGlua3MfA2gfBAICZGQCCQ8PFgYfAgUNZGlzYWJsZV9saW5rcx8DaB8EAgJkZAILDw8WBh8CBQ1kaXNhYmxlX2xpbmtzHwNoHwQCAmRkAg0PDxYGHwIFDWRpc2FibGVfbGlua3MfA2gfBAICZGQCDw8PFgYfAgUNZGlzYWJsZV9saW5rcx8DaB8EAgJkZAIFD2QWAgIBD2QWBgIJDxAPZBYCHgdvbkNsaWNrBYQBamF2YXNjcmlwdDpWYWxpZGF0ZUxvZ2luUmFkaW9CdG5ZZXMoY3RsMDBfY3RsMDBfY3BsaE1haW5fY3BsaENvbnRlbnRfcmRsUGFzc3dvcmRZZXMsY3RsMDBfY3RsMDBfY3BsaE1haW5fY3BsaENvbnRlbnRfcmRsUGFzc3dvcmRObyk7ZGRkAgsPEA9kFgIfBQWDAWphdmFzY3JpcHQ6VmFsaWRhdGVMb2dpblJhZGlvQnRuTm8oY3RsMDBfY3RsMDBfY3BsaE1haW5fY3BsaENvbnRlbnRfcmRsUGFzc3dvcmRZZXMsY3RsMDBfY3RsMDBfY3BsaE1haW5fY3BsaENvbnRlbnRfcmRsUGFzc3dvcmRObyk7ZGRkAhUPD2QWAh8FBdMBamF2YXNjcmlwdDpWYWxpZGF0ZUxvZ2luKCdjdGwwMF9jdGwwMF9jcGxoTWFpbl9jcGxoQ29udGVudF9sYmxSZXN1bHQnLGN0bDAwX2N0bDAwX2NwbGhNYWluX2NwbGhDb250ZW50X3R4dFBhc3N3b3JkLGN0bDAwX2N0bDAwX2NwbGhNYWluX2NwbGhDb250ZW50X3JkbFBhc3N3b3JkWWVzLGN0bDAwX2N0bDAwX2NwbGhNYWluX2NwbGhDb250ZW50X3JkbFBhc3N3b3JkTm8pO2QCBg9kFgICBQ8PFgIfAAUafi9waXBlbGluZS9vcmRlcl9saXN0LmFzcHhkZBgBBR5fX0NvbnRyb2xzUmVxdWlyZVBvc3RCYWNrS2V5X18WAwUvY3RsMDAkY3RsMDAkY3BsaE1haW4kY3BsaENvbnRlbnQkcmRsUGFzc3dvcmRZZXMFLmN0bDAwJGN0bDAwJGNwbGhNYWluJGNwbGhDb250ZW50JHJkbFBhc3N3b3JkTm8FLmN0bDAwJGN0bDAwJGNwbGhNYWluJGNwbGhDb250ZW50JHJkbFBhc3N3b3JkTm99/wuPOuNOonYg5XWvf3RGR1YVkw== __EVENTVALIDATION:/wEWDQLsuI7QDgKnpLoxApD7nfEPAvLAqqUGAp35/akJAqGiqqYPAsXC5NUHAsHJ5OMCAovxoc8LArq0mqAKApm+rVoC9dLe0Q8C5IvEsAlYqPIdcrZvBZcvYav7ATMf4Nhbfg== ctl00$ctl00$ucMarketPlaceSupportNavigation$txtMPTopSignInEmail:XXXXXXXXX ctl00$ctl00$ucMarketPlaceSupportNavigation$txtMPTopSignInPasswordTextNormal:Password ctl00$ctl00$ucMarketPlaceSupportNavigation$txtMPTopSignInPassword:XXXXXXXXXXX ctl00$ctl00$ucMarketPlaceSupportNavigation$btnSigninTop:Sign in ctl00$ctl00$cplhMain$cplhContent$txtEmail:Email address ctl00$ctl00$cplhMain$cplhContent$rdlPasswordYes:rdlPasswordYes ctl00$ctl00$cplhMain$cplhContent$txtPasswordTextNormal:Password ctl00$ctl00$cplhMain$cplhContent$txtPassword: ctl00$ctl00$cplhMain$cplhContent$hdnEmailDefault:Email address ctl00$ctl00$cplhMain$cplhContent$hdnPasswordDefault:Password Response Headersview source Cache-Control:private, no-cache="Set-Cookie" Content-Length:146 Content-Type:text/html; charset=utf-8 Date:Mon, 11 Mar 2013 11:11:57 GMT Etag: Location:/marketplace/default.aspx Server:Microsoft-IIS/6.0 Set-Cookie:.KALAHARINETAUTH=782A6F442823F8148FB113BA0BAF3A9A8DE253762A4ACFAA5E911E4721166F0EEC6A1891755133AADD28654CF0DAE3880CC2B84260F0B915C07897909CFB071495AF8EF05D1BD678DEE1933FCB08E5ECB1CF76462900681C7D4AE963C151E3079D95FBAD6466F0528787455A951D5EC0DA26F0E6CAA341E4C717D7F3BC01D182F488F47F; domain=.kalahari.com; path=/; HttpOnly Set-Cookie:surfLang=ENG; domain=.kalahari.com; expires=Sat, 11-Mar-2023 11:11:57 GMT; path=/ Set-Cookie:prefLanguage=en-ZA; domain=www.kalahari.com; path=/ Set-Cookie:signin=1; domain=kalahari.com; path=/ Set-Cookie:tempshopperid=922859656760417F99E83D5B1427115F; domain=kalahari.com; path=/ Set-Cookie:kalahariShopperId=54B14971F72D426BA02DEF3A3D99DC93; domain=kalahari.com; expires=Sun, 17-Jan-2038 22:00:00 GMT; path=/ Set-Cookie:shopperName=XXXX; domain=kalahari.com; path=/ Set-Cookie:kalahariShopperEmail=XXX@XXXX.XXX; domain=kalahari.com; path=/ X-AspNet-Version:2.0.50727 X-Powered-By:ASP.NET </code></pre> <p>It looks like I'm supposed to be submitting much more than just the username and password. What exactly must I post and how do I post something like a "viewstate" that isn't a fixed value?</p>
0
3,272
Firefox not refreshing select tag on page refresh
<p>I've run into a problem where I have a select tag that the user would use to select a brand of phone and the page using jquery would then just display those phones.</p> <p>Thanks to the help of the people on stack overflow this now works great on every browser but firefox. For some reason when I refresh the page the select tag shows the last selected option but the page shows all phones available as designed. Does anyone have any suggestions or advice on getting firefox to refresh the select tag? I can't show it on js.fiddle because it doesn't happen there.</p> <p>Here is the code:</p> <pre class="lang-html prettyprint-override"><code>&lt;select class=&quot;manufacturers&quot;&gt; &lt;option class=&quot;selected&quot; value=&quot;all&quot;&gt;All&lt;/option&gt; &lt;option value=&quot;motorola&quot;&gt;Motorola&lt;/option&gt; &lt;option value=&quot;htc&quot;&gt;HTC&lt;/option&gt; &lt;option value=&quot;lg&quot;&gt;LG&lt;/option&gt; &lt;option value=&quot;samsung&quot;&gt;Samsung&lt;/option&gt; &lt;option value=&quot;kyocera&quot;&gt;Kyocera&lt;/option&gt; &lt;/select&gt; &lt;div class=&quot;scroll-content&quot;&gt; &lt;ul class=&quot;manulist motorola&quot;&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Motorola Triumph&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class=&quot;manulist htc&quot;&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;HTC WILDFIRE S&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class=&quot;manulist lg&quot;&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;LG Optimus Slider&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;LG Optimus V&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;LG Rumor Touch&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;LG Rumor 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;LG 101&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class=&quot;manulist samsung&quot;&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Samsung Intercept&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Samsung Restore&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Samsung M575&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>The jquery:</p> <pre class="lang-js prettyprint-override"><code>$(document).ready(function() { $('.manufacturers').change(function() { var selected = $(this).find(':selected'); $('ul.manulist').hide(); if ($(this).val() == 'all') { $('.scroll-content ul').show(); } else { $('.' + selected.val()).show(); $('.optionvalue').html(selected.html()).attr( 'class', 'optionvalue ' + selected.val()); } }); }); </code></pre> <p>Thanks in advance for any advice or help.</p>
0
1,376
Implementing Vue draggable with cards?
<p>I am trying to implement <code>vuedraggable</code> with Vuetify Cards but for some reason the drag and drop doesn't work when the cards are in a single row but works when they are in a column. </p> <p>Check out this working <a href="https://codesandbox.io/s/youthful-shockley-g608z?file=/src/components/Parent.vue" rel="nofollow noreferrer">CodeSandbox</a>.</p> <p>In the <code>Parent.vue</code> file, if i remove the <code>&lt;v-layout&gt; &lt;/v-layout&gt;</code> wrapping the <code>&lt;HelloWorld /&gt;</code> component, the cards go into a column and the drag and drop starts working again. </p> <p>This is my HelloWorld component:-</p> <pre><code>&lt;template&gt; &lt;v-flex xs4&gt; &lt;v-card class="mx-4"&gt; &lt;v-img :src="src"&gt;&lt;/v-img&gt; &lt;v-card-title primary-title&gt; &lt;div&gt;{{title}}&lt;/div&gt; &lt;/v-card-title&gt; &lt;/v-card&gt; &lt;/v-flex&gt; &lt;/template&gt; &lt;script&gt; export default { name: "HelloWorld", props: { title: String, src: String, id: Number }, data() { return {}; } }; &lt;/script&gt; </code></pre> <p>This is my Parent component:-</p> <pre><code>&lt;template&gt; &lt;v-container&gt; &lt;v-layout class="mt-5 align-center justify-center row fill-height"&gt; &lt;h2&gt;Parent Component&lt;/h2&gt; &lt;/v-layout&gt; &lt;draggable v-model="draggableCards"&gt; &lt;v-layout&gt; &lt;template v-for="(tech,i) in getCardArray"&gt; &lt;HelloWorld :src="tech.src" :title="tech.title" :key="i"/&gt; &lt;/template&gt; &lt;/v-layout&gt; &lt;/draggable&gt; &lt;/v-container&gt; &lt;/template&gt; &lt;script&gt; import { mapGetters, mapMutations } from "vuex"; import HelloWorld from "./HelloWorld"; import draggable from "vuedraggable"; export default { components: { draggable, HelloWorld }, computed: { ...mapGetters({ getCardArray: "getCardArray" }), draggableCards: { get() { return this.$store.state.cardArray; }, set(val) { this.$store.commit("setCardArray", val); } } }, methods: { ...mapMutations({ setCardArray: "setCardArray" }) } }; &lt;/script&gt; </code></pre> <p>If someone can help me figure this out, i sure would appreciate it. Thank you.</p>
0
1,050
Umarshall JSON object with underscore and camelCase fields between Jackson and JAXB
<p>Using JAXB (2.2) and Jackson (1.9.13), I have trouble unmarshalling the following JSON object to my POJOs</p> <pre><code>{ "userId": "foo", "group_id": "bar" } </code></pre> <p>Note that the payload contains both a camelCase and an underscore field.</p> <p>The POJO generated by xjc for my XML schema is as follows:</p> <pre><code>public class User { @XmlElement(required = true) protected String userId; @XmlElement(name = "group_id", required = true) protected String groupId; public String getUserId() { return userId; } public void setUserId(String value) { this.userId = value; } public String getGroupId() { return groupId; } public void setGroupId(String value) { this.groupId = value; } } </code></pre> <p>Jackson fails with the following exception: </p> <pre><code>org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "group_id" </code></pre> <h2>What I tried so far and failed</h2> <h3>1. Use JAXB binding <code>underscoreBinding="asCharInWord"</code></h3> <p>Using the following JXB binding in my XML schema </p> <pre><code>&lt;jxb:globalBindings underscoreBinding="asCharInWord"/&gt; </code></pre> <p>generates the following POJO:</p> <pre><code>public class User { @XmlElement(required = true) protected String userId; @XmlElement(name = "group_id", required = true) protected String groupId; public String getUserId() { return userId; } public void setUserId(String value) { this.userId = value; } public String getGroup_Id() { return groupId; } public void setGroup_Id(String value) { this.groupId = value; } } </code></pre> <p>Note that JAXB now generated setters/getters with underscore for group IDs but the <code>group_id</code> field is still converted to CamelCase. Jackson's object mapper seems to ignore the property getters/setter names and still can't map <code>group_id</code> to <code>groupId</code>.</p> <h3>2. Jackson property naming strategy</h3> <p>Using Jackson's <a href="http://wiki.fasterxml.com/JacksonFeaturePropertyNamingStrategy" rel="nofollow noreferrer">PropertyNamingStrategy</a> <code>CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES</code> I can convert <code>group_id</code> to <code>groupId</code>, but now the object mapper fails on the <code>userId</code> JSON property.</p> <h3>3. Add a <code>JSONProperty</code> annotation to groupId</h3> <p>Adding a <code>JSONProperty</code> to the vanilla JAXB generated POJOs actually works </p> <pre><code>public class User { /* ... */ @XmlElement(name = "group_id", required = true) @JSONProperty("group_id") protected String groupId; /* ... */ } </code></pre> <p>However, my XML schema is huge and manual instrumentation of the generated classes is not feasible, since we generate our classes often.</p> <h2>What should I do?</h2> <p>I see the following two remaining options to handle this problem:</p> <ol> <li>Implement a JAXB plugin that adds a <code>JSONProperty</code> annotation to each <code>XMLElement</code> with underscore names (my preferred next approach)</li> <li>Use a custom name generator for XJC as outlined in <a href="https://stackoverflow.com/questions/6267478/how-to-disable-java-naming-conventions-in-xjc">this</a> Stackoverflow answer.</li> </ol> <p>Have I missed the obvious? thanks for your thoughts.</p>
0
1,189
Error installing CMake in a docker container. Could not find PROTOBUF
<p>Hi I am trying to build a docker image that runs openpose. It goes all well until I have to compile the source I am giving...</p> <p>I run the Dockerfile below and it throws the following error:</p> <pre><code>CMake Error at /usr/share/cmake-3.5/Modules/FindPackageHandleStandardArgs.cmake:148 (message): Could NOT find Protobuf (missing: PROTOBUF_LIBRARY PROTOBUF_INCLUDE_DIR) Call Stack (most recent call first): /usr/share/cmake-3.5/Modules/FindPackageHandleStandardArgs.cmake:388 (_FPHSA_FAILURE_MESSAGE) /usr/share/cmake-3.5/Modules/FindProtobuf.cmake:308 (FIND_PACKAGE_HANDLE_STANDARD_ARGS) CMakeLists.txt:388 (find_package) </code></pre> <p>I tried to do the following: <a href="https://stackoverflow.com/questions/46698260/could-not-find-protobuf-compiler">Could not find PROTOBUF Compiler</a> and install the protobuf via apt-get but it didn't work. This happens:</p> <pre><code>After this operation, 2321 kB of additional disk space will be used. Do you want to continue? [Y/n] Abort. The command '/bin/sh -c apt-get update &amp;&amp; apt-get install protobuf-compiler' returned a non-zero code: 1 </code></pre> <p>this is my Dockerfile:</p> <pre><code>FROM ubuntu:16.04 RUN apt-get update &amp;&amp; apt-get install -y libopencv-dev WORKDIR src RUN apt-get update &amp;&amp; \ apt-get upgrade -y &amp;&amp; \ apt-get install -y git RUN git clone https://github.com/CMU-Perceptual-Computing-Lab/openpose.git WORKDIR /src/openpose/3rdparty RUN rm -r caffe RUN rm -r pybind11 RUN git clone https://github.com/BVLC/caffe.git RUN git clone https://github.com/pybind/pybind11.git WORKDIR /src/openpose/build RUN apt-get update &amp;&amp; apt-get -y install cmake RUN cmake .. -DBUILD_CAFFE=OFF -DGPU_MODE=CPU_ONLY RUN make RUN make install RUN make -j`nproc` </code></pre> <p>this trouble happens on the RUN cmake .. line.</p> <p>The full log of the error is the following:</p> <pre><code>-- The C compiler identification is GNU 5.4.0 -- The CXX compiler identification is GNU 5.4.0 -- Check for working C compiler: /usr/bin/cc -- Check for working C compiler: /usr/bin/cc -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Detecting C compile features -- Detecting C compile features - done -- Check for working CXX compiler: /usr/bin/c++ -- Check for working CXX compiler: /usr/bin/c++ -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Detecting CXX compile features -- Detecting CXX compile features - done -- GCC detected, adding compile flags -- Building CPU Only. -- Building with MKL support. -- Looking for pthread.h -- Looking for pthread.h - found -- Looking for pthread_create -- Looking for pthread_create - not found -- Looking for pthread_create in pthreads -- Looking for pthread_create in pthreads - not found -- Looking for pthread_create in pthread -- Looking for pthread_create in pthread - found -- Found Threads: TRUE -- Could NOT find GFlags (missing: GFLAGS_INCLUDE_DIR GFLAGS_LIBRARY) -- Could NOT find Glog (missing: GLOG_INCLUDE_DIR GLOG_LIBRARY) CMake Error at /usr/share/cmake-3.5/Modules/FindPackageHandleStandardArgs.cmake:148 (message): Could NOT find Protobuf (missing: PROTOBUF_LIBRARY PROTOBUF_INCLUDE_DIR) Call Stack (most recent call first): /usr/share/cmake-3.5/Modules/FindPackageHandleStandardArgs.cmake:388 (_FPHSA_FAILURE_MESSAGE) /usr/share/cmake-3.5/Modules/FindProtobuf.cmake:308 (FIND_PACKAGE_HANDLE_STANDARD_ARGS) CMakeLists.txt:388 (find_package) -- Configuring incomplete, errors occurred! See also "/src/openpose/build/CMakeFiles/CMakeOutput.log". See also "/src/openpose/build/CMakeFiles/CMakeError.log". The command '/bin/sh -c cmake .. -DBUILD_CAFFE=OFF -DGPU_MODE=CPU_ONLY -DBLAS=open' returned a non-zero code: 1 </code></pre>
0
1,362
SupportMapFragment.getMap() on a null object reference
<p>After trying just about everything, I cannot seem to getmap without pulling a null object reference. I am trying to inflate a google mapfragment into a fragment, however each time I do so I always keep a getmap null object .</p> <p>Here is my code</p> <p>I'm desperate for any help at this point, I've tried just about everything.</p> <blockquote> <p>Error</p> </blockquote> <pre><code> java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()' on a null object reference at com.gnumbu.errolgreen.importedapplication.ViewMapFragment.onViewCreated(ViewMapFragment.java:122) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:971) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499) at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:488) at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141) at android.support.v4.view.ViewPager.populate(ViewPager.java:1073) at android.support.v4.view.ViewPager.populate(ViewPager.java:919) at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.FrameLayout.onMeasure(FrameLayout.java:430) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.FrameLayout.onMeasure(FrameLayout.java:430) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436) at android.widget.LinearLayout.measureVertical(LinearLayout.java:722) at android.widget.LinearLayout.onMeasure(LinearLayout.java:613) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.FrameLayout.onMeasure(FrameLayout.java:430) at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560) at android.view.View.measure(View.java:17430) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767) at android.view.Choreographer.doCallbacks(Choreographer.java:580) at android.view.Choreographer.doFrame(Choreographer.java:550) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) </code></pre> <blockquote> <p>Fragment java class</p> </blockquote> <pre><code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (container == null) { return null; } view = (RelativeLayout) inflater.inflate(R.layout.fragmentmenu_layout, container, false); // Passing harcoded values for latitude &amp; longitude. Please change as per your need. This is just used to drop a Marker on the Map latitude = 26.78; longitude = 72.56; ; // For setting up the MapFragment return view; } /***** Sets up the map if it is possible to do so *****/ public static void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) SectionsPagerAdapter.fragmentManager .findFragmentById(R.id.mapView)).getMap(); // Check if we were successful in obtaining the map. if (mMap != null) setUpMap(); } } /** * This is where we can add markers or lines, add listeners or move the * camera. * &lt;p&gt; * This should only be called once and when we are sure that {@link #mMap} * is not null. */ private static void setUpMap() { // For showing a move to my loction button mMap.setMyLocationEnabled(true); // For dropping a marker at a point on the Map mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Home").snippet("Home Address")); // For zooming automatically to the Dropped PIN Location mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 12.0f)); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { // TODO Auto-generated method stub if (mMap != null) setUpMap(); if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) MainActivity.fragmentManager .findFragmentById(R.id.mapView)).getMap(); // getMap is deprecated // Check if we were successful in obtaining the map. if (mMap != null) setUpMap(); getAllFeaturedItems(); captureMapScreen(); } } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); setUpMapIfNeeded(); } @Override public void onPause() { super.onPause(); } @Override public void onStop() { super.onStop(); } @Override public void onLowMemory() { super.onLowMemory(); } /**** The mapfragment's id must be removed from the FragmentManager **** or else if the same it is passed on the next time then **** app will crash ****/ @Override public void onDestroyView() { super.onDestroyView(); if (mMap != null) { MainActivity.fragmentManager.beginTransaction() .remove(MainActivity.fragmentManager.findFragmentById(R.id.mapView)).commit(); mMap = null; } } @Override public void onDestroy() { super.onDestroy(); } </code></pre> <blockquote> <p>fragmentmenu_layout.xml</p> </blockquote> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:translationZ="5dp" &gt; &lt;ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listViewMenu" android:layout_gravity="center_horizontal" android:dividerHeight="1sp" android:translationZ="5dp" android:divider="@color/background_default" android:background="@color/background_white" android:clickable="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/screenShotMapView" /&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/screenShotMapView" android:layout_alignParentTop="true" android:maxWidth="50dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:adjustViewBounds="true" android:translationZ="5dp" /&gt; &lt;fragment class="com.google.android.gms.maps.MapFragment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/mapView" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:adjustViewBounds="true" android:longClickable="false" android:visibility="visible" android:maxHeight="50dp" android:maxWidth="50dp" /&gt; &lt;/RelativeLayout&gt; </code></pre> <blockquote> <p>MainActivity.java</p> </blockquote> <pre><code>public static FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { // setTheme(R.style.ActionBarTheme); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialising the object of the FragmentManager. Here I'm passing getSupportFragmentManager(). You can pass getFragmentManager() if you are coding for Android 3.0 or above. // final ActionBar actionBar = getSupportActionBar(); buildGoogleApiClient(); // actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mImageBitmap = null; // Create the adapter that will return a fragment for each section/page mSectionsPagerAdapter = new SectionsPagerAdapter( this.getBaseContext(), getSupportFragmentManager()); fragmentManager = getSupportFragmentManager(); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { // actionBar.setSelectedNavigationItem(position); } }); // For each of the sections in the app, add a tab to the action bar. /* for (int i = 0; i &lt; mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. if (i == 0) { actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.ic_action_view_as_list) // .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this) ); } if (i == 1) { actionBar.addTab( actionBar.newTab() .setIcon(R.drawable.ic_action_web_site_dark) // .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this) ); } } */ mAlbumStorageDirFactory = new BaseAlbumDirFactory(); Intent intent = new Intent(this, SplashScreen.class); startActivity(intent); } </code></pre>
0
5,594
EXIF orientation tag value always 0 for image taken with portrait camera app android
<p>I have a camera app in portrait mode which takes pictures from both front and back end cameras.I am saving the image in my sd card and try to find the corresponding exif value which gives 0 always.But i am getting the the expected exif orientation value for the other images stored in the device(like downloaded pictures).</p> <p>How can i fix this ? Can anyone help me out ?</p> <p>Here is the code used to save the picture and the find the orientation</p> <pre><code>PictureCallback myPictureCallback_JPG = new PictureCallback() { @Override public void onPictureTaken(byte[] arg0, Camera arg1) { // TODO Auto-generated method stub try { File APP_FILE_PATH = new File(Environment.getExternalStorageDirectory() .getPath() + "/Myapp/"); if (!APP_FILE_PATH.exists()) { APP_FILE_PATH.mkdirs(); } File file = new File(APP_FILE_PATH, "image.jpg"); FileOutputStream fos = new FileOutputStream(file); fos.write(arg0); fos.close(); imageFileUri=Uri.fromfile(file); getApplicationContext().getContentResolver().notifyChange( imageFileUri, null); sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); ExifInterface exif = new ExifInterface(file.getAbsolutePath()); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); } catch (Exception e) { } } }; </code></pre> <p>Following is the code for surphace created and changed functions</p> <pre><code>@Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { List&lt;Size&gt; sizes = parameters.getSupportedPreviewSizes(); Size optimalSize = getOptimalPreviewSize(sizes, width, height); parameters.setPreviewSize(optimalSize.width, optimalSize.height); camera.setParameters(parameters); camera.startPreview(); startPreview(); } @Override public void surfaceCreated(SurfaceHolder holder) { try { if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.GINGERBREAD) { Camera.CameraInfo info=new Camera.CameraInfo(); for (int i=0; i &lt; Camera.getNumberOfCameras(); i++) { Camera.getCameraInfo(i, info); if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { camera=Camera.open(i); defaultCameraId = i; } } } if (camera == null) { camera=Camera.open(); } try { camera.setPreviewDisplay(surfaceHolder); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Camera.Parameters parameters = camera.getParameters(); android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo(); android.hardware.Camera.getCameraInfo(defaultCameraId, info); int rotation = this.getWindowManager().getDefaultDisplay() .getRotation(); if (Integer.parseInt(Build.VERSION.SDK) &gt;= 8) { int degrees = 0; switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; } int result; if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { result = (info.orientation + degrees) % 360; result = (360 - result) % 360; } else { // back-facing result = (info.orientation - degrees + 360) % 360; } camera.setDisplayOrientation(result); } else { parameters.set("orientation", "portrait"); } camera.setParameters(parameters); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private Size getOptimalPreviewSize(List&lt;Size&gt; sizes, int w, int h) { final double ASPECT_TOLERANCE = 0.1; double targetRatio = (double) w / h; if (sizes == null) return null; Size optimalSize = null; double minDiff = Double.MAX_VALUE; int targetHeight = h; for (Size size : sizes) { double ratio = (double) size.width / size.height; if (Math.abs(ratio - targetRatio) &gt; ASPECT_TOLERANCE) continue; if (Math.abs(size.height - targetHeight) &lt; minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } if (optimalSize == null) { minDiff = Double.MAX_VALUE; for (Size size : sizes) { if (Math.abs(size.height - targetHeight) &lt; minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } } return optimalSize; } </code></pre>
0
2,774
GoogleMaps does not load on page load
<p>I can't get my map running using the GoogleMaps API V3. The map does not load. I would expect the map to appear in the div with the id <code>gisMap</code> but in the Chrome Debugger I get the message: </p> <pre><code>Uncaught InvalidValueError: initMap is not a function </code></pre> <p><strong>Javascript</strong></p> <pre><code>var map; function initMap() { // Enabling new cartography and themes google.maps.visualRefresh = true; // Setting starting options var mapOptions = { center: new google.maps.LatLng(39.9078, 32.8252), zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }; // Getting Map DOM Element var mapElement = document.getElementById('gisMap'); // Creating a map with DOM element map = new google.maps.Map(mapElement, mapOptions); } </code></pre> <p><strong>Bundle.js (excerpt)</strong></p> <pre><code>(...) module.exports = Vue; }).call(this,require('_process')) },{"_process":1}],3:[function(require,module,exports){ 'use strict'; var map; function initMap() { // Enabling new cartography and themes google.maps.visualRefresh = true; // Setting starting options var mapOptions = { center: new google.maps.LatLng(39.9078, 32.8252), zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }; // Getting Map DOM Element var mapElement = document.getElementById('gisMap'); // Creating a map with DOM element map = new google.maps.Map(mapElement, mapOptions); } },{}],4:[function(require,module,exports){ 'use strict'; var Vue = require('vue'); new Vue({}); (...) </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;MFServer Test&lt;/title&gt; &lt;link rel="stylesheet" href="/css/app.css"&gt; &lt;/head&gt; &lt;nav class="navbar navbar-inverse navbar-fixed-top"&gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="#"&gt;MFDispo&lt;/a&gt; &lt;/div&gt; &lt;div id="navbar" class="collapse navbar-collapse"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li class="active"&gt;&lt;a href="#"&gt;Start&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#about"&gt;GIS&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--/.nav-collapse --&gt; &lt;/div&gt; &lt;/nav&gt; &lt;body id="app"&gt; &lt;div class="pageWrapper"&gt; &lt;div id="gisMap"&gt;&lt;/div&gt; &lt;div id="content"&gt;&lt;/div&gt; &lt;/div&gt; &lt;script src="/js/bundle.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha256-KXn5puMvxCw+dAYznun+drMdG1IFl3agK0p/pqT9KAo= sha512-2e8qq0ETcfWRI4HJBzQiA3UoyFk6tbNyG+qSaIBZLyW9Xf3sWZHN/lxe9fTh1U45DpPf07yj94KsUHHWe4Yk1A==" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBDucSpoWkWGH6n05GpjFLorktAzT1CuEc&amp;callback=initMap" async defer&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>SCSS</strong></p> <pre><code>@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap"; @import "partials/forms"; html, body { height: 100%; padding-top: 25px; } .pageWrapper { background-color: red; height:100%; width: 100%; } #gisMap { height: 100%; width: 50%; background-color: green; } </code></pre>
0
1,929
Hibernate Criteria Api Subqueries
<p>I am currently working on a project to transfer some legacy jdbc select statements over to using Hibernate and it's criteria api.</p> <p>The two relevant table columns and the SQL query looks like:</p> <pre><code>-QUERIES- primaryId -QUERYDETAILS- primaryId linkedQueryId -&gt; Foreign key references queries.primaryId value1 value2 select * from queries q where q.primaryId not in (SELECT qd.linkedQueryId FROM querydetails qd WHERE (qd.value1 LIKE 'PROMPT%' OR qd.value2 LIKE 'PROMPT%')); </code></pre> <p>My entity relationships look like:</p> <pre><code>@Table("queries") public class QueryEntity{ @Id @Column private Long primaryId; @OneToMany(targetEntity = QueryDetailEntity.class, mappedBy = "query", fetch = FetchType.EAGER) private Set&lt;QueryDetailEntities&gt; queryDetails; //..getters/setters.. } @Entity @Table(name = "queryDetails") public class QueryDetailEntity { @Id @Column private Long primaryId; @ManyToOne(targetEntity = QueryEntity.class) private QueryEntity query; @Column(name="value1") private String value1; @Column(name="value2") private String value2; //..getters/setters.. } </code></pre> <p>I am attempting to utilize the criteria api in this way:</p> <pre><code>Criteria crit = sessionFactory.getCurrentSession().createCriteria(QueryEntity.class); DetachedCriteria subQuery = DetachedCriteria.forClass(QueryDetailEntity.class); LogicalExpression hasPrompt = Restrictions.or(Restrictions.ilike("value1", "PROMPT%"), Restrictions.ilike("value2", "PROMPT%")); subQuery.add(hasPrompt); Criterion subQueryCrit = Subqueries.notIn("queryDetails", subQuery); crit.add(subQueryCrit); List&lt;QueryMainEntity&gt; entities = (List&lt;QueryMainEntity&gt;) crit.list(); System.out.println("# of results = " + entities.size()); </code></pre> <p>I am getting a NullPointerException on the crit.list() line that looks like</p> <pre><code>Exception in thread "main" java.lang.NullPointerException at org.hibernate.loader.criteria.CriteriaQueryTranslator.getProjectedTypes(CriteriaQueryTranslator.java:362) at org.hibernate.criterion.SubqueryExpression.createAndSetInnerQuery(SubqueryExpression.java:153) at org.hibernate.criterion.SubqueryExpression.toSqlString(SubqueryExpression.java:69) at org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:380) at org.hibernate.loader.criteria.CriteriaJoinWalker.&lt;init&gt;(CriteriaJoinWalker.java:114) at org.hibernate.loader.criteria.CriteriaJoinWalker.&lt;init&gt;(CriteriaJoinWalker.java:83) at org.hibernate.loader.criteria.CriteriaLoader.&lt;init&gt;(CriteriaLoader.java:92) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1687) at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347) </code></pre> <p>Now, I think its pretty safe to say I'm using the Criteria Api/Detached Query Api incorrectly, but I'm not sure what the 'correct' way to do it is since the <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html#querycriteria-detachedqueries" rel="nofollow">Hibernate Docs</a> only briefly cover criteria api subqueries.</p> <p>I realize this is a pretty long question, but I figure its appear to put it all the relevant aspects of the question (query I'm attempting to represent via Criteria API, tables, entities).</p>
0
1,264
cordova Android requirements failed: "Could not find an installed version of Gradle"
<p>I'm trying to build a Cordova Android project using the most recent tools. I followed the instructions <a href="https://cordova.apache.org/docs/en/latest/guide/cli/" rel="noreferrer">here</a>:</p> <pre><code>$ cordova create myApp com.myCompany.myApp myApp $ cd myApp $ cordova platform add android@6.2.1 --save $ cordova requirements android --verbose </code></pre> <p>But the result is:</p> <pre><code>Running command: android list targets Command finished with error code 0: android list,targets Requirements check results for android: Java JDK: installed 1.8.0 Android SDK: installed true Android target: installed android-25,android-23 Gradle: not installed Could not find an installed version of Gradle either in Android Studio, or on your system to install the gradle wrapper. Please include gradle in your path, or install Android Studio Error: CordovaError: Some of requirements check failed at /usr/local/nodejs_next/lib/node_modules/cordova/src/cli.js:401:45 at _fulfilled (/usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:787:54) at self.promiseDispatch.done (/usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:816:30) at Promise.promise.promiseDispatch (/usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:749:13) at /usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:557:44 at flush (/usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:108:17) at _combinedTickCallback (internal/process/next_tick.js:73:7) at process._tickCallback (internal/process/next_tick.js:104:9) </code></pre> <p>It doesn't seem to be able to find Gradle (not sure where that's supposed to be).</p> <p>I've seen <a href="https://issues.apache.org/jira/browse/CB-12524" rel="noreferrer">reports</a> of issues with Cordova and Android SDK Tools 25.3, but this seems to be different, and I have 25.2.3 (see below).</p> <p>I have the following (this is on CentOS 6.8):</p> <pre><code>$ cordova --version 6.5.0 $ node --version v6.10.2 $ npm --version 3.10.10 $ java -version openjdk version "1.8.0_121" $ echo $JAVA_HOME /usr/lib/jvm/java-1.8.0 $ echo $ANDROID_HOME /usr/local/android-sdk # I installed the Android SDK from here # https://developer.android.com/studio/index.html#downloads # under "Get just the command line tools" $ /usr/local/android-sdk/tools/bin/sdkmanager --list Installed packages: Path | Version | Description | Location ------- | ------- | ------- | ------- build-tools;23.0.3 | 23.0.3 | Android SDK Build-Tools 23.0.3 | build-tools/23.0.3/ build-tools;25.0.2 | 25.0.2 | Android SDK Build-Tools 25.0.2 | build-tools/25.0.2/ extras;android;m2repository | 47.0.0 | Android Support Repository | extras/android/m2repository/ extras;google;m2repository | 46 | Google Repository | extras/google/m2repository/ patcher;v4 | 1 | SDK Patch Applier v4 | patcher/v4/ platform-tools | 25.0.4 | Android SDK Platform-Tools | platform-tools/ platforms;android-23 | 3 | Android SDK Platform 23 | platforms/android-23/ platforms;android-25 | 3 | Android SDK Platform 25 | platforms/android-25/ tools | 25.2.3 | Android SDK Tools 25.2.3 | tools/ </code></pre> <p><strong>UPDATE:</strong></p> <p>It doesn't seem to be mentioned anywhere in Cordova's or Android's docs, but if you're using the Android command-line tools without Android Studio, you have to manually install Gradle. Once you do, and it's on your PATH, this error will go away.</p> <p>An additional thing that was confusing me: in older versions of Android SDK tools, there was a Gradle wrapper script in <code>tools/templates/gradle/wrapper/gradlew</code>. This can also be used to install Gradle, but I found it easier to just install it manually. This seems to have been removed as of the latest version.</p>
0
1,689
Checking if textarea is empty in jQuery
<p>Here's my code:</p> <pre><code>if ($('#inputName').val() &amp;&amp; $('#inputEmail').val() &amp;&amp; $('#inputInstrument').val() &amp;&amp; $('#inputFee').val() $('#message').val() != '') { alert('success'); } else { alert('fill in all fields'); } </code></pre> <p>If I take out the last condition (<code>#message</code>), it works fine, but with it in I get:</p> <blockquote> <p>Uncaught SyntaxError: Unexpected identifier</p> </blockquote> <p>Here's the HTML:</p> <pre><code>&lt;form class="form-horizontal" role="form" action="includes/data.php" method="POST" id="findmusicians"&gt; &lt;div class="form-group"&gt; &lt;label for="inputName" class="col-sm-3 control-label"&gt;* Name&lt;/label&gt; &lt;div class="col-md-7"&gt; &lt;input type="text" name="inputName" class="form-control required" minlength="1" id="inputName"&gt; &lt;div id="hidden"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputEmail" class="col-sm-3 control-label"&gt;* Email&lt;/label&gt; &lt;div class="col-md-7"&gt; &lt;input type="email" name="inputEmail" class="form-control" id="inputEmail"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputPhone" class="col-sm-3 control-label"&gt;Telephone&lt;/label&gt; &lt;div class="col-md-7"&gt; &lt;input type="text" name="inputTelephone" class="form-control" id="inputTelephone"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputInstrument" class="col-sm-3 control-label"&gt;* Instrument(s)&lt;/label&gt; &lt;div class="col-md-7"&gt; &lt;input type="text" name="inputInstrument" class="form-control" id="inputInstrument"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputFee" class="col-sm-3 control-label"&gt;* Fee&lt;/label&gt; &lt;div class="col-md-7"&gt; &lt;input type="text" name="inputFee" class="form-control" id="inputFee"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="message" class="col-sm-3 control-label"&gt;* Message&lt;/label&gt; &lt;div class="col-md-9"&gt; &lt;textarea name="message" id="message" class="form-control" rows="3" style="height: 200px"&gt;&lt;/textarea&gt; &lt;span class="help-block" style="text-align: left;"&gt;Please include as much information as possible including repertoire, rehearsal/performance times and venues.&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;div class="col-md-3 col-md-offset-3"&gt; &lt;button id="findmusicians-submit" type="submit" class="btn btn-success"&gt;Submit request&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-9 col-md-offset-3" style="text-align: left; padding-left: 5px"&gt; &lt;span id="result" class="text-success"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/form&gt; </code></pre>
0
1,388
Error in web.config
<p>I am getting following error when running an ASP.NET application:</p> <pre><code>Server Error in '/' Application. Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. Parser Error Message: Section or group name 'dataConfiguration' is already defined. Updates to this may only occur at the configuration level where it is defined. Source Error: Line 1: &lt;?xml version="1.0"?&gt;&lt;configuration&gt; Line 2: &lt;configSections&gt; Line 3: &lt;section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" requirePermission="false"/&gt; Line 4: &lt;sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"&gt; Line 5: &lt;sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"&gt; Source File: E:\kunden\homepages\24\d228211015\glitzgraphix\glitz\architect\web.config Line: 3 </code></pre> <p>following is my web.config</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" requirePermission="false"/&gt; &lt;sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"&gt; &lt;sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"&gt; &lt;section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/&gt; &lt;sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"&gt; &lt;section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/&gt; &lt;section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/&gt; &lt;section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/&gt; &lt;/sectionGroup&gt; &lt;/sectionGroup&gt; &lt;/sectionGroup&gt; &lt;/configSections&gt; &lt;connectionStrings&gt; &lt;!--&lt;add name="AllForKidsConnectionString" connectionString="Data Source=mssql07.1and1.com,1433;Initial Catalog=db221598441;User Id=dbo221598441;Password=AFKvhv@1107;" providerName="System.Data.SqlClient" /&gt;--&gt; &lt;add name="ArchitectConnectionString" connectionString="server=GRAPHIX\SQLEXPRESS;database=Architect;Integrated Security=true" providerName="System.Data.SqlClient"/&gt; &lt;/connectionStrings&gt; &lt;dataConfiguration defaultDatabase="ArchitectConnectionString"/&gt; &lt;system.web&gt; &lt;customErrors mode="Off"/&gt; &lt;pages enableViewStateMac="false"&gt; &lt;controls&gt; &lt;add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/&gt; &lt;/controls&gt; &lt;/pages&gt; &lt;!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --&gt; &lt;compilation debug="false"&gt; &lt;assemblies&gt; &lt;add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/&gt; &lt;add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/&gt; &lt;add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/&gt; &lt;add assembly="System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; &lt;/assemblies&gt; &lt;/compilation&gt; &lt;httpHandlers&gt; &lt;remove verb="*" path="*.asmx"/&gt; &lt;add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/&gt; &lt;add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/&gt; &lt;add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/&gt; &lt;add verb="GET" path="ThumbHandler.ashx" type="Bright.WebControls.ThumbHandler"/&gt; &lt;/httpHandlers&gt; &lt;httpModules&gt; &lt;add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/&gt; &lt;/httpModules&gt; &lt;authentication mode="Forms"&gt; &lt;forms loginUrl="Index.aspx"/&gt; &lt;/authentication&gt; &lt;roleManager enabled="true" defaultProvider="CustomizedRoleProvider"&gt; &lt;providers&gt; &lt;add connectionStringName="ArchitectConnectionString" name="CustomizedRoleProvider" type="System.Web.Security.SqlRoleProvider"/&gt; &lt;/providers&gt; &lt;/roleManager&gt; &lt;membership defaultProvider="CustomizedMembershipProvider"&gt; &lt;providers&gt; &lt;add name="CustomizedMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ArchitectConnectionString"/&gt; &lt;/providers&gt; &lt;/membership&gt; &lt;/system.web&gt; &lt;system.webServer&gt; &lt;validation validateIntegratedModeConfiguration="false"/&gt; &lt;modules&gt; &lt;add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/&gt; &lt;/modules&gt; &lt;handlers&gt; &lt;remove name="WebServiceHandlerFactory-Integrated"/&gt; &lt;add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/&gt; &lt;add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/&gt; &lt;add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>What alteration do I have to make in <code>web.config</code> to resolve this error?</p>
0
3,101
Jenkins slave JNLP4- connection timeout
<p>I see this error in some of the Jenkins jobs</p> <pre><code>Cannot contact jenkins-slave-l65p0-0f7m0: hudson.remoting.ChannelClosedException: Channel "unknown": Remote call on JNLP4-connect connection from 100.99.111.187/100.99.111.187:46776 failed. The channel is closing down or has closed down </code></pre> <p>I have a jenkins master - slave setup.</p> <p>On the slave following logs are found</p> <pre><code>java.nio.channels.ClosedChannelException at org.jenkinsci.remoting.protocol.NetworkLayer.onRecvClosed(NetworkLayer.java:154) at org.jenkinsci.remoting.protocol.impl.NIONetworkLayer.ready(NIONetworkLayer.java:142) at org.jenkinsci.remoting.protocol.IOHub$OnReady.run(IOHub.java:795) at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28) at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) </code></pre> <p>Jenkins is on a kubernetes cluster.</p> <pre><code>apiVersion: apps/v1beta1 kind: StatefulSet metadata: namespace: default name: jenkins-deployment spec: serviceName: "jenkins-pod" replicas: 1 template: metadata: labels: app: jenkins-pod spec: initContainers: - name: volume-mount-hack image: busybox command: ["sh", "-c", "chmod -R 777 /usr/mnt"] volumeMounts: - name: jenkinsdir mountPath: /usr/mnt containers: - name: jenkins-container imagePullPolicy: Always readinessProbe: exec: command: - curl - http://localhost:8080/login - -o - /dev/null livenessProbe: httpGet: path: /login port: 8080 initialDelaySeconds: 120 periodSeconds: 10 env: - name: JAVA_OPTS value: "-Dhudson.slaves.NodeProvisioner.initialDelay=0 -Dhudson.slaves.NodeProvisioner.MARGIN=50 -Dhudson.slaves.NodeProvisioner.MARGIN0=0.85" resources: requests: memory: "7100Mi" cpu: "2000m" ports: - name: http-port containerPort: 8080 - name: jnlp-port containerPort: 50000 volumeMounts: - mountPath: /var/run name: docker-sock - mountPath: /var/jenkins_home name: jenkinsdir volumes: - name: jenkinsdir persistentVolumeClaim: claimName: "jenkins-persistence" - name: docker-sock hostPath: path: /var/run --- apiVersion: v1 kind: Service metadata: namespace: default name: jenkins labels: app: jenkins spec: type: NodePort ports: - name: http port: 8080 targetPort: 8080 nodePort: 30099 protocol: TCP selector: app: jenkins-pod --- apiVersion: v1 kind: Service metadata: namespace: default name: jenkins-external annotations: service.beta.kubernetes.io/aws-load-balancer-internal: 0.0.0.0/0 labels: app: jenkins spec: type: LoadBalancer ports: - name: http port: 8080 targetPort: 8080 protocol: TCP selector: app: jenkins-pod --- apiVersion: policy/v1beta1 kind: PodDisruptionBudget metadata: name: jenkins-master-pdb namespace: default spec: maxUnavailable: 0 selector: matchLabels: app: jenkins-pod --- apiVersion: policy/v1beta1 kind: PodDisruptionBudget metadata: name: jenkins-slave-pdb namespace: default spec: maxUnavailable: 0 selector: matchLabels: jenkins: slave --- kind: Service apiVersion: v1 metadata: name: jenkins-discovery namespace: default labels: app: jenkins spec: selector: app: jenkins-pod ports: - protocol: TCP port: 50000 targetPort: 50000 name: slaves </code></pre> <p>I doubt this has anything to do with kubernetes but still putting it out there. </p>
0
1,846
Consumer/Producer with pthreads having waiting times
<p>I am trying to implement a slightly modified version of Consumer/Producer program with a code i I picked on the internet. It is as follows with my own modifications:</p> <pre><code> /* * Solution to Producer Consumer Problem * Using Ptheads, a mutex and condition variables * From Tanenbaum, Modern Operating Systems, 3rd Ed. */ /* In this version the buffer is a single number. The producer is putting numbers into the shared buffer (in this case sequentially) And the consumer is taking them out. If the buffer contains zero, that indicates that the buffer is empty. Any other value is valid. */ #include &lt;stdio.h&gt; #include &lt;pthread.h&gt; #define MAX 3 /* # of item to produce */ pthread_mutex_t the_mutex; pthread_cond_t condc, condp; int consumeTimes[MAX] = { 1, 4, 3 }; int toConsume = 0; void* producer(void *ptr) { int i; for (i = 0; i &lt; MAX; i++) { pthread_mutex_lock(&amp;the_mutex); /* protect buffer */ /*while (buffer != 0) /* If there is something in the buffer then wait pthread_cond_wait(&amp;condp, &amp;the_mutex);*/ printf("Producer: Produced item %d \n", i); toConsume++; pthread_cond_signal(&amp;condc); /* wake up consumer */ pthread_mutex_unlock(&amp;the_mutex); /* release the buffer */ sleep(3); } pthread_exit(0); } void* consumer(void *ptr) { int i; for (i = 0; i &lt; MAX; i++) { pthread_mutex_lock(&amp;the_mutex); /* protect buffer */ while (toConsume &lt;= 0) /* If there is nothing in the buffer then wait */ pthread_cond_wait(&amp;condc, &amp;the_mutex); sleep(consumeTimes[i]); printf("Consumer: Consumed item %d\n", i); toConsume--; //pthread_cond_signal(&amp;condp); /* wake up consumer */ pthread_mutex_unlock(&amp;the_mutex); /* release the buffer */ } pthread_exit(0); } int main(int argc, char **argv) { pthread_t pro, con; // Initialize the mutex and condition variables /* What's the NULL for ??? */ pthread_mutex_init(&amp;the_mutex, NULL); pthread_cond_init(&amp;condc, NULL); /* Initialize consumer condition variable */ pthread_cond_init(&amp;condp, NULL); /* Initialize producer condition variable */ // Create the threads pthread_create(&amp;con, NULL, consumer, NULL); pthread_create(&amp;pro, NULL, producer, NULL); // Wait for the threads to finish // Otherwise main might run to the end // and kill the entire process when it exits. pthread_join(&amp;con, NULL); pthread_join(&amp;pro, NULL); // Cleanup -- would happen automatically at end of program pthread_mutex_destroy(&amp;the_mutex); /* Free up the_mutex */ pthread_cond_destroy(&amp;condc); /* Free up consumer condition variable */ pthread_cond_destroy(&amp;condp); /* Free up producer condition variable */ } </code></pre> <p>Here's what I want to do:</p> <p>Basically, each item has a consume and a production time.</p> <p>The consume times are indicated for each item in the <strong>consumeTimes array</strong>.</p> <p>So, for example <strong>consumeTimes[0] = 1</strong> which means that consuming the 1st item should take only a single time unit.</p> <p>For production, I use a constant time value, <strong>sleep(3)</strong>, so producing every item should take 3 time units.</p> <p>When I run the code, I get the following output all the time:</p> <pre><code>Producer: Produced item 0 Consumer: Consumed item 0 Producer: Produced item 1 Consumer: Consumed item 1 Producer: Produced item 2 Consumer: Consumed item 2 </code></pre> <p>However, considering the production and consume times it should be like this:</p> <pre><code>Producer: Produced item 0 (t=0) Consumer: Consumed item 0 (t=1) Producer: Produced item 1 (t=3) Producer: Produced item 2 (t=6) Consumer: Consumed item 1 (t=7) Consumer: Consumed item 2 (t=9) </code></pre> <p>In short, producer must always produce a new item in every 3 time intervals. But in this case, it seems to be waiting on the consumer to finish and I can't seem to figure out why.</p>
0
1,479
React: Losing ref values
<p>I am using two components and I am using this pattern: child component should stay isolated as much it can - it is handling its own validation error. Parent component should check for errors which have dependencies between children. So, in my case: <code>password</code> field and <code>password confirmation</code> field.</p> <p>Here is my code:</p> <p><strong>a) SignUp (parent)</strong></p> <p>Setting initial state.</p> <pre><code> constructor() { super(); this.state = { isPasswordMatching: false }; } </code></pre> <p>In <code>render()</code> method I am outputting my child component. Through prop called <code>callback</code> I am propagating method <code>isPasswordMatching()</code> by binding parent's <code>this</code>. The goal is that method can be called within child component.</p> <pre><code>&lt;TextInput id={'password'} ref={(ref) =&gt; this.password = ref} callback={this.isPasswordMatching.bind(this)} // some other unimportant props /&gt; &lt;TextInput id={'passwordConfirm'} ref={(ref) =&gt; this.passwordConfirm = ref} ... </code></pre> <p><code>isPasswordMatching()</code> method is checking if passwords match (through refs <code>this.password</code> and <code>this.passwordConfirm</code>) and then updates state. Please note that this method is called inside child (password or passwordConfirm).</p> <pre><code>isPasswordMatching() { this.setState({ isPasswordMatching: this.password.state.value === this.passwordConfirm.state.value }); } </code></pre> <p><strong>b) TextInput (child)</strong></p> <p>Setting initial state.</p> <pre><code>constructor() { super(); this.state = { value: '', isValid: false }; } </code></pre> <p>On blur validation is done and state is updated.</p> <pre><code>onBlur(event) { // doing validation and preparing error messages this.setState({ value: value, isValid: this.error === null }); } </code></pre> <p>Latest. Callback prop is called.</p> <pre><code>componentDidUpdate(prevProps) { if (prevProps.id === 'password' || prevProps.id === 'passwordConfirm') { prevProps.callback(); } } </code></pre> <p><strong>Issue</strong></p> <p>Somehow my refs are lost. Scenario:</p> <ol> <li>Parent component is renderder</li> <li>Child components are rendered</li> <li>I am entering one of input fields and get out (this invokes <code>onBlur()</code> method) - state gets updated, child component is rendered</li> <li><code>componentDidUpdate()</code> is invoked and <code>prevProp.callback()</code> as well</li> <li>When going to <code>isPasswordMatching()</code> method I am outputting <code>this.password</code> and <code>this.passwordConfirm</code> - they are objects with expected values of reference. Updating state of parent - component gets rendered.</li> <li>Then again all children are rendered, components get updated, callback is called but this time <code>this.password</code> and <code>this.passwordConfirm</code> are <code>null</code>.</li> </ol> <p>I have no idea why references are kinda lost. Should I be doing something differently? Thank you in advance.</p>
0
1,067
Ng-animate does not add the ng-enter and ng-leave classes
<p>This is my first project working with Angular and i have some troubles with ng-animate. I did a couple of tutorials and in the tutorials i got everything working fine. Now i'm using Angular for a project and i just can't get ng-animate to work properly. The classes such as "ng-enter" and "ng-leave" are not added to the different elements. </p> <p>I've compared all kinds of working scripts with mine but just can't find out what i am doing wrong. </p> <p>My header:</p> <pre><code>&lt;link rel="stylesheet" href="css/app.css"&gt; &lt;script src="js/libraries/jquery-2.1.1.min.js"&gt;&lt;/script&gt; &lt;script src="js/libraries/angular.js"&gt;&lt;/script&gt; &lt;script src="js/libraries/angular-animate.js"&gt;&lt;/script&gt; &lt;script src="js/libraries/angular-resource.js"&gt;&lt;/script&gt; &lt;script src="js/libraries/angular-route.js"&gt;&lt;/script&gt; &lt;script src="js/app.js"&gt;&lt;/script&gt; &lt;script src="js/controllers.js"&gt;&lt;/script&gt; &lt;script src="js/services.js"&gt;&lt;/script&gt; </code></pre> <p>My HTML:</p> <pre><code>&lt;div class="view-container"&gt; &lt;div ng-view class="{{pageclass}} view-frame"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>My app.js</p> <pre><code>'use strict'; /* App Module */ var engineShowcaseApp = angular.module('engineShowcaseApp', [ 'ngRoute', 'ngAnimate', 'engineShowcaseController', 'engineShowcaseServices' ]); engineShowcaseApp.config(['$routeProvider', function ($routeProvider) { $routeProvider. when('/', { templateUrl: 'partials/main.html', controller: 'MainCtrl' }). when('/chapters/:chapterID', { templateUrl: 'partials/chapter.html', controller: 'ChapterCtrl' }); } ]); </code></pre> <p>My controllers.js:</p> <pre><code>'use strict'; /* Controllers */ var engineShowcaseController = angular.module('engineShowcaseController', []); engineShowcaseController.controller('MainCtrl', function ($scope, Main) { $scope.pageclass = "page-home"; $scope.hotspots = Main.query(); }); engineShowcaseController.controller('ChapterCtrl', function ($scope, $routeParams, Main) { $scope.pageclass = "page-chapter"; $scope.chapter = Main.get({ chapterID: $routeParams.chapterID }); }); </code></pre> <p>The HTML of the first/main pagina:</p> <pre><code>&lt;div ng-repeat="hotspot in hotspots" class="hotspot hotspot-{{hotspot.id}}" data-nextup="chapter-{{hotspot.id}}" data-startframe="{{hotspot.startFrame}}" data-endframe="{{hotspot.endFrame}}"&gt; &lt;a href="#/chapters/{{hotspot.chapterID}}"&gt; {{hotspot.label}} &lt;/a&gt; &lt;/div&gt; </code></pre> <p>If i'm correct the div's with the class 'hotspot' should receive the 'ng-enter' and 'ng-leave' classes... but somehow they don't. </p> <p>Could anyone help me out with this? What am i doing wrong? Many thanks!!</p>
0
1,134
Problem deploying Axis2 in Tomcat
<p>I am trying to install Axis2 in a servlet container (Tomcat) by using <a href="http://axis.apache.org/axis2/java/core/docs/installationguide.html#servlet_container" rel="noreferrer">this</a> link. But after succesfully following all the steps and after starting tomcat I am not able to see the index file for Axis2. Instead I am getting following error.</p> <p>[ERROR] The service cannot be found for the endpoint reference (EPR) /axis2/services/ org.apache.axis2.AxisFault: The service cannot be found for the endpoint reference (EPR) /axis2/services/</p> <p>I think there is some problem in mappings thats been done in web.xml. Following is the web.xml snapshot.</p> <p></p> <pre><code>&lt;web-app&gt; &lt;display-name&gt;Apache-Axis2&lt;/display-name&gt; &lt;servlet&gt; &lt;servlet-name&gt;AxisServlet&lt;/servlet-name&gt; &lt;display-name&gt;Apache-Axis Servlet&lt;/display-name&gt; &lt;servlet-class&gt;org.apache.axis2.transport.http.AxisServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet&gt; &lt;servlet-name&gt;AxisAdminServlet&lt;/servlet-name&gt; &lt;display-name&gt;Apache-Axis AxisAdmin Servlet (Web Admin)&lt;/display-name&gt; &lt;servlet-class&gt; org.apache.axis2.webapp.AxisAdminServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;AxisServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/servlet/AxisServlet&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;AxisServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;*.jws&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;AxisServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/services/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;AxisAdminServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/axis2-admin/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;extension&gt;inc&lt;/extension&gt; &lt;mime-type&gt;text/plain&lt;/mime-type&gt; &lt;/mime-mapping&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;welcome-file&gt;/axis2-web/index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;error-page&gt; &lt;error-code&gt;404&lt;/error-code&gt; &lt;location&gt;/axis2-web/Error/error404.jsp&lt;/location&gt; &lt;/error-page&gt; &lt;error-page&gt; &lt;error-code&gt;500&lt;/error-code&gt; &lt;location&gt;/axis2-web/Error/error500.jsp&lt;/location&gt; &lt;/error-page&gt; &lt;/web-app&gt; </code></pre> <p>Also this is the directory structure when axis2.war is expanded in webapp directory of tomcat.</p> <p>webapps</p> <ul> <li>axis2 <ul> <li>axis2-web </li> <li>META-INF </li> <li>org </li> <li>WEB-INF <ul> <li>classes </li> <li>conf </li> <li>lib </li> <li>modules</li> <li>services </li> <li>web.xml (Not expanding each directory but just the main ones)</li> </ul></li> </ul></li> </ul> <p>Any tips / suggestions would be very helpful.</p>
0
1,559
Errors when I try to migrate in Django2
<p>I have a problem (at least I think). I am new in all this, so I apologize If I ask something stupid. I have some site, which is working normally. When I try to make migrations ( <code>python manage.py makemigrations</code>), everything passed ok, I got the message of how many models new I have, etc. But, when I run after that migrate, I got the following output:</p> <pre><code>Operations to perform: Apply all migrations: admin, auth, comments, contenttypes, news, sessions Running migrations: Applying comments.0003_auto_20180816_2158...Traceback (most recent call last): File "../venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File ".../venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File ".../venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File ".../venv/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File ".../venv/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File ".../venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File ".../venv/lib/python3.6/site- packages/django/core/management/commands/migrate.py", line 203, in handle fake_initial=fake_initial, File ".../venv/lib/python3.6/site- packages/django/db/backends/base/schema.py", line 531, in _alter_field fk_names = self._constraint_names(model, [old_field.column], foreign_key=True) File ".../venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 1027, in _constraint_names constraints = self.connection.introspection.get_constraints(cursor, model._meta.db_table) File ".../venv/lib/python3.6/site- packages/django/db/backends/postgresql/introspection.py", line 158, in get_constraints """, ["public", table_name]) File ".../venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File ".../venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File ".../venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File ".../venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/.../venv/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File ".../venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ </code></pre> <p>Anyway, if after that I try again to make migrations, got the message that I don't have migrations. So, Django did the job, But this error is here constantly when I try to migrate, I am really wondering why. I tried to google it, but I got nothing. </p>
0
1,443
WPF/MVVM Load an UserControl at Runtime
<p>i know that there a many articles about my problem but i cant find a solution. I am new in WPF - MVVM and i try to understand the MVVM-Logic. So i made a little project to understand that. For my later apps i want to load UserControls dynamicly to my Window.</p> <p>In my StartView i have a Binding to the StartViewModel. (The Binding is in the APP.xaml)</p> <pre><code>StartView app = new StartView(); StartViewModel context = new StartViewModel(); </code></pre> <p>The StartView</p> <pre><code>&lt;Window x:Class="test.Views.StartView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:views="clr-namespace:test.ViewModel" Title="Window1" Height="300" Width="516"&gt; &lt;Grid&gt; &lt;Menu IsMainMenu="True" Margin="0,0,404,239"&gt; &lt;MenuItem Header="_Einstellungen"&gt; &lt;MenuItem Header="Server" /&gt; &lt;/MenuItem&gt; &lt;/Menu&gt; &lt;ContentControl Content="{Binding LoadedControl}" Margin="0,28,0,128" /&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>the StartViewModel</p> <pre><code>namespace test.ViewModel { public class StartViewModel : ViewModelBase { #region Fields private UCStastistikViewModel _loadedControl; #endregion public StartViewModel() { LoadedControl = new UCStastistikViewModel(); } #region Properties / Commands public UCStastistikViewModel LoadedControl { get { return _loadedControl; } set { if (value == _loadedControl) return; _loadedControl = value; OnPropertyChanged("LoadedControl"); } } #endregion #region Methods #endregion } } </code></pre> <p>UCStatistikView</p> <pre><code>&lt;UserControl x:Class="test.Views.UCStatistik" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:vm="clr-namespace:test.ViewModel" mc:Ignorable="d" d:DesignHeight="188" d:DesignWidth="508"&gt; &lt;UserControl.DataContext&gt; &lt;vm:UCStastistikViewModel /&gt; &lt;/UserControl.DataContext&gt; &lt;Grid Background="red"&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>UCStatistikViewModel</p> <pre><code>namespace test.ViewModel { public class UCStastistikViewModel : ViewModelBase { #region Fields #endregion public UCStastistikViewModel() { } #region Properties / Commands #endregion #region Methods #endregion } } </code></pre> <p>Now i want to load my UCStatistikView in the ContentControl of my StartView. But in the Startview only the Path test.UCStatistikViewModel is shown instead of the whole UC Can anybody give me some Ideas where my problem is / where im am going wrong ?</p> <p>Bye j</p>
0
1,505
Jenkins pipeline : select nodejs version (+ python version)
<p>I'm facing an issue with a Jenkins pipeline in a Jenkinsfile. I have 4 different nodeJs versions on my Jenkins instance. I would like to choose which one I'm going to use in my pipeline, but official plugin examples (<a href="https://wiki.jenkins-ci.org/display/JENKINS/NodeJS+Plugin" rel="noreferrer">https://wiki.jenkins-ci.org/display/JENKINS/NodeJS+Plugin</a>) simply don't work.</p> <p>I tried this first approach, failing because $PATH is overwritten by the <code>tools</code> section.</p> <pre><code>pipeline { agent any tools { // I hoped it would work with this command... nodejs 'nodejs6' } stages { stage('Example') { steps { sh 'npm --version' // Failed saying : // Running shell script //nohup: failed to run command 'sh': No such file or directory } } } } </code></pre> <p>I tried this second approach, failing because the <code>tool</code> command seems to do nothing at all.</p> <pre><code>pipeline { agent any stages { stage('Example') { steps { // ... or this one tool name: 'nodejs6' sh 'node --version' sh 'npm --version' // Does not use this version of node, but the default one... 7.5.0 with npm 4.3.0 } } } } </code></pre> <p>Finally, I tried this one, which works for NodeJS but... does not seem to be "very smart", and does not allow me to handle properly my specific version of "Python" --Yes I also have 2 different versions of Python that I would like to handle the same way I do for node--</p> <pre><code>pipeline { agent any stages{ stage ('Which NodeJS'){ steps{ withEnv(["PATH+NODEJS=${tool 'nodejs6'}/bin","PATH+PYTHON27=${tool 'python27'}"]) { // Check node version sh 'which node' // Works properly sh 'node -v' // Expected 6.9.x version sh 'npm -v' // Expected 3.x version sh 'python27 -v' // Failed with // /nd-jenkinsfile_XXX@tmp/xx/script.sh: python27: not found } } } } } </code></pre> <p>I also have a 4th solution, not using <code>pipeline</code> syntax. It works for nodejs, but not for python (so far). And once again, it does not seems very elegant to manually define <code>env.PATH</code>...</p> <pre><code>node { // Setup tools... stage ('Setup NodeJs'){ def nodejsHome = tool 'nodejs6' env.NODE_HOME = "${nodejsHome}" env.PATH = "${nodejsHome}/bin:${env.PATH}" sh 'which node' sh 'node -v' sh 'npm -v' } stage ('Setup Python 2.7'){ def pythonBin = tool 'python27' // Jenkins docker image has Jenkins user's home in "/var/jenkins_home" sh "rm -Rf /var/jenkins_home/tools/python ; mkdir -p /var/jenkins_home/tools/python" // Link python to python 2.7 sh "ln -s ${pythonBin} /var/jenkins_home/tools/python/python" // Include link in path --don't use "~" in path, it won't be resolved env.PATH = "~/tools/python:${env.PATH}:~/tools/python" // Displays correctly Python 2.7 sh "python --version" } } </code></pre> <p>All in all, I'm just wondering which solution (certainly another one that I have not listed here) is the best? Which one do you advice and why?</p> <p>Cheers, Olivier</p>
0
1,546
How can I solve the connection problem during npm install behind a proxy?
<p>I followed the instruction: <a href="https://www.electronjs.org/docs/tutorial/first-app" rel="noreferrer">https://www.electronjs.org/docs/tutorial/first-app</a></p> <p>I typed <code>mkdir</code>, <code>cd</code> and <code>npm init</code>. They all worked well. One file named <code>package.json</code> appeared.</p> <p>Then I typed <code>npm install --save-dev electron</code>. Some error occured.</p> <pre><code>lala@ubu:~/projects/electron/my-app 17:20:34 $ npm install --save-dev electron &gt; core-js@3.6.4 postinstall /home/lala/projects/electron/my-app/node_modules/core-js &gt; node -e "try{require('./postinstall')}catch(e){}" Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library! The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: &gt; https://opencollective.com/core-js &gt; https://www.patreon.com/zloirock Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -) &gt; electron@8.0.0 postinstall /home/lala/projects/electron/my-app/node_modules/electron &gt; node install.js (node:5950) UnhandledPromiseRejectionWarning: RequestError: connect ETIMEDOUT 13.250.177.223:443 at ClientRequest.&lt;anonymous&gt; (/home/lala/projects/electron/my-app/node_modules/got/source/request-as-event-emitter.js:178:14) at Object.onceWrapper (events.js:313:26) at ClientRequest.emit (events.js:228:7) at ClientRequest.origin.emit (/home/lala/projects/electron/my-app/node_modules/@szmarczak/http-timer/source/index.js:37:11) at TLSSocket.socketErrorListener (_http_client.js:406:9) at TLSSocket.emit (events.js:223:5) at emitErrorNT (internal/streams/destroy.js:92:8) at emitErrorAndCloseNT (internal/streams/destroy.js:60:3) at processTicksAndRejections (internal/process/task_queues.js:81:21) (node:5950) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:5950) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN my-app@1.0.0 No description npm WARN my-app@1.0.0 No repository field. + electron@8.0.0 added 85 packages from 91 contributors and audited 102 packages in 87.419s 2 packages are looking for funding run `npm fund` for details found 0 vulnerabilities </code></pre> <p>After executing the above instructions, one folder <code>node_modules</code> and one file <code>package-lock.json</code> appeared.</p> <p>It seemed that I had successfully installed the dependencies. But why one connection error occured?</p> <p>I can not access <code>github.com(13.250.177.223)</code> directly, but my proxy works.</p> <p>I have configured proxy as following, but the connection error still exists.</p> <p>My ~/.bashrc</p> <pre><code>export HTTP_PROXY=http://127.0.0.1:8123/ export HTTPS_PROXY=http://127.0.0.1:8123/ export http_proxy=http://127.0.0.1:8123/ export https_proxy=http://127.0.0.1:8123/ </code></pre> <pre><code>$ cat ~/.npmrc proxy=http://127.0.0.1:8123/ http-proxy=http://127.0.0.1:8123/ https-proxy=http://127.0.0.1:8123/ noproxy=localhost,127.0.0.1,192.168.,10. strict-ssl=false </code></pre> <p>node v12.14.1 npm v6.13.7</p> <p>How can I reduce the error?</p> <p>Thanks for any help!</p>
0
1,302
Redis sentinel not connect to master: Error: READONLY You can't write against a read only slave?
<p>I have this <code>redis replication</code> with <code>sentinel</code> architect:</p> <p>5 servers: <code>.1</code>, <code>.2</code>, <code>.3</code>, <code>.4</code> and <code>.5</code></p> <ul> <li><code>.1</code>: nodejs app, redis master, redis sentinel</li> <li><code>.2</code>: nodejs app, redis slave</li> <li><code>.3</code>: nodejs app, redis slave</li> <li><code>.4</code>: redis sentinel</li> <li><code>.5</code>: redis sentinel</li> </ul> <p>Sentinel handle failover as expected. <code>redis-cli -h x.y.z.5 -p 26379 sentinel get-master-addr-by-name mymaster</code> is always return <code>.1</code> server.</p> <p>My code to connect to this replication (I use <a href="https://github.com/luin/ioredis" rel="noreferrer">ioredis</a>):</p> <pre><code>let sentinels = [ { host: process.env.REDIS_SENTINEL_1, port: process.env.REDIS_PORT }, { host: process.env.REDIS_SENTINEL_2, port: process.env.REDIS_PORT }, { host: process.env.REDIS_SENTINEL_3, port: process.env.REDIS_PORT } ] store = new Redis({ name: 'mymaster', sentinels: sentinels }) store.on('ready', () =&gt; { store.set('foo', new Date()) store.get('foo', function (err, result) { console.log('redis: get foo: ', result) }); }); </code></pre> <p>Then, <code>.1</code> nodejs app run ok, but in <code>.2</code> and <code>.3</code>, the error occurs with this log:</p> <pre><code> events.js:161 throw er; // Unhandled 'error' event ^ Error: READONLY You can't write against a read only slave. </code></pre> <p>P/s: my redis servers are binding in both server IP and <code>127.0.0.1</code>. Because, without <code>127.0.0.1</code>, I meet this error:</p> <pre><code>Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379 </code></pre> <p>So, I guess that, my app isn't connect to <code>redis server</code> via <code>sentinel</code>, but it connect directly with <code>localhost</code>.</p> <p>Any help are appriciate!</p> <p>Update: log when I turn on the <code>DEBUG=ioredis:*</code>:</p> <pre><code>2|MyApp | Wed, 15 Mar 2017 12:58:42 GMT ioredis:redis status[x.y.z.5:26379]: connecting -&gt; connect 2|MyApp | Wed, 15 Mar 2017 12:58:42 GMT ioredis:redis status[x.y.z.5:26379]: connect -&gt; ready 2|MyApp | Wed, 15 Mar 2017 12:58:42 GMT ioredis:connection send 1 commands in offline queue 2|MyApp | Wed, 15 Mar 2017 12:58:42 GMT ioredis:redis write command[0] -&gt; sentinel(get-master-addr-by-name,mymaster) 2|MyApp | events.js:161 2|MyApp | throw er; // Unhandled 'error' event 2|MyApp | ^ 2|MyApp | Error: READONLY You can't write against a read only slave. 2|MyApp | at JavascriptReplyParser._parseResult (/home/demo/demo_api/source/node_modules/redis/lib/parsers/javascript.js:43:16) 2|MyApp | at JavascriptReplyParser.try_parsing (/home/demo/demo_api/source/node_modules/redis/lib/parsers/javascript.js:114:21) 2|MyApp | at JavascriptReplyParser.run (/home/demo/demo_api/source/node_modules/redis/lib/parsers/javascript.js:126:22) 2|MyApp | at JavascriptReplyParser.execute (/home/demo/demo_api/source/node_modules/redis/lib/parsers/javascript.js:107:10) 2|MyApp | at Socket.&lt;anonymous&gt; (/home/demo/demo_api/source/node_modules/redis/index.js:131:27) 2|MyApp | at emitOne (events.js:96:13) 2|MyApp | at Socket.emit (events.js:189:7) 2|MyApp | at readableAddChunk (_stream_readable.js:176:18) 2|MyApp | at Socket.Readable.push (_stream_readable.js:134:10) 2|MyApp | at TCP.onread (net.js:551:20) 2|MyApp | [nodemon] app crashed - waiting for file changes before starting... 2|MyApp | sentinel production 2|MyApp | Wed, 15 Mar 2017 12:58:43 GMT ioredis:redis status[localhost:6379]: [empty] -&gt; connecting 2|MyApp | Wed, 15 Mar 2017 12:58:43 GMT ioredis:redis status[x.y.z.5:26379]: [empty] -&gt; connecting 2|MyApp | Wed, 15 Mar 2017 12:58:43 GMT ioredis:redis queue command[0] -&gt; sentinel(get-master-addr-by-name,mymaster) 2|MyApp | sentinel production 2|MyApp | Wed, 15 Mar 2017 12:58:43 GMT ioredis:redis status[localhost:6379]: [empty] -&gt; connecting 2|MyApp | Wed, 15 Mar 2017 12:58:43 GMT ioredis:redis status[x.y.z.5:26379]: [empty] -&gt; connecting 2|MyApp | Wed, 15 Mar 2017 12:58:43 GMT ioredis:redis queue command[0] -&gt; sentinel(get-master-addr-by-name,mymaster) </code></pre> <p>Update 2: one more thing, I run the app in my local machine with the <code>production</code> environment and everything work like charm!!!</p>
0
1,887
Xamarin.Forms: Creating a SearchBar and search on a ListView
<p>Good Day everyone. I'm currently doing an application that allows the User to CRUD record of an Customer and save it on a database. All the created records are displayed on a ListView.</p> <p>What I want to do is to create a SearchBar that allows me to search Customer Records that is inside my ListView. In a separate program, I've tried to create a searchbar but I was only able to search records from a pre-defined ListView.</p> <p>The searchbar I need to do should allow me to search on a ListView that comes from a database.</p> <p>Hope you can help me with this.</p> <p>Here are some of my codes. If you need to see more. Please let me know. Thanks a lot.</p> <p><strong>CustomerViewModel.cs</strong></p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using XamarinFormsDemo.Models; using XamarinFormsDemo.Services; namespace XamarinFormsDemo.ViewModels { public class CustomerVM : INotifyPropertyChanged { private List&lt;Customer&gt; _customerList; public List&lt;Customer&gt; CustomerList { get { return _customerList; } set { _customerList = value; OnPropertyChanged(); } } public CustomerVM() { InitializeDataAsync(); } private async Task InitializeDataAsync() { var customerServices = new CustomerServices(); CustomerList = await customerServices.GetCustomerAsync(); } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } } </code></pre> <p><strong>CustomerPage.xaml</strong></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="Client List"&gt; &lt;ContentPage.BindingContext&gt; &lt;ViewModels:CustomerVM/&gt; &lt;/ContentPage.BindingContext&gt; &lt;StackLayout Orientation="Vertical"&gt; &lt;ListView x:Name="CustomerListView" 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>
0
2,198
Should I use Perl's conditional ? : operator as a switch / case statement or instead of if elsif?
<p>Perl has a <a href="http://perldoc.perl.org/perlop.html#Conditional-Operator" rel="nofollow noreferrer">conditional</a> operator that is the same a <a href="http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html#Conditional-Expressions" rel="nofollow noreferrer">C's conditional operator</a>. </p> <p>To refresh, the conditional operator in C and in Perl is:</p> <pre><code>(test) ? (if test was true) : (if test was false) </code></pre> <p>and if used with an lvalue you can assign and test with one action:</p> <pre><code>my $x= $n==0 ? "n is 0" : "n is not 0"; </code></pre> <p>I was reading Igor Ostrovsky's blog on <a href="http://igoro.com/archive/a-neat-way-to-express-multi-clause-if-statements-in-c-based-languages/" rel="nofollow noreferrer">A neat way to express multi-clause if statements in C-based languages</a> and realized this is indeed a "neat way" in Perl as well. </p> <p>For example: (edit: used Jonathan Leffler's more readable form...)</p> <pre><code># ternary conditional form of if / elsif construct: my $s= $n == 0 ? "$n ain't squawt" : $n == 1 ? "$n is not a lot" : $n &lt; 100 ? "$n is more than 1..." : $n &lt; 1000 ? "$n is in triple digits" : "Wow! $n is thousands!" ; #default </code></pre> <p>Which reads a LOT easier than what many would write in Perl: (edit: used cjm's more elegant <code>my $t=do{ if };</code> form in rafi's answer)</p> <pre><code># Perl form, not using Switch or given / when my $t = do { if ($n == 0) { "$n ain't squawt" } elsif ($n == 1) { "$n is not a lot" } elsif ($n &lt; 100) { "$n is more than 1..." } elsif ($n &lt; 1000) { "$n is in triple digits" } else { "Wow! $n is thousands!" } }; </code></pre> <p>Are there any gotchas or downside here? Why would I not write an extended conditional form in this manner rather than use <code>if(something) { this } elsif(something) { that }</code>? </p> <p>The conditional operator has <a href="http://perldoc.perl.org/perlop.html#Operator-Precedence-and-Associativity" rel="nofollow noreferrer">right associativity and low precedence</a>. So:</p> <pre><code>a ? b : c ? d : e ? f : g </code></pre> <p>is interpreted as:</p> <pre><code>a ? b : (c ? d : (e ? f : g)) </code></pre> <p>I suppose you might need parenthesis if your tests used one of the few operator of lower precedence than <code>?:</code>. You could also put blocks in the form with braces I think. </p> <p>I do know about the deprecated <code>use Switch</code> or about Perl 5.10's <code>given/when</code> constructs, and I am not looking for a suggestion to use those.</p> <p>These are my questions: </p> <ul> <li><p>Have you seen this syntax used in Perl?** I have not, and it is not in <code>perlop</code> or <code>perlsyn</code> as an alternate to switch.</p></li> <li><p>Are there potential syntax problems or 'gotchas' with using a conditional / ternary operator in this way? </p></li> <li><p>Opinion: Is it more readable / understandable to you? Is it consistent with Idiomatic Perl?</p></li> </ul> <p><strong>-------- Edit --</strong></p> <p>I accepted Jonathan Leffler's answer because he pointed me to <a href="https://rads.stackoverflow.com/amzn/click/com/0596001738" rel="nofollow noreferrer" rel="nofollow noreferrer">Perl Best Practices</a>. The relevant section is 6.17 on <em>Tabular Ternaries.</em> This allowed me to investigate the use further. (If you Google Perl Tabular Ternaries, you can see other comments.)</p> <p>Conway's two examples are:</p> <pre><code>my $salute; if ($name eq $EMPTY_STR) { $salute = 'Dear Customer'; } elsif ($name =~ m/\A ((?:Sir|Dame) \s+ \S+)/xms) { $salute = "Dear $1"; } elsif ($name =~ m/([^\n]*), \s+ Ph[.]?D \z/xms) { $sa1ute = "Dear Dr $1"; } else { $salute = "Dear $name"; } </code></pre> <p>VS:</p> <pre><code> # Name format... # Salutation... my $salute = $name eq $EMPTY_STR ? 'Dear Customer' : $name =~ m/ \A((?:Sir|Dame) \s+ \S+) /xms ? "Dear $1" : $name =~ m/ (.*), \s+ Ph[.]?D \z /xms ? "Dear Dr $1" : "Dear $name" ; </code></pre> <p>My conclusions are: </p> <ul> <li><p>Conway's <code>?:</code> example is more readable and simpler to me than the <code>if/elsif</code> form, but I could see how the form could get hard to understand. </p></li> <li><p>If you have Perl 5.13.1, use <code>my $t=do { given { when } };</code> as an assignment as <a href="https://stackoverflow.com/questions/3898836/should-i-use-perls-conditional-operator-as-a-switch-case-statement-or-ins/3898866#3898866">rafi has done.</a> I think <code>given/when</code> is the best idiom now, unless the tabular ternary format is better for your particular case. </p></li> <li><p>If you have Perl 5.10+ use <code>given/when</code> in general instead of <code>Switch</code> or if you need some sort of case type switch. </p></li> <li><p>Older Perl's, this is a fine form for <em>simple</em> alternatives or as an alternate to a case statement. It is better than using <code>Switch</code> I think. </p></li> <li><p>The right to left associativity means the form is evaluated bottom to top. Remember that when using...</p></li> </ul>
0
2,113