title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
Swashbuckle - Add Model and Example values to Swagger UI from a Model from another project
<p>I am using Swagger to document my <code>.NET C#</code> API and when my models are on another project Swagger just crashes and doesn't load anything.</p> <p>When I load the sample <code>WebAPI</code> Project from Visual Studio it uses the models that are on the same project and it works:</p> <p><img src="https://i.stack.imgur.com/ZPuTI.png" alt="Visual Studio Sample Project Example Image"></p> <p>But when I use Models from other project it just crashes before loading anything.</p> <p>I have an API project and a Business Project. My models are View Models stored(and shared among other projects, therfore needed there) on my Buisiness Project.</p> <p>Is there any way I can indicate to Swagger where my model definitions are?</p>
0
Check for last iteration in jQuery.each
<p>How can we check for the last iteration of a <code>jQuery.each()</code> loop? My loop is iterating on an object coming from a <code>$.ajax</code> request. </p> <pre class="lang-js prettyprint-override"><code>jQuery.ajax({ url: "&lt;?php echo $this-&gt;getUrl('xs4arabia/index/getFetchrOrderLogs/'); ?&gt;", type: "GET", data: { tracking_id: tracking_id }, dataType: "json", success: function(data) { jQuery.each(data, function(key, value) { console.log(value); }) } }); </code></pre>
0
how to set the primary key when writing a pandas dataframe to a sqlite database table using df.to_sql
<p>I have created a sqlite database using pandas df.to_sql however accessing it seems considerably slower than just reading in the 500mb csv file. </p> <p>I need to: </p> <ol> <li>set the primary key for each table using the df.to_sql method</li> <li>tell the sqlite database what datatype each of the columns in my 3.dataframe are? - can I pass a list like [integer,integer,text,text]</li> </ol> <p>code.... (format code button not working)</p> <pre><code>if ext == ".csv": df = pd.read_csv("/Users/data/" +filename) columns = df.columns columns = [i.replace(' ', '_') for i in columns] df.columns = columns df.to_sql(name,con,flavor='sqlite',schema=None,if_exists='replace',index=True,index_label=None, chunksize=None, dtype=None) </code></pre>
0
run multiple node instance on same node using pm2
<p>I want to run 2 node.js application on single server , using pm2 and those application need to deploy via puppet.Could you please advise is this possible.</p> <p>Regards, Bala</p>
0
How to create new set of color styles in Bootstrap 4 with sass
<p>I'm starting to navigate through the wonderful Bootstrap 4 and I'm wondering how to add a whole new set of elements color to the _custom.scss </p> <p>Example: Right now you have btn-danger, text-danger etc... how to create for example, using a random name: "crisp" set... so you will have btn-crisp, text-crisp etc...</p> <p>My guess would be to start with adding a variable </p> <pre><code>$brand-crisp: #color !default; </code></pre> <p>But, then what? Thanks! I appreciate your help. </p>
0
"Server DNS address could not be found" error after adding subdomain in cPanel
<p>I'm trying to create a subdomain through cPanel. After adding the subdomain and visiting it in the browser, I get a <code>This site can’t be reached - server DNS address could not be found</code>. Can anyone please advise?</p>
0
Get all unique object properties from array of objects
<p>Let's imagine I have an array of objects e.g.</p> <pre><code> [{ "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "car": true }, { "firstName": "Peter", "lastName": "Jones" }] </code></pre> <p>I want to get all the unique property names from this array of objects, so the result will be:</p> <pre><code>[firstName, lastName, car] </code></pre> <p><strong>How can I do it:</strong></p> <p>I can imagine that it's possible to do this with something like this:</p> <pre><code>function getPropertiesNames(obj){ var arr = []; for(var name in obj) { if(arr.indexOf(name) != -1) arr.push(name); } return arr; } </code></pre> <p><strong>Why I need it:</strong></p> <p>I will have to make a table of multiple objects. Because each object can be a bit different I need unique property names. However I am going to do it in angularJS so it's kind of a bad option for me to once use loop to get property names for <code>&lt;th&gt;</code> and once again use loop with <code>&lt;tr ng-repeat&gt;&lt;/tr&gt;</code> to display values.</p> <p><strong>What i want:</strong></p> <p>Is there some option to get all unique property names from an array of objects without iterating it? Maybe some lodash or build in JS function which I don't know?</p>
0
Using a return/stop function on click
<p>Currently closee to finishing a slideshow using html and JavaScript. My last problem is creating stop button which needs to use a return function (I assume) Or some sort of exit function. It is an image slideshow that runs automatically, can be paused, skip image, go back an image and so on. I'd like the stop button to kill the autoRun function and set the image back to the first default image. I've set up a function which I'm guessing is totally wrong as it is not working. </p> <p>The HTML</p> <p></p> <pre><code> &lt;td class="controls"&gt; &lt;button onClick="autoRun()"&gt;Start&lt;/button&gt; &lt;button onClick="changeImage(-1); return false;"&gt;Previous Image&lt;/button&gt; &lt;button onClick="pause();"&gt;pause&lt;/button&gt; &lt;button onClick="changeImage(1); return false;"&gt;Next Image&lt;/button&gt; &lt;button onClick="Exit();"&gt;Exit&lt;/button&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>All buttons are working besides the last one</p> <p>JavaScript</p> <pre><code>var images = ["HGal0.jpg", "HGal1.jpg", "HGal2.jpg", "HGal3.jpg", "HGal4.jpg", "HGal5.jpg", "HGal6.jpg", "HGal7.jpg", "HGal8.jpg", "HGal9.jpg", "HGal10.jpg", "HGal11.jpg", "HGal12.jpg", "HGal13.jpg", "HGal14.jpg", "HGal15.jpg"]; var interval = setInterval("changeImage(1)", 2000); var imageNumber = 0; var imageLength = images.length - 1; function changeImage(x) { imageNumber += x; // if array has reached end, starts over if (imageNumber &gt; imageLength) { imageNumber = 0; } if (imageNumber &lt; 0) { imageNumber = imageLength; } document.getElementById("slideshow").src = images[imageNumber]; return false; } function autoRun() { interval = setInterval("changeImage(1)", 2000); } function pause(){ clearInterval(interval); interval = null; } function Exit(){ return; } </code></pre> <p>I'm not fully understanding the return statement in the Exit function, as most examples I've looked at run the function when an 'if' statement is met, whereas I'd like mine to execute when the Stop button is clicked. Thanks</p>
0
Calculate local time derivative of Series
<p>I have data that I'm importing from an hdf5 file. So, it comes in looking like this:</p> <pre><code>import pandas as pd tmp=pd.Series([1.,3.,4.,3.,5.],['2016-06-27 23:52:00','2016-06-27 23:53:00','2016-06-27 23:54:00','2016-06-27 23:55:00','2016-06-27 23:59:00']) tmp.index=pd.to_datetime(tmp.index) &gt;&gt;&gt;tmp 2016-06-27 23:52:00 1.0 2016-06-27 23:53:00 3.0 2016-06-27 23:54:00 4.0 2016-06-27 23:55:00 3.0 2016-06-27 23:59:00 5.0 dtype: float64 </code></pre> <p>I would like to find the local slope of the data. If I just do tmp.diff() I do get the local change in value. But, I want to get the change in value per second (time derivative) I would like to do something like this, but this is the wrong way to do it and gives an error:</p> <pre><code>tmp.diff()/tmp.index.diff() </code></pre> <p>I have figured out that I can do it by converting all the data to a DataFrame, but that seems inefficient. Especially, since I'm going to have to work with a large, on disk file in chunks. Is there a better way to do it other than this:</p> <pre><code>df=pd.DataFrame(tmp) df['secvalue']=df.index.astype(np.int64)/1e+9 df['slope']=df['Value'].diff()/df['secvalue'].diff() </code></pre>
0
Get dimensions of image with React
<p>I need to get the dimensions of an image with React. I found a library called <a href="https://github.com/souporserious/react-measure" rel="noreferrer">react-measure</a> that computes measurements of React components. It works, but I can't get it to fire when the image has loaded. I need to get it to fire when the image loads so I get accurate dimensions and not 0 x 157 or something like that.</p> <p>I tried using the <code>onLoad</code> Image Event to detect when the image has loaded, but I didn't get satisfactory results. Essentially what I've done is when the image has loaded (<code>handleImageLoaded()</code> has been called), change the <code>hasLoaded</code> state property to <code>true</code>. I know for a fact that <code>hasLoaded</code> has been changed to <code>true</code> because it says so: <code>Image Loaded: true</code>.</p> <p>What I noticed is that I can calculate the dimensions for only images that have been cached...</p> <p><strong>Here is a demo video</strong>: cl.ly/250M2g3X1k21</p> <p>Is there a better, more concise way of retrieving dimensions properly with React? </p> <p>Here is the code:</p> <pre><code>import React, {Component} from 'react'; import Measure from '../src/react-measure'; class AtomicImage extends Component { constructor() { super(); this.state = { hasLoaded: false, dimensions: {} }; this.onMeasure = this.onMeasure.bind(this); this.handleImageLoaded = this.handleImageLoaded.bind(this); } onMeasure(dimensions) { this.setState({dimensions}); } handleImageLoaded() { this.setState({hasLoaded: true}); } render() { const {src} = this.props; const {hasLoaded, dimensions} = this.state; const {width, height} = dimensions; return( &lt;div&gt; &lt;p&gt;Dimensions: {width} x {height}&lt;/p&gt; &lt;p&gt;Image Loaded: {hasLoaded ? 'true' : 'false'}&lt;/p&gt; &lt;Measure onMeasure={this.onMeasure} shouldMeasure={hasLoaded === true}&gt; &lt;div style={{display: 'inline-block'}}&gt; &lt;img src={src} onLoad={this.handleImageLoaded}/&gt; &lt;/div&gt; &lt;/Measure&gt; &lt;/div&gt; ); } } export default AtomicImage; </code></pre> <p>Here is the parent code. It's not really important—just passes <code>src</code> to the <code>AtomicImage</code> element:</p> <pre><code>import React, {Component} from 'react'; import ReactDOM from 'react-dom'; import AtomicImage from './AtomicImage'; class App extends Component { constructor() { super(); this.state = {src: ''} this.handleOnChange = this.handleOnChange.bind(this); } handleOnChange(e) { this.setState({src: e.target.value}); } render() { const {src} = this.state; return ( &lt;div&gt; &lt;div&gt; &lt;input onChange={this.handleOnChange} type="text"/&gt; &lt;/div&gt; &lt;AtomicImage src={src} /&gt; &lt;/div&gt; ) } } ReactDOM.render(&lt;App /&gt;, document.getElementById('app')); </code></pre>
0
For Node.js applications, when to use port 3000 vs 8080?
<p>I have been reading up on some tutorials, and although most of them use port <code>3000</code> for node applications. Some of them use port <code>8080</code> instead. I am wondering what is the recommended practice, and under what circumstances should we use the other. Any guidelines?</p>
0
flexbox: stretching the height of elements with flex-direction: row
<p>I want to stretch two div elements (<code>.sideline</code> and <code>.main-contents</code>) to reach the bottom of the page and stay at a certain height from the footer.</p> <p>The two divs are nested inside a div (<code>.row-elements</code>) with the <code>flex-direction: row</code> since I wanted them to be on the same row.</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>/* body { display:flex; flex-direction:column; } */ .one-above-all { display: flex; flex-direction: column; /* flex: 1 0 auto; */ /* min-height: 1100px; */ border: solid black 1px; } .top-block { margin: 0 auto; border: solid black 1px; width: 300px; height: 30px; margin-top: -15px; } .headline { border: solid black 1px; width: 90%; align-self: flex-end; margin-top: 40px; margin-right: 10px; height: 160px; display: flex; box-sizing: border-box; } .row-elements { display: flex; flex-direction: row; margin-top: 40px; align-items: stretch; /* min-height: 900px; flex: 1 0 auto; */ } .sideline { width: 160px; border: solid 1px; margin-left: calc(10% - 10px); box-sizing: border-box; flex-shrink: 1 } .main-contents { border: solid 1px; margin-left: 40px; /* align-self: stretch; */ flex: 1 1 auto; margin-right: 10px; box-sizing: border-box; } .bottom-block { align-self: flex-end; margin-top: auto; border: black solid 1px; margin: auto; width: 300px; height: 30px; margin-bottom: -10px; /* margin-top: 880px; */ } /* .stretch-test { border:solid, 1px; display: flex; flex-direction: column; flex: 1 0 auto; } */</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="one-above-all"&gt; &lt;div class="top-block"&gt;&lt;/div&gt; &lt;div class="headline"&gt;&lt;/div&gt; &lt;!-- &lt;div class="stretch-test"&gt; --&gt; &lt;div class="row-elements"&gt; &lt;div class="sideline"&gt;&lt;/div&gt; &lt;div class="main-contents"&gt;jhjkdhfjksdhafjksdahfl&lt;/div&gt; &lt;!--&lt;/div&gt; --&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="bottom-block"&gt;footer&lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="http://codepen.io/binarytrance/pen/xOoydX" rel="nofollow">Codepen</a></p> <p>The commented out code in the css is the things I have tried.</p> <p>I tried to set the <code>body</code> as flex and give the row-elements class <code>flex</code> property of <code>1 0 auto</code> which didn't work.</p> <p>I tried nesting the <code>row-elements</code> class (which has the <code>flex-direction</code> of <code>row</code>) in another div with a <code>flex-direction</code> of <code>column</code> and setting <code>.row-elements</code> to <code>flex:1 0 auto</code> which also didn't work.</p> <p>I tried totally removing the the row-elements class but the two divs won't come on the same row.</p> <p>Any solution will be appreciated.</p>
0
What is spark.driver.maxResultSize?
<p>The <a href="http://spark.apache.org/docs/latest/configuration.html" rel="noreferrer">ref</a> says:</p> <blockquote> <p>Limit of total size of serialized results of all partitions for each Spark action (e.g. collect). Should be at least 1M, or 0 for unlimited. Jobs will be aborted if the total size is above this limit. Having a high limit may cause out-of-memory errors in driver (depends on spark.driver.memory and memory overhead of objects in JVM). Setting a proper limit can protect the driver from out-of-memory errors.</p> </blockquote> <p>What does this attribute do exactly? I mean at first (since I am not battling with a job that fails due to out of memory errors) I thought I should increase that.</p> <p>On second thought, it seems that this attribute defines the max size of the result a worker can send to the driver, so leaving it at the default (1G) would be the best approach to protect the driver..</p> <p>But will happen on this case, the worker will have to send more messages, so the overhead will be just that the job will be slower?</p> <hr> <p>If I understand correctly, assuming that a worker wants to send 4G of data to the driver, then having <code>spark.driver.maxResultSize=1G</code>, will cause the worker to send 4 messages (instead of 1 with unlimited <code>spark.driver.maxResultSize</code>). If so, then increasing that attribute to protect my driver from being assassinated from Yarn should be wrong.</p> <p>But still the question above remains..I mean what if I set it to 1M (the minimum), will it be the most protective approach?</p>
0
Embedding facebook post on responsive website
<p>I want to embed some Facebook posts (images) on my website, which is intended to be responsive. I am using bootstrap as a main frame for everything and it is very easy to get typical image responsiveness.</p> <p>Unfortunately with Facebook posts those are <code>iframe</code> objects and they don't want to scale so nicely. </p> <p>For my tests I am using this iframe:</p> <pre><code>&lt;div class="iframe_div"&gt; &lt;div&gt;Title&lt;/div&gt; &lt;div&gt; &lt;iframe src="https://www.facebook.com/plugins/post.php?href=https%3A%2F%2Fwww.facebook.com%2FKickstarter%2Fphotos%2Fa.10152384621799885.1073741831.73182029884%2F10154511546454885%2F%3Ftype%3D3&amp;width=500" style="border:none;overflow:hidden;width:100%;height:100%;position:absolute;left:0;" scrolling="no" frameborder="0" allowTransparency="true"&gt;&lt;/iframe&gt; &lt;/div&gt; &lt;div&gt;Tekst&lt;/div&gt; &lt;/div&gt; </code></pre> <p>My problem is that when I am changing the size of the window I can sometimes see whole post and other time only top half of it. Well, more precisely it is gradually changing between those two values. Good thing is that it is never too wide, but it is not height enough to display whole.</p> <p>Another issue is that it overlays the text below it, and only if I'll set some fixed value for <code>iframe_div</code> I am able to see it, but then it is not responsive design.</p> <p>Does anyone managed to embed facebook post in responsive design page?</p>
0
How to integrate or make use of KeyCloak user database in my application?
<p>So far I have been playing with KeyCloak and been able to set it up and running the customer-portal example successfully. Now I need to actually use it in my application, and I am not totally sure whether KeyCloak is the right thing that I am looking for, but I believe my need is just a common use case and hopefully KeyCloak is the right software that I am looking for..</p> <p>When a user comes to my website, he registers and makes a post. Both the post and the user information is stored into databases, and the link between the user and post, i.e. who made which post? So I have two tables in my database: Post(id, post) and User(id,name), and another table UserPost(PostID, UserID) to store linking information. This is all fine in my own database.</p> <p>But now when KeyCloak comes into play, the user first registers in KeyCloak server and user information are stored in its own database there, which seems unrelated to the database (Post and User) in my application. I don't want to duplicate two User databases in two servers, right? Even if I can tolerate the duplication, how to make the connection between KeyCloak database and my application database? I am using JBoss, Hibernate/JPA in my application.</p> <p>Maybe I am missing something in the way how to connect KeyCloak user table with my own application database. Is there any tutorial or documentation that I can read? </p> <p>Thank you.</p> <p>Updated: This User table in my application only stores an id, which will come from the KeyCloak user registration information, and one more field 'reputation' which will be assigned based on this user's new post. Most other attributes of a user will be kept intact in the KeyCloak's USER_ENTITY table. Now, whenever a new user registers, KeyCloak will insert a record into the USER_ENTITY table. No worry about that. But at the same time, I need to add a record to the User table in my application based on the user ID from the KeyCloak USER_ENTITY. The question is how to get the User ID from Keycloak from the registration html page? </p> <pre><code>@Entity public class User { @Id private Long id; private int reputation = 0; @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) private List&lt;Post&gt; posts = new ArrayList&lt;&gt;(); public User() { } public User(Long id, int reputation) { this.id = id; this.reputation = reputation; } public void setId(Long id) { } public Long getId() { return id; } public void setReputation(int reputation) { this.reputation = reputation; } public int getReputation() { return reputation; } public List&lt;Post&gt; getPosts() { return posts; } } @Entity public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne private User user; private String text; public Post() { } public Long getId() { return id; } public void setUser(User user) { this.user = user; } public User getUser() { return user; } public void setText(String text) { this.text = text; } public String getText() { return text; } } </code></pre>
0
Accessing input field value without ngModel in Angular2/Typescript
<p>I'm using Typescript with Angular2, just like in the Angular2 Tour of Heroes tutorial.</p> <p>I have an input field that I want to attach a <code>change</code> event to, so that some custom logic can perform when the field is changed. I need to know the field's current value to perform the logic, so I don't want to bind that field with <code>ngModel</code>, as that will override the property before I'm able to retrieve its former value before it was changed.</p> <p>So I have something like:</p> <pre><code>&lt;input (change)="handleChange(myObj, $event)" value={{ myObj.myField }}... /&gt; </code></pre> <p>Then in handleChange:</p> <pre><code>handleChange (obj: MyObjectClass, e: Event) { oldValue: number = obj.myField; newValue : number = parseInt(e.target.value); // Do some logic obj.myField = newValue; } </code></pre> <p>While this works fine in code, the Typescript compiler is throwing an error <code>error TS2339: Property 'value' does not exist on type 'EventTarget'.</code> on the line <code>newValue : number = parseInt(e.target.value);</code></p> <p>Is there a better way of doing this?</p>
0
After session destroy or close browser tab or close browser execute logout using Laravel 5.2
<p>In my project I am using session destroy method which very simple way in Laravel 5.2 . </p> <pre><code>/* |-------------------------------------------------------------------------- | Session Lifetime |-------------------------------------------------------------------------- | | Here you may specify the number of minutes that you wish the session | to be allowed to remain idle before it expires. If you want them | to immediately expire on the browser closing, set that option. | */ 'lifetime' =&gt; 10, 'expire_on_close' =&gt; true, </code></pre> <p>Now my question is when session destroy automatically or user close browser tab or close browser that time execute logout query. Is it possible execute logout function all cases?</p> <p>My logout function</p> <pre><code>public function logout() { $user = Auth::user()-&gt;toArray(); $user1 = ActiveUsers::where("assinedto_id",'=',$user['_id']); $user1 -&gt;delete(); Auth::logout(); return redirect('/login'); } </code></pre> <p>I want to when session destroy or close browser tab or close browser that time run <strong><code>logout()</code></strong> function. Please suggest me. Thanks</p>
0
How to match a pattern given in a variable in awk?
<p>I want to extract a substring where certain pattern exist from pipe separated file, thus I used below command,</p> <pre><code>awk -F ":" '/REWARD REQ. SERVER HEADERS/{print $1, $2, $3, $4}' sample_profile.txt </code></pre> <p>Here, 'REWARD REQ. SERVER HEADERS' is a pattern which is to be searched in the file, and print its first 4 parts on a colon separated line.</p> <p>Now, I want to send bash variable to act as a pattern. thus I used below command, but it's not working.</p> <pre><code>awk -v pat="$pattern" -F ":" '/pat/{print $1, $2 , $3, $4 } sample_profile.txt </code></pre> <p>How can I use <code>-v</code> and <code>-F</code> in a single <code>awk</code> command?</p>
0
Windows bundle install: HOME environment variable (or HOMEDRIVE and HOMEPATH) must be set and point to a directory (RuntimeError)
<p>I installed bundler succesfully with</p> <pre><code>gem install bundler </code></pre> <p>Then I try to do</p> <pre><code>bundle install </code></pre> <p>I get following error:</p> <pre><code>C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rbreadline.rb:1097:in `&lt;module:RbReadline&gt;': HOME environment variable (or HOMEDRIVE and HOMEPATH) must be set and point to a directory (RuntimeError) from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rbreadline.rb:17:in `&lt;top (required)&gt;' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/readline.rb:10:in `&lt;module:Readline&gt;' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/readline.rb:8:in `&lt;top (required)&gt;' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor/line_editor/readline.rb:2:in `&lt;top (required)&gt;' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor/line_editor.rb:2:in `&lt;top (required)&gt;' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor/base.rb:8:in `&lt;top (required)&gt;' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/vendor/thor/lib/thor.rb:2:in `&lt;top (required)&gt;' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/vendored_thor.rb:3:in `&lt;top (required)&gt;' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/friendly_errors.rb:4:in `&lt;top (required)&gt;' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/exe/bundle:18:in `&lt;top (required)&gt;' from C:/Ruby22-x64/bin/bundle:22:in `load' from C:/Ruby22-x64/bin/bundle:22:in `&lt;main&gt;' </code></pre> <p>Seems to be error with environment variables, however those are set properly in my system</p> <pre><code>set HOME HOMEDRIVE=C: HOMEPATH=\Users\My Näme </code></pre> <p>Yes, I have scandinavian letter in my name so I'm wondering if that is the problem. I've faced that once before with web2py installer I think.</p> <p>Anyway, any ideas how to solve that problem?</p>
0
ipython notebook clear all code
<p>All I want to do is try some new codes in ipython notebook and I don't want to save it every time as its done automatically. Instead what I want is clear all the codes of ipython notebook along with reset of variables.</p> <p>I want to do some coding and clear everything and start coding another set of codes without going to new python portion and without saving the current code.</p> <p>Any shortcuts will be appreciated.</p> <p>Note: I want to clear every cells code one time. All I want is an interface which appears when i create new python file, but I don't want to save my current code.</p>
0
Flask session variable not persisting between requests
<p>Using the app below and Flask 0.11.1, I navigated to the routes associated with the following function calls, with the given results: </p> <ul> <li>create(): '1,2,3' # OK</li> <li>remove(1) : '2,3' # OK</li> <li>remove(2) : '1,3' # expected '3'</li> <li>maintain(): '1,2,3' # expected '1,3' or '3'</li> </ul> <p>&nbsp;</p> <pre><code>from flask import Flask, session app = Flask(__name__) @app.route('/') def create(): session['list'] = ['1','2','3'] return ",".join(session['list']) @app.route('/m') def maintain(): return ",".join(session['list']) @app.route('/r/&lt;int:id&gt;') def remove(id): session['list'].remove(str(id)) return ",".join(session['list']) if __name__ == '__main__': app.secret_key = "123" app.run() </code></pre> <p>This question is similar in theme to <a href="https://stackoverflow.com/questions/18139910/using-session-in-flask-app">this question</a>, <a href="https://stackoverflow.com/questions/18709213/flask-session-not-persisting">this</a>, and <a href="https://stackoverflow.com/questions/7100315/flask-session-member-not-persisting-across-requests">this one</a>, but I'm setting the secret key and not regenerating it, and my variable is certainly not larger than the 4096 bytes allowed for cookies. Perhaps I'm missing some more basic understanding about Flask session variables?</p>
0
How can I create a custom ArgumentMatcher that accepts arguments from other matchers?
<p>I'm currently writing unit tests on a code base that uses a lot of <code>ActionEvent</code>'s internally, and since <code>ActionEvent</code> doesn't override <code>equals()</code>, I'm creating a custom <code>ArgumentMatcher</code> to match <code>ActionEvent</code>'s.</p> <p>My <code>ArgumentMatcher</code> currently looks like this:</p> <pre><code>public class ActionEventMatcher extends ArgumentMatcher&lt;ActionEvent&gt; { private Object source; private int id; private String actionCommand; public ActionEventMatcher(Object source, int id, String actionCommand) { this.source = source; this.id = id; this.actionCommand = actionCommand; } @Override public boolean matches(Object argument) { if (!(argument instanceof ActionEvent)) return false; ActionEvent e = (ActionEvent)argument; return source.equals(e.getSource()) &amp;&amp; id == e.getId() &amp;&amp; actionCommand.equals(e.getActionCommand()); } } </code></pre> <p>I would like to know if it possible to change my <code>ArgumentMatcher</code> so that it accepts arguments that were created from other matchers. For instance, if I have a method called <code>actionEvent()</code> that returns the matcher, I would like to be able to do the following:</p> <pre><code>verify(mock).fireEvent(argThat(actionEvent(same(source), anyInt(), eq("actionCommand")))); </code></pre> <p>Is there a way to have a custom <code>ArgumentMatcher</code> that accepts arguments from other matchers this way?</p>
0
NSAttributedString extension in swift 3
<p>I'm migrating my code to swift 3 and I'm having a hard time with this extension that was working on the previous swift version.</p> <pre><code>extension Data { var attributedString: NSAttributedString? { do { return try NSAttributedString(data: self, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8], documentAttributes: nil) } catch let error as NSError { print(error.localizedDescription) } return nil } } </code></pre> <p>Now when I try to call this piece of code I get an exception error like this</p> <pre><code>error: warning: couldn't get required object pointer (substituting NULL): Couldn't load 'self' because its value couldn't be evaluated </code></pre> <p>That's how I call the method from my view controller</p> <pre><code>let htmlCode = "&lt;html&gt;&lt;head&gt;&lt;style type=\"text/css\"&gt;@font-face {font-family: Avenir-Roman}body {font-family: Avenir-Roman;font-size:15;margin: 0;padding: 0}&lt;/style&gt;&lt;/head&gt;&lt;body bgcolor=\"#FBFBFB\"&gt;" + htmlBodyCode + "&lt;/body&gt;" newsDescription.attributedText = htmlCode.utf8Data?.attributedString </code></pre>
0
Unable to change MUI table padding
<p>I am using the <code>Table</code> component from the <code>react</code> library <code>material-ui</code>.<br/> For some reason, each row, including the header, has a <code>24px</code> padding, top and bottom, which I can't override.<br/> I already tried changing the style on all the underlying components with no success. Here is the code:</p> <pre><code>&lt;Table&gt; &lt;TableHeader adjustForCheckbox={false} displaySelectAll={false} fixedHeader={true}&gt; &lt;TableRow&gt; &lt;TableHeaderColumn&gt;id&lt;/TableHeaderColumn&gt; &lt;TableHeaderColumn&gt;name&lt;/TableHeaderColumn&gt; &lt;TableHeaderColumn&gt;number&lt;/TableHeaderColumn&gt; &lt;/TableRow&gt; &lt;/TableHeader&gt; &lt;TableBody showRowHover={true} displayRowCheckbox={false}&gt; {data.map(item =&gt; { return ( &lt;TableRow key={item.id}&gt; &lt;TableRowColumn&gt;{item.id}&lt;/TableRowColumn&gt; &lt;TableRowColumn&gt;{item.name}&lt;/TableRowColumn&gt; &lt;TableRowColumn&gt;{item.number}&lt;/TableRowColumn&gt; &lt;/TableRow&gt; ); })} &lt;/TableBody&gt; &lt;/Table&gt; </code></pre> <p>Any idea how which component's style needs to be changed in order to override this styling?</p>
0
How to add json to RestSharp POST request
<p>I have the following JSON string that is passed into my c# code as a string parameter - AddLocation(string locationJSON):</p> <pre><code>{"accountId":"57abb4d6aad4","address":{"city":"TEST","country":"TEST","postalCode":"TEST","state":"TEST","street":"TEST"},"alternateEmails":[{"email":"TEST"}],"alternatePhoneNumbers":[{"phoneNumber":"TEST"}],"alternateWebsites":[{"website":"TEST"}],"auditOnly":false,"busName":"593163b7-a465-43ea-b8fb-e5b967d9690c","email":"TEST EMAIL","primaryKeyword":"TEST","primaryPhone":"TEST","rankingKeywords":[{"keyword":"TEST","localArea":"TEST"}],"resellerLocationId":"5461caf7-f52f-4c2b-9089-2ir8hgdy62","website":"TEST"} </code></pre> <p>I'm trying to add the JSON to a RestSharp POST request like this but it's not working:</p> <pre><code>public string AddLocation(string locationJSON) { var client = new RestClient(_authorizationDataProvider.LocationURL); var request = new RestRequest(Method.POST); request.RequestFormat = DataFormat.Json; request.AddHeader("cache-control", "no-cache"); request.AddHeader("Authorization", _authorizationResponse.Token); ... request.AddJsonBody(locationJSON); var response = client.Execute(request); } </code></pre> <p>The response comes back as "Bad Request". Here is what I get if I inspect the response in the debugger:</p> <pre><code>{"code":"invalid_json","details":{"obj.address":[{"msg":["error.path.missing"],"args":[]}],"obj.rankingKeywords":[{"msg":["error.path.missing"],"args":[]}],"obj.alternatePhoneNumbers":[{"msg":["error.path.missing"],"args":[]}],"obj.busName":[{"msg":["error.path.missing"],"args":[]}],"obj.accountId":[{"msg":["error.path.missing"],"args":[]}],"obj.alternateEmails":[{"msg":["error.path.missing"],"args":[]}],"obj.alternateWebsites":[{"msg":["error.path.missing"],"args":[]}],"obj.email":[{"msg":["error.path.missing"],"args":[]}],"obj.primaryKeyword":[{"msg":["error.path.missing"],"args":[]}],"obj.auditOnly":[{"msg":["error.path.missing"],"args":[]}]}} </code></pre> <p>I have inspected the request parameters after calling AddJsonBody and the value appears to be including the escape sequence for double quotes - which seems to be the issue.</p> <pre><code>{\"accountId\":\"57abb4d6aad4def3d213c25d\",\"address\":{\"city\":\"TEST\",\"country\":\"TEST\",\"postalCode\":\"TEST\",\"state\":\"TEST\",\"street\":\"TEST\"},\"alternateEmails\":[{\"email\":\"TEST\"}],\"alternatePhoneNumbers\":[{\"phoneNumber\":\"TEST\"}],\"alternateWebsites\":[{\"website\":\"TEST\"}],\"auditOnly\":false,\"busName\":\"84e7ef98-7a9f-4805-ab45-e852a4b078d8\",\"email\":\"TEST EMAIL\",\"primaryKeyword\":\"TEST\",\"primaryPhone\":\"TEST\",\"rankingKeywords\":[{\"keyword\":\"TEST\",\"localArea\":\"TEST\"}],\"resellerLocationId\":\"06b528a9-22a6-4853-8148-805c9cb46941\",\"website\":\"TEST\"} </code></pre> <p>so my question is how do I add a json string to the request body?</p>
0
How to overwrite remote branch with different local branch with git
<p>I have a remote branch that is the basis for a pullrequest.</p> <p>I mainly worked on a different branch, however that should now replace the old branch. </p> <p>I tried to do a <code>git push remote oldBranch -f</code> but that only pushes my latest local <code>oldBranch</code> to the git server instead of the current branch - no matter which branch i am currently on.</p> <p>How can I replace the remote branch with my local branch?</p> <p>EDIT: If anybody else is interested, this is how i got this to work:</p> <pre><code>git checkout oldBranch git branch -m 'oldBranchToBeReplaced' git checkout newBranch git branch -m oldBranch git push myrepo oldBranch -f </code></pre>
0
Append button to a table row dynamically using jquery
<p>I have an array of JavaScript JSON objects which is being parsed from a JSON formatted-string. Now what I'm doing is that I'm looping through the array and append the data to a table within the page.</p> <h3>jQuery Code:</h3> <pre><code>$.each(objArr, function(key, value) { var tr = $("&lt;tr /&gt;"); $.each(value, function(k, v) { tr.append($("&lt;td /&gt;", { html: v })); $("#dataTable").append(tr); }) }) </code></pre> <p>The code works perfectly and the table is getting populated successfully</p> <p>But what I'm looking for is that, I want to add a delete <strong>button</strong> at the <strong>end</strong> of the row, by which the user will delete the row, and it also important to handle the click event in order to perform the required action</p> <p>I've done this in another way, but it is not that efficient, I want to use the code above to accomplish that as it is more efficient:</p> <pre><code>for (var i = 0; i &lt; objArr.length; i++) { var tr = "&lt;tr&gt;"; var td1 = "&lt;td&gt;" + objArr[i]["empID"] + "&lt;/td&gt;"; var td2 = "&lt;td&gt;" + objArr[i]["fname"] + "&lt;/td&gt;"; var td3 = "&lt;td&gt;" + objArr[i]["lname"] + "&lt;/td&gt;"; var td4 = "&lt;td&gt;" + objArr[i]["phone"] + "&lt;/td&gt;"; var td5 = "&lt;td&gt;" + objArr[i]["address"] + "&lt;/td&gt;"; var td6 = "&lt;td &gt;" + objArr[i]["deptID"] + "&lt;/td&gt;"; var td7 = "&lt;td&gt;" + objArr[i]["email"] + "&lt;/td&gt;"; var td8 = "&lt;td&gt;" + '&lt;button id="' + objArr[i]["empID"] + '" value="' + objArr[ i]["empID"] + '" onclick="onClickDelete(' + objArr[i]["empID"] + ')"&gt;Delete&lt;/button&gt;' + "&lt;/td&gt;&lt;/tr&gt;"; $("#dataTable").append(tr + td1 + td2 + td3 + td4 + td5 + td6 + td7 + td8); } </code></pre> <p>Any suggestions please?</p>
0
How to bind user object to request in a middleware
<p>i'm writing an application in Laravel Spark 1.0 (Laravel 5.2). I wrote a custom middleware for agent (api) authentication. This is the code:</p> <pre><code>&lt;?php namespace App\Http\Middleware; use App\Agent; use Closure; use Illuminate\Http\Request; class AgentAuth { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if( isset($request-&gt;token) &amp;&amp; !empty($request-&gt;token) ) { $agent = Agent::where('token', '=', $request-&gt;token)-&gt;first(); if( $agent != NULL ) { $team = $agent-&gt;Team()-&gt;first(); $user = $team-&gt;User()-&gt;first(); $request-&gt;merge(['team' =&gt; $team ]); $request-&gt;merge(['user' =&gt; $user ]); return $next($request); } else { return response('Unauthorized 2.', 401); } } else { return response('Unauthorized 1.', 401); } } } </code></pre> <p>In the default laravel authentication the user object is injected in the request (see laravel docs): <a href="https://laravel.com/docs/5.2/authentication#retrieving-the-authenticated-user" rel="noreferrer">https://laravel.com/docs/5.2/authentication#retrieving-the-authenticated-user</a></p> <p>So you can retrieve the user using:</p> <pre><code>$request-&gt;user(); </code></pre> <p>Spark obviously use this method to check if user subscription is valid (laravel\spark\src\Http\Middleware\VerifyUserIsSubscribed):</p> <pre><code>if ($this-&gt;subscribed($request-&gt;user(), $subscription, $plan, func_num_args() === 2)) { return $next($request); } </code></pre> <p>And it's not working because, with my middleware, you can retrieve the user using: <code>$request-&gt;user;</code> but not with the laravel defaults <code>$request-&gt;user();</code></p> <p>How should i inject the user object into the request?</p> <p>Thank you in advance</p> <p><strong>EDIT:</strong></p> <p>Laravel in the service provider (Illuminate\Auth\AuthServiceProvider@registerRequestRebindHandler)</p> <p>Use this code to bind object user to the request:</p> <pre><code>/** * Register a resolver for the authenticated user. * * @return void */ protected function registerRequestRebindHandler() { $this-&gt;app-&gt;rebinding('request', function ($app, $request) { $request-&gt;setUserResolver(function ($guard = null) use ($app) { return call_user_func($app['auth']-&gt;userResolver(), $guard); }); }); } </code></pre> <p>I tried to insert this code, with the appropriate correction, in the middleware but i can't figure out how to make it work.</p>
0
Log4j2 Custom appender: ERROR Attempted to append to non-started appender
<p>I have created a custom appender in log4j2. While using the custom appender, I am getting the following error: "ERROR Attempted to append to non-started appender". Any help is appreciated.</p>
0
Angular2 RC5 Mock Activated Route Params
<p>I need to be able to mock the activated route parameters to be able to test my component.</p> <p>Here's my best attempt so far, but it doesn't work.</p> <pre><code>{ provide: ActivatedRoute, useValue: { params: [ { 'id': 1 } ] } }, </code></pre> <p>The ActivatedRoute is used in the actual component like this:</p> <pre><code>this.route.params.subscribe(params =&gt; { this.stateId = +params['id']; this.stateService.getState(this.stateId).then(state =&gt; { this.state = state; }); }); </code></pre> <p>The error I get with my current attempt is simply:</p> <p><code>TypeError: undefined is not a constructor (evaluating 'this.route.params.subscribe')</code></p> <p>Any help would be greatly appreciated.</p>
0
Scala sbt run - "Unsupported major.minor version 52.0"
<p>Things run without any problem when I work on IntelliJ, but when I try to compile and run my Scala code in the command line (with <code>sbt run</code>) the following error message pops up.</p> <pre><code>[error] (run-main-0) java.lang.UnsupportedClassVersionError: akka/event/LogSource : Unsupported major.minor version 52.0 java.lang.UnsupportedClassVersionError: akka/event/LogSource : Unsupported major.minor version 52.0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:803) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2625) at java.lang.Class.getMethod0(Class.java:2866) at java.lang.Class.getMethod(Class.java:1676) </code></pre> <p>I'm using Ubuntu 14.04 LTS.</p> <pre><code>$ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 14.04.5 LTS Release: 14.04 Codename: trusty </code></pre> <p>And my Scala version is 2.9.2.</p> <pre><code>$ scalac -version Scala compiler version 2.9.2 -- Copyright 2002-2011, LAMP/EPFL </code></pre> <p>I barely started learning Scala a few weeks ago, so if anyone could provide some advice on what I should look into, it would be greatly appreciated.</p>
0
Laravel 5.3 Redefine "reset email" blade template
<p>How to customize the path of the reset email blade template in Laravel 5.3?</p> <p>The template used is: <code>vendor/laravel/framework/src/Illuminate/Notifications/resources/views/email.blade.php</code></p> <p>I'd like to build my own.</p> <p>Also, how to change the text of this email predefined in: <code>vendor/laravel/framework/src/Illuminate/Auth/Notifications/ResetPassword.php</code></p> <pre><code>public function toMail() { return (new MailMessage) -&gt;line([ 'You are receiving this email because we received a password reset request for your account.', 'Click the button below to reset your password:', ]) -&gt;action('Reset Password', url('password/reset', $this-&gt;token)) -&gt;line('If you did not request a password reset, no further action is required.'); } </code></pre>
0
Kafka - difference between Log end offset(LEO) vs High Watermark(HW)
<p>What is the difference between <code>LEO and HW</code> in Replica ( <code>Leader Replica</code>)?</p> <p>Will they contain the same number? I can understand HW is the <code>last committed message offset</code>.</p> <p>When LEO will be updated and how?</p>
0
Pandas Mean for Certain Column
<p>I have a pandas dataframe like that:</p> <p><a href="https://i.stack.imgur.com/KOZan.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KOZan.png" alt="enter image description here"></a></p> <p>How can I able to calculate mean (min/max, median) for specific column if Cluster==1 or CLuster==2?</p> <p>Thanks!</p>
0
More than 2 buttons on sweetalert 2
<p>I have a sweetalert with 2 buttons but I want to have one more button in it. For example, as of now, I have yes and no I want to add one more button say later. Please help.</p> <pre><code>$("#close_account").on("click", function(e) { e.preventDefault(); swal({ title: "Are you sure?", text: "You will not be able to open your account!", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes, close my account!", closeOnConfirm: false }, function() { window.location.href="&lt;?php echo base_url().'users/close_account' ?&gt;" }); }); </code></pre> <p>Thanks in advance.</p>
0
stop a long running PS cmdlet
<p>I've seen articles that mention hitting Ctrl+C or Ctrl+Break to stop Powershell in it's tracks but I see varied responses to this. For example if I run: <code>dir -include *.txt -recurse</code> And then get tired of watching screens of info I will try to break out using one of the keyboard shortcuts mentioned above but it keeps on going. Alt + F4 is the only thing that works. What is the best way to kill it instantly?</p>
0
Get lag with cross-correlation?
<p>Let's say have have two signals:</p> <pre><code>import numpy dt = 0.001 t_steps = np.arange(0, 1, dt) a_sig = np.sin(2*np.pi*t_steps*4+5) b_sig = np.sin(2*np.pi*t_steps*4) </code></pre> <p>I want to shift the first signal to match the second signal. I know this can be completed using cross-correlation, as evidenced by Matlab, but how do I accomplish this with SciPy.</p>
0
Image clustering by its similarity in python
<p>I have a collection of photos and I'd like to distinguish clusters of the similar photos. Which features of an image and which algorithm should I use to solve my task?</p>
0
Karma Webpack sourcemaps not working
<p>I'm using Karma-Webpack to run my Angular 2 specs.</p> <p><a href="https://github.com/webpack/karma-webpack">https://github.com/webpack/karma-webpack</a></p> <p>When I execute tests using karma in Chrome, the source files for my specs appear readable in the debugger. However, the system under test files (my application source) is unreadable.</p> <p>I'm using the karma-sourcemap-loader and have devtool set to 'inline-source-map' as instructed. What could be causing this problem?</p> <p>This build is modeled after the AngularClass angular2-webpack-starter. <a href="https://github.com/AngularClass/angular2-webpack-starter">https://github.com/AngularClass/angular2-webpack-starter</a></p> <p>Spec file in debugger:</p> <p><a href="https://i.stack.imgur.com/uHECb.png"><img src="https://i.stack.imgur.com/uHECb.png" alt="enter image description here"></a></p> <p>SUT file in debugger:</p> <p><a href="https://i.stack.imgur.com/fSANN.png"><img src="https://i.stack.imgur.com/fSANN.png" alt="enter image description here"></a></p> <p>webpack.test.js</p> <pre><code>const helpers = require('./helpers'); /** * Webpack Plugins */ const ProvidePlugin = require('webpack/lib/ProvidePlugin'); const DefinePlugin = require('webpack/lib/DefinePlugin'); /** * Webpack Constants */ const ENV = process.env.ENV = process.env.NODE_ENV = 'test'; /** * Webpack configuration * * See: http://webpack.github.io/docs/configuration.html#cli */ module.exports = { /** * Source map for Karma from the help of karma-sourcemap-loader &amp; karma-webpack * * Do not change, leave as is or it wont work. * See: https://github.com/webpack/karma-webpack#source-maps */ devtool: 'inline-source-map', /** * Options affecting the resolving of modules. * * See: http://webpack.github.io/docs/configuration.html#resolve */ resolve: { /** * An array of extensions that should be used to resolve modules. * * See: http://webpack.github.io/docs/configuration.html#resolve-extensions */ extensions: ['', '.ts', '.js'], /** * Make sure root is src */ root: helpers.root('src'), }, /** * Options affecting the normal modules. * * See: http://webpack.github.io/docs/configuration.html#module */ module: { /** * An array of applied pre and post loaders. * * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders */ preLoaders: [ /** * Tslint loader support for *.ts files * * See: https://github.com/wbuchwalter/tslint-loader */ { test: /\.ts$/, loader: 'tslint-loader', exclude: [helpers.root('node_modules')] }, /** * Source map loader support for *.js files * Extracts SourceMaps for source files that as added as sourceMappingURL comment. * * See: https://github.com/webpack/source-map-loader */ { test: /\.js$/, loader: 'source-map-loader', exclude: [ // these packages have problems with their sourcemaps helpers.root('node_modules/rxjs'), helpers.root('node_modules/@angular') ] } ], /** * An array of automatically applied loaders. * * IMPORTANT: The loaders here are resolved relative to the resource which they are applied to. * This means they are not resolved relative to the configuration file. * * See: http://webpack.github.io/docs/configuration.html#module-loaders */ loaders: [ /** * Typescript loader support for .ts and Angular 2 async routes via .async.ts * * See: https://github.com/s-panferov/awesome-typescript-loader */ { test: /\.ts$/, loader: 'awesome-typescript-loader', query: { compilerOptions: { // Remove TypeScript helpers to be injected // below by DefinePlugin removeComments: true } }, exclude: [/\.e2e\.ts$/] }, /** * Json loader support for *.json files. * * See: https://github.com/webpack/json-loader */ { test: /\.json$/, loader: 'json-loader', exclude: [helpers.root('src/index.html')] }, /** * Raw loader support for *.css files * Returns file content as string * * See: https://github.com/webpack/raw-loader */ { test: /\.css$/, loaders: ['to-string-loader', 'css-loader'], exclude: [helpers.root('src/index.html')] }, /** * Raw loader support for *.html * Returns file content as string * * See: https://github.com/webpack/raw-loader */ { test: /\.html$/, loader: 'raw-loader', exclude: [helpers.root('src/index.html')] } ], /** * An array of applied pre and post loaders. * * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders */ postLoaders: [ /** * Instruments JS files with Istanbul for subsequent code coverage reporting. * Instrument only testing sources. * * See: https://github.com/deepsweet/istanbul-instrumenter-loader */ { test: /\.(js|ts)$/, loader: 'istanbul-instrumenter-loader', include: helpers.root('src'), exclude: [ /\.(e2e|spec)\.ts$/, /node_modules/ ] } ] }, /** * Add additional plugins to the compiler. * * See: http://webpack.github.io/docs/configuration.html#plugins */ plugins: [ /** * Plugin: DefinePlugin * Description: Define free variables. * Useful for having development builds with debug logging or adding global constants. * * Environment helpers * * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin */ // NOTE: when adding more properties make sure you include them in custom-typings.d.ts new DefinePlugin({ 'ENV': JSON.stringify(ENV), 'HMR': false, 'process.env': { 'ENV': JSON.stringify(ENV), 'NODE_ENV': JSON.stringify(ENV), 'HMR': false, } }), ], /** * Static analysis linter for TypeScript advanced options configuration * Description: An extensible linter for the TypeScript language. * * See: https://github.com/wbuchwalter/tslint-loader */ tslint: { emitErrors: false, failOnHint: false, resourcePath: 'src' }, /** * Include polyfills or mocks for various node stuff * Description: Node configuration * * See: https://webpack.github.io/docs/configuration.html#node */ node: { global: 'window', process: false, crypto: 'empty', module: false, clearImmediate: false, setImmediate: false } }; </code></pre> <p>karma.conf.js</p> <pre><code>/** * @author: @AngularClass */ module.exports = function (config) { var testWebpackConfig = require('./webpack.test.js'); var configuration = { // base path that will be used to resolve all patterns (e.g. files, exclude) basePath: '', /* * Frameworks to use * * available frameworks: https://npmjs.org/browse/keyword/karma-adapter */ frameworks: ['jasmine'], // list of files to exclude exclude: [], /* * list of files / patterns to load in the browser * * we are building the test environment in ./spec-bundle.js */ files: [{ pattern: './spec-bundle.js', watched: false }], /* * preprocess matching files before serving them to the browser * available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor */ preprocessors: { './spec-bundle.js': ['coverage', 'webpack', 'sourcemap'] }, // Webpack Config at ./webpack.test.js webpack: testWebpackConfig, coverageReporter: { dir: './../karma_html/coverage/', reporters: [ { type: 'text-summary' }, { type: 'json' }, { type: 'html' } ] }, // Webpack please don't spam the console when running in karma! webpackServer: { noInfo: true }, /* * test results reporter to use * * possible values: 'dots', 'progress' * available reporters: https://npmjs.org/browse/keyword/karma-reporter */ reporters: ['mocha', 'coverage'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, /* * level of logging * possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG */ logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, /* * start these browsers * available browser launchers: https://npmjs.org/browse/keyword/karma-launcher */ browsers: [ 'PhantomJS' ], customLaunchers: { Chrome_travis_ci: { base: 'Chrome', flags: ['--no-sandbox'] } }, /* * Continuous Integration mode * if true, Karma captures browsers, runs the tests and exits */ singleRun: true }; if (process.env.TRAVIS) { configuration.browsers = ['Chrome_travis_ci']; } config.set(configuration); }; </code></pre> <p>spec-bundle.js</p> <pre><code>/** * @author: @AngularClass */ /* * When testing with webpack and ES6, we have to do some extra * things to get testing to work right. Because we are gonna write tests * in ES6 too, we have to compile those as well. That's handled in * karma.conf.js with the karma-webpack plugin. This is the entry * file for webpack test. Just like webpack will create a bundle.js * file for our client, when we run test, it will compile and bundle them * all here! Crazy huh. So we need to do some setup */ Error.stackTraceLimit = Infinity; require('core-js/es6'); require('core-js/es7/reflect'); // Typescript emit helpers polyfill require('ts-helpers'); require('zone.js/dist/zone'); require('zone.js/dist/long-stack-trace-zone'); require('zone.js/dist/jasmine-patch'); require('zone.js/dist/async-test'); require('zone.js/dist/fake-async-test'); require('zone.js/dist/sync-test'); // RxJS require('rxjs/Rx'); var testing = require('@angular/core/testing'); var browser = require('@angular/platform-browser-dynamic/testing'); testing.setBaseTestProviders( browser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, browser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS ); /* * Ok, this is kinda crazy. We can use the the context method on * require that webpack created in order to tell webpack * what files we actually want to require or import. * Below, context will be an function/object with file names as keys. * using that regex we are saying look in ./src/app and ./test then find * any file that ends with spec.js and get its path. By passing in true * we say do this recursively */ var testContext = require.context('../src', true, /\.spec\.ts/); /* * get all the files, for each file, call the context function * that will require the file and load it up here. Context will * loop and require those spec files here */ function requireAll(requireContext) { return requireContext.keys().map(requireContext); } // requires and returns all modules that match var modules = requireAll(testContext); </code></pre>
0
Conditional assignment of tensor values in TensorFlow
<p>I want to replicate the following <code>numpy</code> code in <code>tensorflow</code>. For example, I want to assign a <code>0</code> to all tensor indices that previously had a value of <code>1</code>.</p> <pre><code>a = np.array([1, 2, 3, 1]) a[a==1] = 0 # a should be [0, 2, 3, 0] </code></pre> <p>If I write similar code in <code>tensorflow</code> I get the following error.</p> <pre><code>TypeError: 'Tensor' object does not support item assignment </code></pre> <p>The condition in the square brackets should be arbitrary as in <code>a[a&lt;1] = 0</code>.</p> <p>Is there a way to realize this "conditional assignment" (for lack of a better name) in <code>tensorflow</code>?</p>
0
What's the difference between api key, client id and service account?
<p>I needed to access a Google's service, i.e. Google Analytics, from my Symfony 2 application, so I had to use the Google api client (version 2). Before accessing Google Analytics' info, I had to create either a api key, a client id or a service account in the Google API Console.</p> <p>At the end, I created a service account, and a file was downloaded. This file is used by the Google api client to grant access to my Google Analytics account and its respective collected info.</p> <p>My question are:</p> <ol> <li><p>What are the differences between api key, client id and service account? </p></li> <li><p>When to create/use one over the other, and why?</p></li> </ol> <p>I've not seen any exhaustive article which explains what I'm asking in this question.</p>
0
What is the difference between Expo and React Native?
<p>From <a href="https://expo.io" rel="noreferrer">the Expo website</a></p> <blockquote> <p>Expo lets web developers build truly native apps that work across both iOS and Android by writing them once in just JavaScript.</p> </blockquote> <p>Isn't this what React Native does? What's the difference?</p>
0
Query items user was mentioned in
<p>Is there a way to query work items where a user was mentioned? I am able to receive 'hard-coded' results by querying for</p> <p><strong>"History"-"Contains word"-"\@Username"</strong>,</p> <p>but I want a generic version, which works for all users. (Opposed to writing one query for every user)</p>
0
How to solve TypeError: d3.time is undefined?
<p>I want to parse data/time using D3.js. For that purpose I created one javascript file and use <code>var d3 = require('d3')</code>. I install D3 using <code>npm install d3</code>, and also tried <code>npm install d3 --save</code> which saves it in <code>package.json</code> file : </p> <pre><code>{ "name": "school", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" &amp;&amp; exit 1" }, "author": "", "license": "ISC", "dependencies": { "browserify": "^13.1.0", "bufferutil": "^1.2.1", "d3": "^4.2.2", "express": "^4.14.0", "guid": "0.0.12", "gulp": "^3.9.1", "react": "^15.3.1", "react-dom": "^15.3.1", "reactify": "^1.1.1", "utf-8-validate": "^1.2.1", "vinyl-source-stream": "^1.1.0", "websocket": "^1.0.23", "ws": "^1.1.1" } } </code></pre> <p>However, I'm facing this exception:</p> <pre><code>TypeError: d3.time is undefined </code></pre> <p>program code: </p> <pre><code>'use strict'; var d3 = require("d3"); var latency_arr = []; var time_arr = []; var timeFormat = d3.time.format('%H:%M:%S %L'); module.exports = { histogram: function(data) { console.log(data); return { getBin: function() { var jsonObject = JSON.parse(data); this.time_arr = jsonObject.time; for(var i = 0 ; i &lt; this.time_arr.length ; i++){ temp_time = this.time_arr[i]; this.time_arr[i] = new Date(timeFormat.parse(temp_time)); } return this.time_arr; }, addValue: function(date, value) { return true; }, getValues: function() { if(data !== undefined){ var jsonObject = JSON.parse(data); this.latency_arr = jsonObject.latency; return this.latency_arr; } } }; } }; </code></pre> <p><strong>Checking :</strong> </p> <pre><code>&gt; var d3 = require('d3'); undefined </code></pre> <p>But the d3 module is in node_modules directory.</p> <p>Why didn't it recognize the d3 module? What am I missing? </p>
0
Blur not working - Angular 2
<p>I'm trying to set a blue event in angular 2 like so:</p> <pre><code>&lt;div id="area-button" (blur)="unfocusAreaInput()" class="form-group" (click)="focusAreaInput()"&gt; </code></pre> <p>component.ts:</p> <pre><code>import { Component, ViewChild, ElementRef, Output, EventEmitter } from '@angular/core'; import { GoogleplaceDirective } from 'angular2-google-map-auto-complete/directives/googleplace.directive'; @Component({ selector: 'my-area', directives: [GoogleplaceDirective], templateUrl: 'app/find-page/area-picker.component.html', styleUrls: ['app/find-page/area-picker.component.css'] }) export class AreaComponent { public address: Object; @ViewChild('areaInput') areaInput; areaSelected: boolean = false; @Output() onAreaSelected = new EventEmitter&lt;boolean&gt;(); @Output() onAreaDeselected = new EventEmitter&lt;boolean&gt;(); constructor(el: ElementRef) { } getAddress(place: Object) { this.address = place['formatted_address']; var location = place['geometry']['location']; var lat = location.lat(); var lng = location.lng(); console.log("Address Object", place); } focusAreaInput() { this.areaInput.nativeElement.focus(); this.onAreaSelected.emit(true); } unfocusAreaInput() { this.onAreaSelected.emit(false); } } </code></pre> <p>unfocusAreaInput() never gets executed. Why?</p>
0
Process string templates with thymeleaf 3
<p>Can we use StringTemplateResolver to populate a string template with Icontext. If so how we can do? TemplateProcessingParameters and IResourceResolver is removed from Thymeleaf 3. Any working example would greatly help?</p> <p>I have followed this example and it works great in Thymeleaf 2<br> <a href="https://stackoverflow.com/questions/22830370/is-there-a-way-to-make-spring-thymeleaf-process-a-string-template">Is there a way to make Spring Thymeleaf process a string template?</a></p> <p>I didnt see any reference any migration guide as well.</p>
0
What is Google Cloud API for TTS (Text to Speech)?
<p>In my webapp, I'm trying to call make an HTTP request to a Google API which takes some text (such as "Hello World") and returns a MP3 file with the speech equivalent.</p> <p>I have seen this question: <a href="https://stackoverflow.com/questions/36003969/google-text-to-speech-tts-api-doesnt-seems-to-work">Google text to speech tts api doesn&#39;t seems to work</a>. And this google page: <a href="https://cloud.google.com/translate/docs/" rel="nofollow noreferrer">https://cloud.google.com/translate/docs/</a>. </p> <p>And there are lots of other pages that seem out of date -- it looks like this feature has been removed by google or is under a different rest call?</p> <p>I don't see any documentation (such as in Google Translate API <a href="https://cloud.google.com/translate/" rel="nofollow noreferrer">https://cloud.google.com/translate/</a>) on how to call the google api for TTS. I have a google cloud API account and key.</p> <p>Thanks, Dan</p>
0
connect to Postgresql with SSL
<p>I am attempting to connect to a postgresql database which uses SSL via my c# application. But I'm unable to work out what the correct connection string would be. Is anyone able to help?</p> <pre><code> NpgsqlConnection postgresConn; public PostgreManager() { openConnection(); } private void openConnection() { postgresConn = new NpgsqlConnection("Server=10.153.8.4;Port=5432;Database=au_wa_jpc;User Id=readonly;Password=myPass;"); postgresConn.Open(); } </code></pre> <p>Edit:</p> <p>I have attempted to use <code>Ssl Mode=Require;</code> in the connection string, however it throws the following exception.</p> <p>An unhandled exception of type 'System.IO.IOException' occurred in Npgsql.dll</p> <p>Additional information: TlsClientStream.ClientAlertException: CertificateUnknown: Server certificate was not accepted. Chain status: A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.</p> <p>. The specified hostname was not present in the certificate.</p>
0
Hazelcast, HazelcastSerializationException: Failed to serialize 'com.hazelcast.spi.impl.operationservice.impl.operations.Backup'
<p>I have created custom entry processor for updating map entries by extending <code>AbstractEntryProcessor</code>. When my app is running in a cluster on two instances, and the entry processor is executed I receive following exception: </p> <pre><code>com.hazelcast.nio.serialization.HazelcastSerializationException: Failed to serialize 'com.hazelcast.spi.impl.operationservice.impl.operations.Backup' at com.hazelcast.internal.serialization.impl.SerializationUtil.handleSerializeException(SerializationUtil.java:73) at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toBytes(AbstractSerializationService.java:143) at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toBytes(AbstractSerializationService.java:124) at com.hazelcast.spi.impl.operationservice.impl.OperationServiceImpl.send(OperationServiceImpl.java:406) at com.hazelcast.spi.impl.operationservice.impl.OperationBackupHandler.sendSingleBackup(OperationBackupHandler.java:187) at com.hazelcast.spi.impl.operationservice.impl.OperationBackupHandler.makeBackups(OperationBackupHandler.java:159) at com.hazelcast.spi.impl.operationservice.impl.OperationBackupHandler.backup(OperationBackupHandler.java:78) at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.sendBackup(OperationRunnerImpl.java:270) at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.handleResponse(OperationRunnerImpl.java:253) at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:182) at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:122) at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.run(OperationThread.java:102) Caused by: com.hazelcast.nio.serialization.HazelcastSerializationException: Failed to serialize 'com.hazelcast.map.impl.operation.PartitionWideEntryWithPredicateBackupOperation' at com.hazelcast.internal.serialization.impl.SerializationUtil.handleSerializeException(SerializationUtil.java:73) at com.hazelcast.internal.serialization.impl.AbstractSerializationService.writeObject(AbstractSerializationService.java:201) at com.hazelcast.internal.serialization.impl.ByteArrayObjectDataOutput.writeObject(ByteArrayObjectDataOutput.java:371) at com.hazelcast.spi.impl.operationservice.impl.operations.Backup.writeInternal(Backup.java:222) at com.hazelcast.spi.Operation.writeData(Operation.java:472) at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.write(DataSerializableSerializer.java:161) at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.write(DataSerializableSerializer.java:52) at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.write(StreamSerializerAdapter.java:41) at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toBytes(AbstractSerializationService.java:140) ... 10 common frames omitted Caused by: com.hazelcast.nio.serialization.HazelcastSerializationException: Failed to serialize 'com.hazelcast.map.AbstractEntryProcessor$EntryBackupProcessorImpl' at com.hazelcast.internal.serialization.impl.SerializationUtil.handleSerializeException(SerializationUtil.java:73) at com.hazelcast.internal.serialization.impl.AbstractSerializationService.writeObject(AbstractSerializationService.java:201) at com.hazelcast.internal.serialization.impl.ByteArrayObjectDataOutput.writeObject(ByteArrayObjectDataOutput.java:371) at com.hazelcast.map.impl.operation.PartitionWideEntryBackupOperation.writeInternal(PartitionWideEntryBackupOperation.java:98) at com.hazelcast.map.impl.operation.PartitionWideEntryWithPredicateBackupOperation.writeInternal(PartitionWideEntryWithPredicateBackupOperation.java:51) at com.hazelcast.spi.Operation.writeData(Operation.java:472) at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.write(DataSerializableSerializer.java:161) at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.write(DataSerializableSerializer.java:52) at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.write(StreamSerializerAdapter.java:41) at com.hazelcast.internal.serialization.impl.AbstractSerializationService.writeObject(AbstractSerializationService.java:199) ... 17 common frames omitted Caused by: java.util.ConcurrentModificationException: null at java.util.ArrayList.writeObject(Unknown Source) at sun.reflect.GeneratedMethodAccessor143.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source) at java.io.ObjectOutputStream.writeSerialData(Unknown Source) at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) at java.io.ObjectOutputStream.writeSerialData(Unknown Source) at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.writeObject(Unknown Source) at java.util.ArrayList.writeObject(Unknown Source) at sun.reflect.GeneratedMethodAccessor143.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source) at java.io.ObjectOutputStream.writeSerialData(Unknown Source) at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) at java.io.ObjectOutputStream.writeSerialData(Unknown Source) at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) at java.io.ObjectOutputStream.writeSerialData(Unknown Source) at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.writeObject(Unknown Source) at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.write(JavaDefaultSerializers.java:242) at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.write(StreamSerializerAdapter.java:41) at com.hazelcast.internal.serialization.impl.AbstractSerializationService.writeObject(AbstractSerializationService.java:199) ... 25 common frames omitted </code></pre> <p>My entry processor is look like this: </p> <pre><code>public class HRUpdateRacesWithEntriesProcessor extends AbstractEntryProcessor&lt;HRMeeting.HRMeetingKey, HRMeeting&gt; { private List&lt;HRRace&gt; races; private Date date; public HRUpdateRacesWithEntriesProcessor(List&lt;HRRace&gt; races, Date date) { this.races = races; this.date = date; } @Override public Object process(Map.Entry&lt;HRMeeting.HRMeetingKey, HRMeeting&gt; entry) { HRMeeting meeting = entry.getValue(); races.stream() .filter(race -&gt; entry.getKey().equals(new HRMeeting.HRMeetingKey(race.getMeetingDate(), race.getCourseId()))) .forEach(newRace -&gt; { Optional&lt;HRRace&gt; matchedRace = meeting.getRaces().stream().filter(origin -&gt; origin.getKey().equals(newRace.getKey())).findFirst(); if (newRace.getEntries() != null &amp;&amp; matchedRace.isPresent()) { newRace.setUpdateDate(date); newRace.getEntries().stream() .filter(hrEntry -&gt; matchedRace.get().getEntries().stream().map(el -&gt; el.getKey()) .collect(Collectors.toList()).contains(hrEntry.getKey())) .forEach(hrEntry -&gt; hrEntry.setUpdateDate(date)); matchedRace.get().getEntries().retainAll(newRace.getEntries()); newRace.getEntries().addAll(matchedRace.get().getEntries()); } meeting.getRaces() .removeIf(hrRace -&gt; matchedRace.isPresent() &amp;&amp; matchedRace.get().getKey().equals(hrRace.getKey())); meeting.getRaces().add(newRace); }); entry.setValue(meeting); return null; } } </code></pre> <p>For serialization my entites implements java <code>Serializible</code>. Is is can be reason of the issue? </p> <p>I am using hazelcast-3.8-SNAPSHOT</p> <p>Please, help me to solve it.</p>
0
How to test an app created with Angular CLI ng serve from another device?
<p>I have an app generated with Angular CLI from scratch. CLI version <code>angular-cli: 1.0.0-beta.11-webpack.2</code></p> <p>I am trying to test it from my smartphone but I get <strong>Connection refused</strong>.</p> <p>So, I run <code>ng serve</code> on my laptop and try to access the app:</p> <ul> <li>From laptop, using <code>localhost</code>: Works</li> <li>From laptop, using IP: <strong>Connection refused</strong></li> <li>From smartphone, using IP: <strong>Connection refused</strong></li> </ul> <p>This used to work with the previous, SystemJS version of CLI. I checked that I don't have a firewall running.</p> <p>How could I fix or debug this error?</p> <p>I am using a Mac.</p>
0
DateTime.now in Elixir and Ecto
<p>I want to get the current date-time stamp in Phoenix/Elixir without a third-party library. Or simply, I want something like <code>DateTime.now()</code>. How can I do that?</p>
0
Print out contents of a file using ansible
<p>I want to print out the results of a text file in ansible using cat. This is my code.</p> <pre><code> tasks: - name: This option script: "./getIt.py -s {{ myhostname }} -u {{ myuser }} -p {{ mypass }} &gt;&gt; ./It.txt" shell: cat ./It.txt when: user_option == 'L' </code></pre> <p>This however doesn't work. What am I doing wrong?</p>
0
WebGL: How to correctly blend alpha channel png
<p>I'm pretty new to OpenGL and even newer to WebGL. I'm trying to draw a textured quad with an alpha channel. However I just can't get the blending right.</p> <p>This is the result I'm looking for</p> <p><img src="https://i.stack.imgur.com/TF3Nf.png" alt="This is the result I'm looking for" /></p> <p>And this is what the WebGL result looks like</p> <p><img src="https://i.stack.imgur.com/MAvX6.png" alt="And this is what the WebGL result looks like" /></p> <p>As you can see there is kind of a white outline on the dice edges, where in the original image, there is not.</p> <p>This is how I do my blending in WebGL</p> <pre class="lang-js prettyprint-override"><code>gl.clearColor(0.5, 0.5, 0.5, 1); gl.disable(gl.DEPTH_TEST); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); </code></pre> <p>Here is my fragment shader:</p> <pre class="lang-c prettyprint-override"><code>precision mediump float; varying vec2 vUV; uniform sampler2D texture; void main(void) { vec4 frag = texture2D(texture, vUV); gl_FragColor = frag; } </code></pre> <p>Any idea why this is happening? I'm not creating mipmaps, BTW.</p>
0
Connect JS client with Python server
<p>I'm relatively new to JS and Python, so this is probably a beginners question. I'm trying to send a string from a JS client to Python Server (and then send the string to another Python client).</p> <p>This is my code:</p> <p>JS client:</p> <pre><code> var socket = io.connect('http://127.0.0.1:8484'); socket.send('lalala'); </code></pre> <p>Python server:</p> <pre><code>HOST = '127.0.0.1' PORT = 8484 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(2) #JS conn1, addr1 = s.accept() print 'Connected by', addr1 #PY conn2, addr2 = s.accept() print 'Connected by', addr2 while 1: try: data = conn1.recv(1024) except socket.error: print '' if data: print data.decode('utf-8') conn2.send('data') </code></pre> <p>Python client:</p> <pre><code>def __init__(self): #inicializacion self.comando = '0' self.HOST = '127.0.0.1' self.PORT = 8484 self.cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM) fcntl.fcntl(self.cliente, fcntl.F_SETFL, os.O_NONBLOCK) def activate(self): print "Plugin de envio en marcha." def deactivate(self): print "Plugin de envio off." def __call__(self, sample): self.cliente.connect((self.HOST, self.PORT)) try: self.comando = self.cliente.recv(1024).decode('utf-8') except socket.error, e: self.comando = '0' print "******************" print self.comando print "******************" </code></pre> <p>I have no problem sending a random string from python server to python client, but I can't receive from the JS client. </p> <p>When I run the server and the clients there are no problems with the connection: </p> <pre><code>Connected by ('127.0.0.1', 52602) Connected by ('127.0.0.1', 52603) </code></pre> <p>But, for example, this is what I receive from the JS:</p> <pre><code>GET /socket.io/1/?t=1472322502274 HTTP/1.1 Host: 127.0.0.1:8484 Connection: keep-alive Origin: http://127.0.0.1:8880 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36 Accept: */* Referer: http://127.0.0.1:8880/normal.html Accept-Encoding: gzip, deflate, sdch Accept-Language: es-ES,es;q=0.8 Cookie: io=e7675566ceab4aa1991d55cd72c8075c </code></pre> <p>But I want the string 'lalala'.</p> <p>Any ideas? </p> <p>(And thank you!)</p>
0
File.Copy error - C# - IOException The filename, directory name, or volume label
<p>Trying to copy all files/directories inside a directory to a new location that I create. Users select the 'backup drive' to work with to in a combobox, then when they click the backup desktop button it simply creates a backup directory on that drive and copies all the files into that directory.</p> <p>The backup directory gets created on the drive appropriately - but the first file it hits it kicks off an error.</p> <pre><code>private void backupDesktopButton_Click(object sender, EventArgs e) { //set the destionationLocation to the selectedDrive string selectedDrive = backupDriveCombo.SelectedItem.ToString(); string destinationLocation = selectedDrive+"Backups-" + DateTime.Now.Month.ToString()+"-"+DateTime.Now.Year.ToString()+"\\Desktop\\"; if (!Directory.Exists(destinationLocation)) { Directory.CreateDirectory(destinationLocation); } string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); string[] fileList = Directory.GetFiles(desktopFolder); foreach (string file in fileList) { //move the file File.Copy(file, destinationLocation); } } </code></pre> <p>I get the error:</p> <blockquote> <p><em>IOException was unhandled.</em></p> <p><em>The filename, directory name, or volume label syntax is incorrect.</em></p> </blockquote> <p>In the 'Autos' window (VS2010) I see the locations are set correctly:</p> <p>destinationLocation = the appropriate directory (<em>C:\Backups-8-2016\Desktop\</em>)</p> <p>file = the appropriate first file (<em>C:\Users\myusername\Desktop\myshortcut.url</em>)</p> <p>What am I missing? I have all rights to be able to copy/paste/create things and the directory to store it gets created - just a problem moving the file.</p>
0
What happens when the Kubernetes master fails?
<p>I've been trying to figure out what happens when the Kubernetes master fails in a cluster that only has one master. Do web requests still get routed to pods if this happens, or does the entire system just shut down?</p> <p>According to the OpenShift 3 documentation, which is built on top of Kubernetes, (<a href="https://docs.openshift.com/enterprise/3.2/architecture/infrastructure_components/kubernetes_infrastructure.html" rel="noreferrer">https://docs.openshift.com/enterprise/3.2/architecture/infrastructure_components/kubernetes_infrastructure.html</a>), if a master fails, nodes continue to function properly, but the system looses its ability to manage pods. Is this the same for vanilla Kubernetes?</p>
0
Navigate relative with Angular 2 Router (Version 3)
<p>How to navigate relative from <code>/questions/123/step1</code> to <code>/questions/123/step2</code> within a component using <code>Router</code> without string concatenation and specifying <code>/questions/123/</code>?</p> <p>I've added an own answer below. Please feel free to suggest a better answer. ;-) I guess there are better approaches.</p>
0
Django TextField and CharField is stripping spaces and blank lines
<p>I just researched my "bug" and it turned out to be a new feature in Django 1.9 that CharFields strip spaces by default : <a href="https://docs.djangoproject.com/en/1.9/ref/forms/fields/#django.forms.CharField.strip" rel="noreferrer">https://docs.djangoproject.com/en/1.9/ref/forms/fields/#django.forms.CharField.strip</a></p> <p>The same seams to apply to text fields TextField.</p> <p>So I found out why Django suddenly behaves differently than before, but is there an easy way to restore the previous default for auto generated admin forms?</p> <p>I would like to NOT strip spaces while still using the auto generated form from the admin. Is that still possible?</p>
0
paypal standard checkout redirects to paypal.com/webapps/hermes
<p>we have set the form URL for PayPal standard checkout to <a href="https://www.paypal.com/uk/cgi-bin/webscr" rel="nofollow">https://www.paypal.com/uk/cgi-bin/webscr</a>. When we test it from India, it works fine. All the data passed to PayPal is also displayed over there. But when try the same from UK, it redirects to <a href="https://www.paypal.com/webapps/hermes?token=" rel="nofollow">https://www.paypal.com/webapps/hermes?token=</a>, which is not the URL we set in the form. And the data passed were missing. can you say what can be the issue? </p> <p>i searched a lot for the answer, but didn't get any answer for this.</p> <p>can any suggest a solution for this? any help will be appreciated</p>
0
WKWebView won't open social media login popups
<p>I have a WKWebView in my app. Everything is running smooth except the website I show has the social media logon buttons. The problem is, they display (or try to display) a popup where you allow it to have access to your social media account. I have researched this and tried a few things, but none seem to fit. Here is what I tried:</p> <p>in viewDidLoad, I tried to enable Javascript on the init:</p> <pre><code>WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init]; WKPreferences *thePreferences = [[WKPreferences alloc] init]; thePreferences.javaScriptCanOpenWindowsAutomatically = YES; thePreferences.javaScriptEnabled = YES; theConfiguration.preferences = thePreferences; self.wkWeb = [[WKWebView alloc] initWithFrame:screenRect configuration:theConfiguration]; </code></pre> <p>However, this didn't help me. Then I tried to play with the delegates and go that route. I tried playing around with the createWebViewWithConfiguration method, but that seems like overkill because I had to filter out if they are at the login URL then configure a popup and display it. And then this still wasn't working. I also come in here for the if not main frame logic, cancel the request and reload it in the main view, and that is an easy one-line fix where as this was ballooning into 20+ lines.</p> <p>This seems like a common problem, but I can't seem to find a lot of information out there. Any ideas?</p> <h3>EDIT - Addition</h3> <p>After playing around with Armands answer, I get closer. This is my createWebViewWithConfig method now, which just displays a white screen overlay. It's like I need something to tell the new popup to load the content. Also - I assume I can place this modal window in my current .m file and it doesn't need a completely new file?</p> <pre><code>NSURL *url = navigationAction.request.URL; if(!navigationAction.targetFrame.isMainFrame &amp;&amp; [url.absoluteString rangeOfString:@"initiate_"].location != NSNotFound) { //open new modal webview AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; config.processPool = [appDelegate getSharedPool]; self.popupLogin = [[WKWebView alloc] initWithFrame:self.wkWeb.bounds configuration:config]; self.popupLogin.frame = CGRectMake(self.wkWeb.frame.origin.x, self.wkWeb.frame.origin.y, self.wkWeb.frame.size.width, self.wkWeb.frame.size.height); self.popupLogin.navigationDelegate = self; self.popupLogin.UIDelegate = self; [webView addSubview:self.popupLogin]; [self.popupLogin loadRequest:navigationAction.request]; return nil; } </code></pre>
0
how to globally define the naming convention with Jackson
<p>I'm using Jackson with Spring. I have a few methods like this:</p> <pre><code>@RequestMapping(value = "/myURL", method = RequestMethod.GET) public @ResponseBody Foo getFoo() { // get foo return foo; } </code></pre> <p>The class Foo that's serialized is quite big and has many members. The serialization is ok, using annotation or custom serializer.</p> <p>The only thing I can't figure out is how to define the naming convention. I would like to use snake_case for all the serializations.</p> <p>So how do I define <strong>globally</strong> the naming convention for the serialization?</p> <p>If it's not possible, then a local solution will have to do then.</p>
0
Formatting output of CSV file in Python
<p>I am creating a very rudimentary "Address Book" program in Python. I am grabbing contact data from a CSV file, the contents of which looks like the following example:</p> <pre><code>Name,Phone,Company,Email Elon Musk,454-6723,SpaceX,[email protected] Larry Page,853-0653,Google,[email protected] Tim Cook,133-0419,Apple,[email protected] Steve Ballmer,456-7893,Developers!,[email protected] </code></pre> <p>I am trying to format the output so that it looks cleaner and more readable, i.e. everything lined up in rows and columns, like this:</p> <pre><code>Name: Phone: Company: Email: Elon Musk 454-6723 SpaceX [email protected] </code></pre> <p>My current code is as follows:</p> <pre><code>f = open("contactlist.csv") csv_f = csv.reader(f) for row in csv_f: print(row) </code></pre> <p>Which naturally due to lack of formatting, produces this, which still looks very unclean.</p> <pre><code>['Name', 'Phone', 'Company', 'Email'] ['Elon Musk', '454-6723', 'SpaceX', '[email protected]'] ['Larry Page', '853-0653', 'Google', '[email protected]'] ['Tim Cook', '133-0419', 'Apple', '[email protected]'] ['Steve Ballmer', '456-7893', 'Developers!', '[email protected]'] </code></pre> <p>Any tips on how to produce a cleaner output would be greatly appreciated, as I am beginner and I find all of this quite confusing. Many thanks in advance.</p>
0
Espresso can't find a view: NoMatchingViewException
<p>In my app,I have two fragments attached in an activity. Each fragment contains different views.</p> <p>The first one has two edit text fields and two buttons,where the user can login or register. So now I want to apply some Espresso testing. </p> <pre><code>@RunWith(AndroidJUnit4.class) public class LoginTest { @Rule public final ActivityRule&lt;MainActivity&gt; main = new ActivityRule&lt;&gt; (MainActivity.class); @Test public void shouldBeAbleToFindViewsOfLoginScreen(){ onView(withText(R.id.user_name)).perform(click()); } } </code></pre> <p>However the test complains that it can not find the view with the id of R.id.user_name.</p> <pre><code>android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with string from resource id: &lt;2131493050&gt;[user_name] value: false </code></pre> <p>I use the corrent id as I checked from the uiautomatorviewer as well.</p> <p>The xml code for this fragment is</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/fragmentLogin" tools:context="team.football.ael.MainActivity" android:background="@drawable/background"&gt; &lt;include android:id="@+id/toolbar" layout="@layout/tool_lay" /&gt; &lt;LinearLayout android:padding="20dp" android:background="@drawable/roundedlayout" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_width="wrap_content" android:orientation="vertical" android:layout_height="wrap_content"&gt; &lt;ImageView android:src="@mipmap/ael_logo" android:layout_width="60dp" android:layout_height="60dp" android:layout_gravity="center_horizontal" /&gt; &lt;android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp"&gt; &lt;EditText android:id="@+id/user_name" android:hint="@string/login_username" android:textColor="#fff" android:textColorHint="#fff" android:layout_width="250dp" android:layout_height="wrap_content" /&gt; &lt;/android.support.design.widget.TextInputLayout&gt; &lt;android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp"&gt; &lt;EditText android:id="@+id/user_pass" android:textColorHint="#fff" android:layout_width="250dp" android:layout_height="wrap_content" android:inputType="textPassword" android:layout_marginTop="20dp" android:hint="κωδικός" android:textColor="#fff" /&gt; &lt;/android.support.design.widget.TextInputLayout&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;Button android:id="@+id/loginButton" android:layout_gravity="center_horizontal" android:text="Εισοδος" android:layout_marginTop="20dp" android:layout_width="0dp" android:layout_weight="1" android:textColor="#fff" android:background="@drawable/roundbutton" android:layout_height="wrap_content" android:onClick="userLogin"/&gt; &lt;Button android:layout_marginTop="20dp" android:layout_gravity="center_horizontal" android:text="Εγγραφη" android:textColor="#fff" android:layout_width="0dp" android:layout_marginLeft="10dp" android:background="@drawable/roundbutton" android:onClick="userReg" android:layout_weight="1" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; &lt;TextView android:textStyle="bold|italic" android:textSize="25sp" android:layout_gravity="center_horizontal" android:text="Ξέχασες τον κωδικό σου?" android:id="@+id/forgotPass" android:textColor="#fff" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; </code></pre> <p></p> <p>Any ideas?</p> <p>Thanks.</p>
0
ImportError: No module named 'cryptography'
<p>I installed python 3.4 on windows 7 and when trying to use paramiko I get this error :</p> <pre><code>import paramiko File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\__init__.py", line 30, in module File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\transport.py", line 32, in module ImportError: No module named 'cryptography' </code></pre> <p>I installed pycrypto-2.6.1.win but the problem persist. Any help ?</p>
0
What is the difference of saveArg and saveArgPointee in gmock?
<p>I am studying in the gmock. Now Im trying to mock the class named "task", like this:</p> <pre><code>class MockTask : public Task { public: MOCK_METHOD3(Execute, bool(std::set&lt;std::string&gt; &amp;setDeviceIDs, int timeout, PACKET_DATA *Data)); }; </code></pre> <p>And I want to save the struct pdata when the task.excute is called, so that I can validate the pdata->member. This is my code:</p> <pre><code>PAKET_DATA data; EXPECT_CALL(task, Execute(testing::_, testing::_, testing::_)) .WillOnce(testing::saveArg&lt;2&gt;(&amp;data)); ASSERT_EQ(data-&gt;resultcode, 0); </code></pre> <p>Is that correct? And what is the difference of saveArg and saveArgPointee?</p>
0
How do I mount a volume in a docker container in .gitlab-ci.yml?
<p>I'm using <code>.gitlab-ci.yml</code> and docker as a GitLab CI runner on an Android project. At the end of the test run, <code>gradlew</code> saves test results in xml and html under the build directory:</p> <pre><code>Finished generating test XML results (0.001 secs) into: /builds/org/project/sdk/build/test-results/release Generating HTML test report... Finished generating test html results (0.002 secs) into: /builds/org/project/sdk/build/reports/tests/release </code></pre> <p>I'd like to have access to these files, but the <a href="http://docs.gitlab.com/ce/ci/docker/using_docker_images.html" rel="noreferrer">documentation</a> doesn't mention how to mount a volume like one would with <code>docker run -v &lt;path&gt;:/builds/org/...</code>.</p>
0
How to center the images in the Owl Carousel
<p>My Owl Carousel contains pictures of different width and height. How do I align them in the middle - both horizontally and vertically?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$("#owl-example").owlCarousel({ navigation: true });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.css"&gt; &lt;link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.theme.min.css"&gt; &lt;div id="owl-example" class="owl-carousel"&gt; &lt;div&gt;&lt;img src="https://via.placeholder.com/120x120/69c/fff/" alt=""&gt;&lt;/div&gt; &lt;div&gt;&lt;img src="https://via.placeholder.com/200x200/c69/fff/" alt=""&gt;&lt;/div&gt; &lt;div&gt;&lt;img src="https://via.placeholder.com/160x160/9c6/fff/" alt=""&gt;&lt;/div&gt; &lt;div&gt;&lt;img src="https://via.placeholder.com/240x240/fc6/fff/" alt=""&gt;&lt;/div&gt; &lt;div&gt;&lt;img src="https://via.placeholder.com/160x160/9c6/fff/" alt=""&gt;&lt;/div&gt; &lt;div&gt;&lt;img src="https://via.placeholder.com/200x200/c69/fff/" alt=""&gt;&lt;/div&gt; &lt;div&gt;&lt;img src="https://via.placeholder.com/120x120/69c/fff/" alt=""&gt;&lt;/div&gt; &lt;/div&gt; &lt;script src="//code.jquery.com/jquery-1.12.4.min.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
0
java.lang.IllegalArgumentException: Unknown parameter name : customer
<p>I'm trying to use the <code>getNamedQuery</code> method to create a List, but I'm getting this exception.</p> <p>Here is my code</p> <pre><code>public List&lt;Equip&gt; getEquipsByCustomer(int customer) { return (List&lt;Equip&gt;) sessionFactory.getCurrentSession() .getNamedQuery("getEquipsByCustomer") .setParameter("customer", customer) .list(); } </code></pre> <p>And the query in the xml file</p> <pre><code>&lt;sql-query name="getEquipsByCustomer"&gt; &lt;return class="Equip" alias="equip"/&gt; &lt;query-param name="customer" type="int"/&gt; SELECT e.* FROM request r INNER JOIN equip e ON r.equip_id = e.equip_id INNER JOIN customer c ON r.customer_id = c.customer_id WHERE c.customer_id = :customer; &lt;/sql-query&gt; </code></pre> <p>I'm using another <code>getNamedQuery</code> methods but only this is getting the exception and I can't find what I'm doing wrong. Is there anything I'm missing?</p> <p>the full exception</p> <pre><code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Unknown parameter name : customer org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:980) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859) javax.servlet.http.HttpServlet.service(HttpServlet.java:622) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:112) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:206) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:106) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) java.lang.IllegalArgumentException: Unknown parameter name : customer org.hibernate.query.internal.QueryParameterBindingsImpl.getBinding(QueryParameterBindingsImpl.java:193) org.hibernate.query.internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:474) org.hibernate.query.internal.NativeQueryImpl.setParameter(NativeQueryImpl.java:571) org.hibernate.query.internal.NativeQueryImpl.setParameter(NativeQueryImpl.java:51) com.cclip.core.equip.EquipRepositoryImpl.getEquipsByCustomer(EquipRepositoryImpl.java:18) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) java.lang.reflect.Method.invoke(Unknown Source) org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302) org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) com.sun.proxy.$Proxy44.getEquipsByCustomer(Unknown Source) com.cclip.core.equip.EquipServiceImpl.findEquipsByCustomer(EquipServiceImpl.java:37) com.cclip.mvc.controllers.HomeController.helloWorld(HomeController.java:67) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) java.lang.reflect.Method.invoke(Unknown Source) org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859) javax.servlet.http.HttpServlet.service(HttpServlet.java:622) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:112) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:206) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:106) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) </code></pre>
0
Use schema to convert AVRO messages with Spark to DataFrame
<p>Is there a way to use a schema to convert <a href="/questions/tagged/avro" class="post-tag" title="show questions tagged &#39;avro&#39;" rel="tag">avro</a> messages from <a href="/questions/tagged/kafka" class="post-tag" title="show questions tagged &#39;kafka&#39;" rel="tag">kafka</a> with <a href="/questions/tagged/spark" class="post-tag" title="show questions tagged &#39;spark&#39;" rel="tag">spark</a> to <a href="/questions/tagged/dataframe" class="post-tag" title="show questions tagged &#39;dataframe&#39;" rel="tag">dataframe</a>? The schema file for user records:</p> <pre><code>{ "fields": [ { "name": "firstName", "type": "string" }, { "name": "lastName", "type": "string" } ], "name": "user", "type": "record" } </code></pre> <p>And code snippets from <a href="https://github.com/apache/spark/blob/master/examples/src/main/scala/org/apache/spark/examples/streaming/SqlNetworkWordCount.scala" rel="noreferrer">SqlNetworkWordCount example</a> and <a href="http://aseigneurin.github.io/2016/03/04/kafka-spark-avro-producing-and-consuming-avro-messages.html" rel="noreferrer">Kafka, Spark and Avro - Part 3, Producing and consuming Avro messages</a> to read in messages. </p> <pre class="lang-scala prettyprint-override"><code>object Injection { val parser = new Schema.Parser() val schema = parser.parse(getClass.getResourceAsStream("/user_schema.json")) val injection: Injection[GenericRecord, Array[Byte]] = GenericAvroCodecs.toBinary(schema) } ... messages.foreachRDD((rdd: RDD[(String, Array[Byte])]) =&gt; { val sqlContext = SQLContextSingleton.getInstance(rdd.sparkContext) import sqlContext.implicits._ val df = rdd.map(message =&gt; Injection.injection.invert(message._2).get) .map(record =&gt; User(record.get("firstName").toString, records.get("lastName").toString)).toDF() df.show() }) case class User(firstName: String, lastName: String) </code></pre> <p>Somehow I can't find another way than using a case class to convert AVRO messages to DataFrame. Is there a possibility to use the schema instead? I'm using <code>Spark 1.6.2</code> and <code>Kafka 0.10</code>.</p> <p>The complete code, in case you're interested.</p> <pre class="lang-scala prettyprint-override"><code>import com.twitter.bijection.Injection import com.twitter.bijection.avro.GenericAvroCodecs import kafka.serializer.{DefaultDecoder, StringDecoder} import org.apache.avro.Schema import org.apache.avro.generic.GenericRecord import org.apache.spark.rdd.RDD import org.apache.spark.sql.SQLContext import org.apache.spark.streaming.kafka._ import org.apache.spark.streaming.{Seconds, StreamingContext, Time} import org.apache.spark.{SparkConf, SparkContext} object ReadMessagesFromKafka { object Injection { val parser = new Schema.Parser() val schema = parser.parse(getClass.getResourceAsStream("/user_schema.json")) val injection: Injection[GenericRecord, Array[Byte]] = GenericAvroCodecs.toBinary(schema) } def main(args: Array[String]) { val brokers = "127.0.0.1:9092" val topics = "test" // Create context with 2 second batch interval val sparkConf = new SparkConf().setAppName("ReadMessagesFromKafka").setMaster("local[*]") val ssc = new StreamingContext(sparkConf, Seconds(2)) // Create direct kafka stream with brokers and topics val topicsSet = topics.split(",").toSet val kafkaParams = Map[String, String]("metadata.broker.list" -&gt; brokers) val messages = KafkaUtils.createDirectStream[String, Array[Byte], StringDecoder, DefaultDecoder]( ssc, kafkaParams, topicsSet) messages.foreachRDD((rdd: RDD[(String, Array[Byte])]) =&gt; { val sqlContext = SQLContextSingleton.getInstance(rdd.sparkContext) import sqlContext.implicits._ val df = rdd.map(message =&gt; Injection.injection.invert(message._2).get) .map(record =&gt; User(record.get("firstName").toString, records.get("lastName").toString)).toDF() df.show() }) // Start the computation ssc.start() ssc.awaitTermination() } } /** Case class for converting RDD to DataFrame */ case class User(firstName: String, lastName: String) /** Lazily instantiated singleton instance of SQLContext */ object SQLContextSingleton { @transient private var instance: SQLContext = _ def getInstance(sparkContext: SparkContext): SQLContext = { if (instance == null) { instance = new SQLContext(sparkContext) } instance } } </code></pre>
0
R and Python in one Jupyter notebook
<p>Is it possible to run R and Python code in the same Jupyter notebook. What are all the alternatives available?</p> <ol> <li>Install r-essentials and create R notebooks in Jupyter.</li> <li>Install rpy2 and use rmagic functions.</li> <li>Use a beaker notebook.</li> </ol> <p>Which of above 3 options is reliable to run Python and R code snippets (sharing variables and visualizations) or is there a better option already?</p>
0
linux shell, sort column 1 in ascending order column 3 in descending order
<p>my file contains 3 columns numbers, like 5 lines data below,</p> <pre><code>1 811036 395 2 811036 195 1 811036 295 2 811036 95 1 811036 95 </code></pre> <p>I want to sort 1 column in ascending order and column 3 in descending order, </p> <pre><code>1 811036 395 1 811036 295 1 811036 95 2 811036 195 2 811036 95 </code></pre> <p>I tried "<strong>sort -n -k 1 -n -k 3</strong>" but failed. how to write a single Linux shell command to accomplish this ?</p>
0
FCM - Setting badge in onMessageReceived
<p>I have an Android application, where I'm using some method to show notification number on app icon. Now I want to set that number when notification is received.</p> <p>I thought that I should set the number when notification received so I set it inside <code>onMessageReceived</code> method. But, my problem is <strong>when my app is in background, <code>onMessageReceived</code> method not called, so the notification number isn't set.</strong></p> <p>Following is my code. I set the number inside <code>onMessageReceived</code>. I already tested <code>setBadge</code> method and can verify that it is working. The problem is <code>onMessageReceived</code> is not called so <code>setBadge</code> is also not called, which doesn't set the number.</p> <pre><code>@Override public void onMessageReceived(RemoteMessage remoteMessage) { // TODO(developer): Handle FCM messages here. Log.d(TAG, "From: " + remoteMessage.getFrom()); Conts.notificationCounter ++; //I am setting in here. setBadge(getApplicationContext(),Conts.notificationCounter ); Log.e("notificationNUmber",":"+ Conts.notificationCounter); // Check if message contains a data payload. if (remoteMessage.getData().size() &gt; 0) { Log.d(TAG, "Message data payload: " + remoteMessage.getData()); } // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. } // [END receive_message] public static void setBadge(Context context, int count) { String launcherClassName = getLauncherClassName(context); if (launcherClassName == null) { Log.e("classname","null"); return; } Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE"); intent.putExtra("badge_count", count); intent.putExtra("badge_count_package_name", context.getPackageName()); intent.putExtra("badge_count_class_name", launcherClassName); context.sendBroadcast(intent); } public static String getLauncherClassName(Context context) { PackageManager pm = context.getPackageManager(); Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); List&lt;ResolveInfo&gt; resolveInfos = pm.queryIntentActivities(intent, 0); for (ResolveInfo resolveInfo : resolveInfos) { String pkgName = resolveInfo.activityInfo.applicationInfo.packageName; if (pkgName.equalsIgnoreCase(context.getPackageName())) { String className = resolveInfo.activityInfo.name; return className; } } return null; } </code></pre> <p>When I searched this <a href="https://stackoverflow.com/questions/37711082/how-to-handle-notification-when-app-in-background-in-firebase/37845174">issue</a>, I found that if the coming message is <em>display message</em> then <code>onMessageReceived</code> is called only if app is foreground. But if coming message is <em>data message</em> then <code>onMessageReceived</code> is called even if the app is background.</p> <p>But my friend told me who is sending the notification(server side), the message already goes as both display and data message. He said that data object is filled.</p> <p>Following is the <strong>JSON</strong> for <strong>coming message</strong>, it has <strong>data object</strong>.</p> <pre><code>{ "to":"my_device_id", "priority":"high", "notification":{ "body":"Notification Body", "title":"Notification Title", "icon":"myicon", "sound":"default" }, "data":{ "Nick":"DataNick", "Room":"DataRoom" } } </code></pre> <p>If I only use data object, onMessageReceived is called as they said but that time notification does not appear at the top.</p> <p>Now why <code>onMessageReceived</code> is not called if the message is also data message. Should I do something different to handle data message? Is it working same with display messaging in client side. </p> <p>Any help would be appreciated. Thanks in advance.</p>
0
How to resolve java.lang.VerifyError: JVMVRFY012 stack shape inconsistent; class=com/sun/xml/messaging/saaj/soap/SOAPDocumentImpl
<p>I am getting the below error when calling SOAP based webservice from SOAP client. This WebService is deployed in Websphere 8.5.0 with IBM JDK 7.0. however i am able to successfully call and get the response from the same WebService, when i deploy the same ear in WAS with IBM JDK 6.0.Any inputs on how to resolve this issue would be much appreciated.</p> <blockquote> <p>java.lang.VerifyError: JVMVRFY012 stack shape inconsistent; class=com/sun/xml/messaging/saaj/soap/SOAPDocumentImpl, method=createDocumentFragment()Lorg/w3c/dom/DocumentFragment;, pc=5 at java.lang.J9VMInternals.verifyImpl(Native Method) at java.lang.J9VMInternals.verify(J9VMInternals.java:94) at java.lang.J9VMInternals.initialize(J9VMInternals.java:169) at com.sun.xml.messaging.saaj.soap.SOAPPartImpl.(SOAPPartImpl.java:106) at com.sun.xml.messaging.saaj.soap.ver1_2.SOAPPart1_2Impl.(SOAPPart1_2Impl.java:69) at com.sun.xml.messaging.saaj.soap.ver1_2.Message1_2Impl.getSOAPPart(Message1_2Impl.java:89) at com.sun.xml.messaging.saaj.soap.MessageImpl.initCharsetProperty(MessageImpl.java:1491) at com.sun.xml.messaging.saaj.soap.MessageImpl.init(MessageImpl.java:552) ... 47 more</p> </blockquote>
0
Angular 2: How to make an option in a select to selected based on a condition?
<p>I'm building a select element in a form from an array of objects. I want one of the options to be selected based on an attribute of the current object (<code>myobject.is_default</code>).</p> <p>The basic template code looks like this:</p> <pre><code>&lt;select formControlName="template"&gt; &lt;option *ngFor="let t of templates" [value]="t.id"&gt;{{t.title}}&lt;/option&gt; &lt;/select&gt; </code></pre> <p>I could now set the select option like this:</p> <pre><code>&lt;select formControlName="template"&gt; &lt;option *ngFor="let t of templates" [value]="t.id" [selected]="t.is_default ? 'selected' : ''"&gt;{{t.title}}&lt;/option&gt; &lt;/select&gt; </code></pre> <p>But the problem I'm having is the HTML5 specs which state:</p> <blockquote> <p>The selected attribute is a boolean attribute.</p> <p><a href="http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes" rel="nofollow">http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes</a> :</p> <p>The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.</p> <p>If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.</p> </blockquote> <p>The following are valid, equivalent and true:</p> <pre><code>&lt;option selected /&gt; &lt;option selected="" /&gt; &lt;option selected="selected" /&gt; &lt;option selected="SeLeCtEd" /&gt; </code></pre> <p>The following are invalid:</p> <pre><code>&lt;option selected="0" /&gt; &lt;option selected="1" /&gt; &lt;option selected="false" /&gt; &lt;option selected="true" /&gt; </code></pre> <p>That means: As soon as the selected attribute is present, the option is selected. So I need a way of not having the <code>selected</code> in all but one option.</p> <p>I cannot use <code>ngIf</code> since it cannot be used together with <code>ngFor</code> on the same element.</p>
0
Failed at chromedriver installation
<p>I'm going to install slamdata on debian Jessie, as described <a href="http://docs.slamdata.com/en/v3.0/administration-guide.html#section-1-installation" rel="nofollow">here</a>, but I failed at npm install section and it wanted to install chromedriver. I even tried a mirror of chromedriver. Here is logs.</p> <pre><code>exec@mob-db1:/opt/slamdata$ npm install </code></pre> <blockquote> <p>npm WARN deprecated [email protected]: this package has been reintegrated into npm and is now out of date with respect to npm</p> <p>[email protected] install /opt/slamdata/node_modules/chromedriver node install.js</p> <p>Downloading <a href="http://chromedriver.storage.googleapis.com/2.23/chromedriver_linux64.zip" rel="nofollow">http://chromedriver.storage.googleapis.com/2.23/chromedriver_linux64.zip</a> Saving to /tmp/chromedriver/chromedriver_linux64.zip Receiving... ChromeDriver installation failed undefined</p> <p>npm WARN optional Skipping failed optional dependency /chokidar/fsevents:</p> <p>npm WARN notsup Not compatible with your operating system or architecture: [email protected]</p> <p>npm ERR! Linux 4.2.8-1-pve</p> <p>npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install"</p> <p>npm ERR! node v6.4.0</p> <p>npm ERR! npm v3.10.6</p> <p>npm ERR! code ELIFECYCLE</p> <p>npm ERR! [email protected] install: node install.js</p> <p>npm ERR! Exit status 1</p> <p>npm ERR! </p> <p>npm ERR! Failed at the [email protected] install script node install.js.</p> <p>npm ERR! Make sure you have the latest version of node.js and npm installed.</p> <p>npm ERR! If you do, this is most likely a problem with the chromedriver package,</p> <p>npm ERR! not with npm itself.</p> <p>npm ERR! Tell the author that this fails on your system:</p> <p>npm ERR! node install.js</p> <p>npm ERR! You can get information on how to open an issue for this project with:</p> <p>npm ERR! npm bugs chromedriver</p> <p>npm ERR! Or if that isn't available, you can get their info via:</p> <p>npm ERR! npm owner ls chromedriver</p> <p>npm ERR! There is likely additional logging output above.</p> <p>npm ERR! Please include the following file with any support request:</p> <p>npm ERR! /opt/slamdata/npm-debug.log</p> </blockquote> <pre><code>exec@mob-db1:/opt/slamdata$ npm install chromedriver --chromedriver_cdnurl=http://npm.taobao.org/mirrors/chromedriver </code></pre> <blockquote> <p>npm WARN deprecated [email protected]: this package has been reintegrated into npm and is now out of date with respect to npm</p> <p>[email protected] install /opt/slamdata/node_modules/chromedriver node install.js</p> <p>Downloading <a href="http://npm.taobao.org/mirrors/chromedriver/2.23/chromedriver_linux64.zip" rel="nofollow">http://npm.taobao.org/mirrors/chromedriver/2.23/chromedriver_linux64.zip</a> Saving to /tmp/chromedriver/chromedriver_linux64.zip Receiving... ChromeDriver installation failed undefined npm WARN optional Skipping failed optional dependency /chokidar/fsevents: npm WARN notsup Not compatible with your operating system or architecture: [email protected]</p> <p>npm ERR! Linux 4.2.8-1-pve</p> <p>npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "chromedriver" "--chromedriver_cdnurl=<a href="http://npm.taobao.org/mirrors/chromedriver" rel="nofollow">http://npm.taobao.org/mirrors/chromedriver</a>"</p> <p>npm ERR! node v6.4.0</p> <p>npm ERR! npm v3.10.6</p> <p>npm ERR! code ELIFECYCLE</p> <p>npm ERR! [email protected] install: node install.js</p> <p>npm ERR! Exit status 1</p> <p>npm ERR! </p> <p>npm ERR! Failed at the [email protected] install script 'node install.js'.</p> <p>npm ERR! Make sure you have the latest version of node.js and npm installed.</p> <p>npm ERR! If you do, this is most likely a problem with the chromedriver package,</p> <p>npm ERR! not with npm itself.</p> <p>npm ERR! Tell the author that this fails on your system:</p> <p>npm ERR! node install.js</p> <p>npm ERR! You can get information on how to open an issue for this project with:</p> <p>npm ERR! npm bugs chromedriver</p> <p>npm ERR! Or if that isn't available, you can get their info via:</p> <p>npm ERR! npm owner ls chromedriver</p> <p>npm ERR! There is likely additional logging output above.</p> <p>npm ERR! Please include the following file with any support request:</p> <p>npm ERR! /opt/slamdata/npm-debug.log</p> </blockquote>
0
Docker: Are Docker links deprecated?
<p>When reading about linking containers together they now call it <em>legacy links</em> e.g. <a href="https://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/" rel="noreferrer">here</a>.</p> <p><a href="https://www.rethinkdb.com/blog/docker-networking/" rel="noreferrer">This article</a> claims <code>links</code> got deprecated in Docker 1.9, but the <a href="https://docs.docker.com/v1.9/engine/misc/deprecated/" rel="noreferrer">release notes</a> doesn't mention this and the <a href="https://docs.docker.com/engine/deprecated/" rel="noreferrer">list of deprecated features</a> doesn't mention it either.</p> <p><strong>Question</strong></p> <p>Why does Docker now call <code>links</code> for legacy links? And should I stop use them?</p>
0
Date.now().toISOString() throwing error "not a function"
<p>I am running Node v6.4.0 on Windows 10. In one of my Javascript files I am trying to get an ISO date string from the Date object:</p> <pre><code>let timestamp = Date.now().toISOString(); </code></pre> <p>This throws: Date.now(...).toISOString is not a function</p> <p>Looking through stackoverflow this should work...possible bug in Node?</p>
0
How to specify all ports in Security group - CloudFormation
<p>I have my CloudFormation script like this now:</p> <pre><code> "SecurityGroupIngress" : [{ "IpProtocol" : "tcp", "FromPort" : "0", "ToPort" : "65535", "CidrIp" : "0.0.0.0/0" }] </code></pre> <p>and it looks like this, which is fine:</p> <p><a href="https://i.stack.imgur.com/MsgKJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MsgKJ.png" alt="enter image description here"></a></p> <p>But I am wondering how to I update the template to get this:</p> <p><a href="https://i.stack.imgur.com/r0rYA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/r0rYA.png" alt="enter image description here"></a></p> <p>Notice the Ports say All. I also wonder if they are different?</p>
0
How to Create or Update a record with GORM?
<p>Gorm has a <code>FirstOrCreate</code> method and a <code>FirstOrInit</code> but how to check afterwards if the record was actually created? I like to create a record if it does not exists and if it exists I want to update some fields.</p>
0
Google.Protobuff timestamp.proto in c#
<p>I have successfully compiled my .proto file with google.proto.Timestamp and generated the .cs file with protoc. The only problem i am having is initialization in my c# code.</p> <p>I have tried the following: </p> <p><strong>.proto File</strong></p> <pre><code>message teststamp { string Name = 1 ; string address = 2; google.protobuf.Timestamp _timeStamp = 3; } </code></pre> <p><strong>C# File</strong></p> <pre><code>teststamp test = new teststamp(); test.Name = "Test"; test.address = "Test_Test_TEST" //Example 2 : POSIX test._timeStamp.Seconds = DateTime.Now.Second; test._timeStamp.Nanos = DateTime.Now.Second*1000 ; </code></pre> <p>The above is compiling without errors but giving me this error: <code>Object reference not set to an instance of an object</code> .I have tried few other approaches but due to less help it is unable to fix the error. </p> <p>Please help me out in this issue</p> <p>Thanks</p>
0
how to use ahead-of-time compiler with angular cli webpack
<p>is there a way to use AOT with angular cli?</p> <p>I've installed the modules (@angular/compiler @angular/compiler-cli) and when I type ngc -p scr it creates the ngFactory.ts files and compiles it to dist/tsc-out (angular cli default in tsconfig)</p> <p>not sure how to proceed from here :)</p> <p>Cheers</p> <p>Han</p>
0
ERR_CONNECTION_RESET when trying to access localhost on ASP.NET Web App project
<p>So I've been working on this webapp project in my desktop computer, but I had to transfer it to my laptop since I have gone on holiday. The code builds fine, but when I try to access the site (<a href="http://localhost:port" rel="noreferrer">http://localhost:port</a>) in Chrome I get an ERR_CONNECTION_RESET message. I've also tried with other browsers (<em>Firefox, Microsoft Edge, Opera</em>) and I get a similar message. I also created a New Project and tried to run it with the same result. IIS Express seems to run without problems. I tried running <code>netstat -ao</code> in the cmd to see if the port assigned to the URL was being used by something else. And it was being actually used by a process with the PID:4, which turned out to be <em>NT Kernel &amp; System</em>.</p> <p><strong>Things I've tried:</strong></p> <ul> <li>Self signing a certificate.</li> <li>Writing 127.0.0.1 in the URL instead of localhost</li> <li>Reinstalling IIS</li> <li>Deleting the config files to make IIS create new ones</li> <li>Modifying the <code>&lt;binding protocol="http" bindingInformation="*:port:localhost"/&gt;</code> removing the <code>localhost</code> part, leaving it like this: <code>&lt;binding protocol="http" bindingInformation="*:port:" /&gt;</code></li> <li>Changing the port in Project Properties => Web, doesn't matter which one I pick, PID:4 always uses it.</li> <li>Opening <code>RegEdit</code> and setting <code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP</code>'s <code>start</code> attribute from 3 to 4, presumably stopping HTTP from listening to ports. Once I did this and rebooted the PC, I tried to run the dummy project again (the one which was only the template), and this time I got an <code>unable to launch the iis express web server</code>. I tried to work around it by reinstalling IIS and modifying the config, but it didn't work. At last, I decided to leave the 'start' attribute with value 3, and return to the <code>ERR_CONNECTION_RESET</code> since I wasn't sure it had been a step forwards or backwards.</li> </ul>
0
Can pandas read a transposed CSV?
<p>Can <code>pandas</code> read a transposed CSV? Here's the file (note I'd also like to select a subset of columns):</p> <pre><code>A,x,x,x,x,1,2,3 B,x,x,x,x,4,5,6 C,x,x,x,x,7,8,9 </code></pre> <p>Would like to get this DataFrame:</p> <pre><code> A B C 0 1 4 7 1 2 5 8 2 3 6 9 </code></pre>
0
'You have a usable connection already' error in Visual Studio 2015 adding Data Source
<p>Visual Studio 2015; Windows 10;</p> <p>In the Data Source Configuration Wizard, trying to add a table from a MySQL install on the network. I get up to this step</p> <p><a href="https://i.stack.imgur.com/ATm70.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ATm70.png" alt="enter image description here"></a></p> <p>When I click 'Finish', I then get this error message:</p> <p><a href="https://i.stack.imgur.com/E8sve.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E8sve.png" alt="enter image description here"></a></p> <p>Other SO posts refer to this issue, none are resolved. This is a fresh WinForms project, there is no code written.</p>
0
Postgresql - Check if a given string starts with any element of the array of strings
<p>Given two strings we can do:</p> <pre><code>select 'aaa123' ilike 'aaa'||'%' </code></pre> <p>The result will be TRUE. I would like to do the same thing with a string and an array - if the given string starts with any of the elements of the array of strings than the result would show TRUE.</p> <p>For example (array and string):</p> <pre><code>select array['aaa123'::text,'bbb123'::text] as text_array select 'aaa12345' as string </code></pre> <p>I would like to do something like this:</p> <pre><code>select string ilike ANY(text_array || '%') </code></pre> <p>And I would expect TRUE since aaa12345 starts with aaa123 (element of the array).</p> <p>Thanks a lot for the help!</p>
0
GET request parameters with koa-router
<p><a href="http://localhost:3000/endpoint?id=83" rel="noreferrer">http://localhost:3000/endpoint?id=83</a> results in 404 (Not Found). All other routes work as expected. Am I missing something here?</p> <pre><code>router .get('/', function *(next) { yield this.render('index.ejs', { title: 'title set on the server' }); }) .get('/endpoint:id', function *(next) { console.log('/endpoint:id'); console.log(this.params); this.body = 'Endpoint return'; }) </code></pre> <p>koa-router documentation on parameters</p> <pre><code>//Named route parameters are captured and added to ctx.params. router.get('/:category/:title', function *(next) { console.log(this.params); // =&gt; { category: 'programming', title: 'how-to-node' } }); </code></pre> <p>Request in angular controller:</p> <pre><code> $http.get('/endpoint', {params: { id: 223 }}) .then( function(response){ var respnse = response.data; console.log(response); } ); </code></pre>
0
java.lang.NoClassDefFoundError: Failed resolution of: Lorg/jacoco/agent/rt/internal_14f7ee5/Offline
<p>I'm seeing the following error in my Android project after updating to Gradle Build Tools 2.1.3 and Gradle 2.14.1. It happens immediately when I run the application. How do I fix this?</p> <pre><code>java.lang.NoClassDefFoundError: Failed resolution of: Lorg/jacoco/agent/rt/internal_14f7ee5/Offline; at com.ourapp.next.conversation.SomeList.SomeListViewModel.$jacocoInit(SomeListViewModel.java) at com.ourapp.next.conversation.SomeList.SomeListViewModel.(SomeListViewModel.java) at com.ourapp.next.conversation.SomeList.SomeListAdapterTest.(SomeListAdapterTest.java:26) at java.lang.reflect.Constructor.newInstance(Native Method) at java.lang.reflect.Constructor.newInstance(Constructor.java:288) at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217) at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runners.Suite.runChild(Suite.java:128) at org.junit.runners.Suite.runChild(Suite.java:27) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at org.junit.runner.JUnitCore.run(JUnitCore.java:115) at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59) at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1853) Caused by: java.lang.ClassNotFoundException: Didn't find class "org.jacoco.agent.rt.internal_14f7ee5.Offline" on path: DexPathList[[zip file "/system/framework/android.test.runner.jar", zip file "/data/app/com.ourapp.next.debug.test-1/base.apk", zip file "/data/app/com.ourapp.next.debug-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56) at java.lang.ClassLoader.loadClass(ClassLoader.java:511) at java.lang.ClassLoader.loadClass(ClassLoader.java:469) ... 30 more Suppressed: java.lang.ClassNotFoundException: org.jacoco.agent.rt.internal_14f7ee5.Offline at java.lang.Class.classForName(Native Method) at java.lang.BootClassLoader.findClass(ClassLoader.java:781) at java.lang.BootClassLoader.loadClass(ClassLoader.java:841) at java.lang.ClassLoader.loadClass(ClassLoader.java:504) ... 31 more Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available </code></pre>
0
Download image from S3 bucket to Lambda temp folder (Node.js)
<p>Good day guys.</p> <p>I have a simple question: <strong>How do I download an image from a S3 bucket to Lambda function temp folder for processing</strong>? Basically, I need to attach it to an email (this I can do when testing locally).</p> <p>I have tried:</p> <pre><code>s3.download_file(bucket, key, '/tmp/image.png') </code></pre> <p>as well as (not sure which parameters will help me get the job done):</p> <pre><code>s3.getObject(params, (err, data) =&gt; { if (err) { console.log(err); const message = `Error getting object ${key} from bucket ${bucket}.`; console.log(message); callback(message); } else { console.log('CONTENT TYPE:', data.ContentType); callback(null, data.ContentType); } }); </code></pre> <p>Like I said, simple question, which for some reason I can't find a solution for.</p> <p>Thanks!</p>
0
How to use Android KeyStore API with API 18?
<p>How do I get the equivalent code below when I'm targeting API 18? Code below works only for API 23 and above. Also how secure would the API 18 code be, given that we can't use <code>KeyGenParameterSpec</code> and the API 18 code might use deprecated APIs? </p> <pre><code>KeyGenerator keyGenerator = KeyGenerator.getInstance( KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); keyGenerator.init(new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setKeySize(256) .setUserAuthenticationRequired(true) .setUserAuthenticationValidityDurationSeconds(400) .setRandomizedEncryptionRequired(false) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) .build()); SecretKey key = keyGenerator.generateKey(); </code></pre>
0
Delete all characters after a certain character from a string in Swift
<p>I have a <code>textField</code> and I would like to remove all character after a certain character.</p> <p>For instance if what I have in the textField is the word <code>Orange</code> and I want to remove all characters after the <code>n</code> I would like to get <code>Ora</code> after the deletion.</p> <p>How can I delete all characters after a certain character from a string in Swift?</p> <p>Thanks</p>
0
NameError: global name 'Path' is not defined
<p>I'm a beginner of learning GUI. My python version is 2.7,and I'm using windows</p> <p>what should I do to be able to change the value of "path" by clicking button?</p> <p>here is the part of my code. :)</p> <pre><code>class Sign_page(tk.Frame): def __init__(self, parent, controller): self.controller = controller tk.Frame.__init__(self, parent) img_path = "C:/" Path = tk.Text(self, width = 45, height=1) Path.insert("end",img_path) Path.grid(row=2,column=0) ask_path = tk.Button(self, text = "...", command = lambda: asking_path(self)) ask_path.grid(row=2,column=1) </code></pre> <p>and this part is out of class "Sign_page"</p> <pre><code>def asking_path(self): fileName = askopenfilename(initialdir = "C:/") img_path = fileName Path.delete("1.0","end") Path.insert("end",img_path) </code></pre>
0
How to check if the parameter exist in python
<p>I would like to create a simple python script that will take a parameter from the console, and it will display this parameter. If there will be no parameter then I would like to display error message, but custom message not something like IndexError: list index out of range</p> <p>Something like this:</p> <pre><code>if isset(sys.argv[1]): print sys.argv[1]; else: print "No parameter has been included" </code></pre>
0
how to determine whether the directory is empty directory with nodejs
<p>I have searched the Nodejs Doc,But don't find relative API.</p> <p>So I write the following code to determine whether the directory is empty directory.</p> <pre><code>var fs = require('fs'); function isEmptyDir(dirnane){ try{ fs.rmdirSync(dirname) } catch(err){ return false; } fs.mkdirSync(dirname); return true } </code></pre> <p><strong>QUESTION:it look like some troublesome,there is better way to do it with nodejs?</strong></p>
0
pandas.factorize on an entire data frame
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="noreferrer"><code>pandas.factorize</code></a> encodes input values as an enumerated type or categorical variable. </p> <p>But how can I easily and efficiently convert many columns of a data frame? What about the reverse mapping step?</p> <p>Example: This data frame contains columns with string values such as "type 2" which I would like to convert to numerical values - and possibly translate them back later.</p> <p><a href="https://i.stack.imgur.com/MLATh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MLATh.png" alt="enter image description here"></a></p>
0
maven-replacer-plugin to replace tokens in build and not source
<p>I am trying to use the <code>maven-replacer-plugin</code> to replace tokens in my <code>web.xml</code> when it is built in the WAR file but not in the source, which would remove the tokens for subsequent builds and show the file as changed relative to the version control repository.</p> <p>Currently, I am only able to change the file in the source, which does not meet my requirement:</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;com.google.code.maven-replacer-plugin&lt;/groupId&gt; &lt;artifactId&gt;replacer&lt;/artifactId&gt; &lt;version&gt;1.5.2&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;prepare-package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;replace&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;configuration&gt; &lt;file&gt;${project.basedir}/src/main/webapp/WEB-INF/web.xml&lt;/file&gt; &lt;replacements&gt; &lt;replacement&gt; &lt;token&gt;@@sec.level@@&lt;/token&gt; &lt;value&gt;local&lt;/value&gt; &lt;/replacement&gt; &lt;/replacements&gt; &lt;/configuration&gt; &lt;/plugin&gt; </code></pre> <p><strong>Question</strong>: How can I run the replacer to only change the file in the WAR package while leaving the source unchanged for subsequent builds?</p>
0
How to show soft keyboard perfectly in fragment in Android?
<p>I have an EditText inside a Fragment inside a Activity.</p> <p>My Activity layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/login_bg"&gt; ... &lt;FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent"/&gt; ... &lt;/RelativeLayout&gt; </code></pre> <p>My Activity config in AndroidManifest.xml:</p> <pre><code> &lt;activity android:name="com.demo.LoginActivity" android:configChanges="orientation|keyboardHidden" android:launchMode="singleTop" android:screenOrientation="portrait" android:theme="@style/activityTheme" /&gt; </code></pre> <p>My code that use to start fragment in Activity:</p> <pre><code>private void startFragment(BaseFragment fragment, String tag) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.fragment_container, fragment); fragmentTransaction.addToBackStack(tag); fragmentTransaction.commitAllowingStateLoss(); } </code></pre> <p>My Fragment layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/common_background_color_white" android:orientation="vertical" android:clickable="true" android:paddingLeft="@dimen/email_common_padding_horizontal" android:paddingRight="@dimen/email_common_padding_horizontal"&gt; ... &lt;com.example.widget.LineEditView android:id="@+id/login_email_input" style="@style/BaseEditText.LoginEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:focusable="true" /&gt; ... &lt;/LinearLayout&gt; </code></pre> <p>My Custom Widget <code>LineEditView</code> is a child class extend <code>RelativeLayout</code>,and it layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/input" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;EditText android:id="@+id/edit" android:layout_width="match_parent" android:layout_height="wrap_content" android:focusable="true" android:gravity="start|center_vertical" android:background="@android:color/transparent" android:textColor="@color/common_text_color_black" android:maxLines="1" android:textCursorDrawable="@drawable/common_cursor_background_orange" android:textSize="@dimen/email_fields_text_size" android:paddingBottom="@dimen/email_fields_text_padding_bottom"/&gt; &lt;View android:id="@+id/underline" android:layout_below="@id/edit" android:layout_width="match_parent" android:layout_height="2px"/&gt; &lt;/RelativeLayout&gt; </code></pre> <p>I want to show soft keyboard according to inputType property of EditText,and can hide easily.</p> <p>What I have tried but not work or not perfect:</p> <p>1.According to <a href="https://stackoverflow.com/questions/10508363/show-keyboard-for-edittext-when-fragment-starts,i">Show keyboard for edittext when fragment starts</a> can show soft keyboard but can not hide easily(even can not hide sometimes) and it show keyboard not according to inputType property of EditText.</p> <p>2.I add following code to My Fragment:</p> <pre><code>@Override public View onCreateView(LayoutInflater inflater, ViewGroup container) { mEditText = (EditText) rootView.findViewById(R.id.edit); mEditText.requestFocus(); mEditText.setFocusable(true); } @Override public void onResume() { mEditText.postDelayed(mShowSoftInputRunnable, 400); super.onResume(); } private Runnable mShowSoftInputRunnable = new Runnable() { @Override public void run() { FragmentActivity activity = getActivity(); if (activity == null) return; InputMethodManager input = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); input.showSoftInput(mEditText, InputMethodManager.SHOW_IMPLICIT); } }; </code></pre> <p>but it can not show soft keyboard at all in my fragment.</p> <p>I can not put EditText to Activity because it need to refactor a lot of code.</p> <p>Does anyone have ideas to solve this problems?</p>
0
how to programmatically take a screenshot in react-native
<p>How can I take a screenshot in ReactNative. I need a screenshot and put it in <code>Image</code> component. How could I do?</p>
0
Angular 2 Passing data to component when dynamically adding the component
<p>I have dynamically added a component on the click of a button .</p> <p>Below is the code for my widget . Simple div with color property being set as input.</p> <p><strong>Widget.tmpl.html</strong></p> <pre><code> div class="{{color}}" (click)="ChangeColor()" </code></pre> <p>In the Widget component i am taking color as my input . This component works fine when i add it manually . But now i am trying to dynamically add the component and also need to pass the Color Value to the Widget Component.</p> <p>Below is the code in the app.component.ts where i am calling addItem() on the button click .</p> <p><strong>app.component.ts</strong> </p> <pre><code>export class AppComponent { @ViewChild('placeholder', {read: ViewContainerRef}) viewContainerRef; private componentFactory: ComponentFactory&lt;any&gt;; constructor(componentFactoryResolver: ComponentFactoryResolver, compiler: Compiler) { this.componentFactory = componentFactoryResolver.resolveComponentFactory(MyAppComponent); } addItem () { this.viewContainerRef.createComponent(this.componentFactory, 0); } public myValue:string = 'red'; onChange(val: any) { this.myValue = val; } } </code></pre> <p>In the addItem() method i am dynamically adding my widget component to my view. The component gets added fine . But the problem is how to pass the color property when dynamically adding . Based on what color i pass when creating the widget i want it to be displayed in red or green etc. How to property bind in this scenario?</p> <p>Here is some of the Code :</p> <pre><code>export class MyAppComponent { @Input() color; @Output('changes') result: EventEmitter&lt;any&gt; = new EventEmitter(); public constructor() { } ChangeColor() { this.ToggleColor(); this.result.emit(this.color);// Emitting the color to the parent. } ToggleColor() { if (this.color == "red") this.color = "blue"; else this.color = "red"; } } </code></pre> <p>In the above code i am emitting my color to the parent app.component.ts but since i have dynamically added the widget component , i dont know where to add this code (changes)="onChange($event)". I tried to add this code in the div as shown below :</p> <pre><code>&lt;div class="{{color}}" (click)="ChangeColor()" (changes)="onChange($event)"&gt;&lt;/div&gt; </code></pre> <p>But it does not work.</p>
0
How to print 2 lists vertically next to each other?
<p>I know how to print a list vertically :</p> <pre><code>for item in items: print(item) </code></pre> <p>Output :</p> <pre><code>43435 23423 </code></pre> <p>however I want to put another list (called items2) next to each other so the out put is like this :</p> <pre><code>43435 a 23423 a </code></pre> <p>how can I do this in the simplest way ?</p> <p>EDIT:</p> <pre><code>86947367 banana 2 10 78364721 apple 2 6 </code></pre>
0
Cut a polygon with two lines in Shapely
<p>I am trying to cut a <code>shapely.geometry.Polygon</code> instance in two parts with two lines. For example, in the code below, <code>polygon</code> is a ring and if we cut it with <code>line1</code> and <code>line2</code> we should get two partial rings, one w/ 270 degrees and one with 90 degrees. Would there be a clean way to do this?</p> <pre><code>from shapely.geometry import Point, LineString, Polygon polygon = Point(0, 0).buffer(2).difference(Point(0, 0).buffer(1)) line1 = LineString([(0, 0), (3, 3)]) line2 = LineString([(0, 0), (3, -3)]) </code></pre>
0