title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
How to create a string array using JNI in Qt
<p>I have to write some Android platform specific code in Qt and need to use JNI. I have a problem with how to create an array of some object. In this case I want to construct an array of strings from C++.</p> <p>In the two code snippets below the first one creates a java string and it works as expected. In the second code snippet I want to create a java string array, but I get the debug message: "Java string array not valid" so I assume the signature and/or parameters passed to the "QAndroidJniObject javaStringArray()" function is not correct.</p> <p>I have been looking at the documentation, but was not able to find or properly understand how to do this.</p> <p>I assume I have to send in the size of the java string array object I want to construct as well.</p> <p>Any help is appreciated!</p> <pre><code>QAndroidJniObject javaString("java/lang/String"); if (!javaString.isValid()) { qDebug() &lt;&lt; "Java string not valid"; return false; } QAndroidJniObject javaStringArray("[Ljava/lang/String;"); if (!javaStringArray.isValid()) { qDebug() &lt;&lt; "Java string array not valid"; return false; } </code></pre>
2
Regarding will_paginate using an explicit "per page" limit - Rails 4.2.0
<p>For instance, I have got a Post model and I will achieve per page limit of 10 in the way as below;</p> <pre><code>Post.paginate(:page =&gt; params[:page], :per_page =&gt; 10) </code></pre> <p>But my question is, How would I limit pages randomly.</p> <p>For example, for the first page I want to show 10 records and on the second page I want to show 15 records and so on.</p> <p>How would I implement this in my rails application.</p> <p>posts_controller.rb</p> <pre><code> class PostsController &lt; ApplicationController before_action :set_post, only: [:show, :edit, :update, :destroy] # GET /posts # GET /posts.json def index @posts = Post.paginate(page: params[:page]) dynamic_paging = {"1" =&gt; 10, "2"=&gt; 15, "3"=&gt; 20, "4"=&gt;25 } per_page_after_four = 30 params[:page] = params[:page] || 1 if params[:page] &lt; 5 @posts = Post.paginate(:page =&gt; params[:page], :per_page =&gt; dynamic_paging[params[:page]]) else @posts = Post.paginate(:page =&gt; params[:page], :per_page =&gt; per_page_after_four) end end </code></pre> <p>index.html.erb</p> <pre><code>&lt;center&gt;&lt;%= will_paginate @posts %&gt;&lt;/center&gt; </code></pre> <p>Any suggestions are most welcome.</p> <p>Thank you in advance.</p>
2
Codeigniter : Parse error: syntax error, unexpected end of file on my View
<p>I got some error on my <code>View</code> form: </p> <blockquote> <p>Parse error: syntax error, unexpected end of file</p> </blockquote> <pre><code>&lt;div class="form-group"&gt; &lt;label for="exampleInputJenis"&gt;Jenis Obat&lt;/label&gt; &lt;div class="input-group"&gt; &lt;span class="input-group-addon"&gt;&lt;i class="fa fa-list"&gt;&lt;/i&gt;&lt;/span&gt; &lt;select name="kode_jenis_obat" class="form-control" action="&lt;?php echo form_dropdown('kode_jenis_obat',$hasil-&gt;kode_jenis_obat);?&gt;"&gt; &lt;option&gt;Pilih Jenis Obat&lt;/option&gt; &lt;!-----Displaying fetched cities in options using foreach loop ----&gt; &lt;?php foreach ($kode_jenis_obat as $isi) { if($isi-&gt;kode_jenis_obat == $isi-&gt;kode_jenis_obat) {?&gt; &lt;option value="&lt;?php echo $isi-&gt;kode_jenis_obat; ?&gt;"&gt;&lt;?php echo $isi-&gt;nama_jenisobat?&gt;&lt;/option&gt; &lt;?php} else {?&gt; &lt;option value="&lt;?php echo $isi-&gt;kode_jenis_obat; ?&gt;"&gt;&lt;?php echo $isi-&gt;nama_jenisobat?&gt;&lt;/option&gt; &lt;?php} } ?&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Can someone help me?</p>
2
Unable to generate java code for webservice using WSDLToJava with Apache CXF 3.1.6
<p>I am trying to generate the java code for webservice using <code>WSDLToJava</code> in Apache CXF 3.1.6, but I am getting this exception and I don't know from where the Velocity templates are coming into picture.</p> <pre><code>WSDLToJava Error: Could not find Velocity template file: org/apache/cxf/tools/wsdlto/frontend/jaxws/template/service.vm </code></pre> <p>I was trying to locate the file in my project or in the generated code, but I don't see it anywhere.</p> <p>Do I need to include the velocity jars in my project or do I need to create a <code>service.vm</code> velocity template?</p>
2
BLE Explorer for Windows 10 Universal
<p>Is there any Bluetooth Low Energy sample applications for Windows 10 universal platform? Please help me.</p>
2
How to Hide previous dates in Date Picker in Android Xamarin
<p>I am Using This Code but OnDateChanged method is not called why, where am i doing mistake please help me.</p> <pre><code>public class DatePickerFragment : DialogFragment, DatePickerDialog.IOnDateSetListener,DatePicker.IOnDateChangedListener { // TAG can be any string of your choice. public static readonly string TAG = "X:" + typeof(DatePickerFragment).Name.ToUpper(); // Initialize this value to prevent NullReferenceExceptions. Action&lt;DateTime&gt; _dateSelectedHandler = delegate { }; DateTime currently = DateTime.Now; public static DatePickerFragment NewInstance(Action&lt;DateTime&gt; onDateSelected) { DatePickerFragment frag = new DatePickerFragment(); frag._dateSelectedHandler = onDateSelected; return frag; } public override Dialog OnCreateDialog(Bundle savedInstanceState) { DatePickerDialog dialog = new DatePickerDialog(Activity, this, currently.Year, currently.Month, currently.Day); return dialog; } public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // Note: monthOfYear is a value between 0 and 11, not 1 and 12! DateTime selectedDate = new DateTime(year, monthOfYear + 1, dayOfMonth); _dateSelectedHandler(selectedDate); } public void OnDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { if (year &lt; currently.Year) view.UpdateDate(currently.Year, currently.Month, currently.Day); if(monthOfYear &lt; currently.Month &amp;&amp; monthOfYear == currently.Year) view.UpdateDate(currently.Year, currently.Month, currently.Day); if(dayOfMonth&lt; currently.Day &amp;&amp; year == currently.Year &amp;&amp;monthOfYear == currently.Month) view.UpdateDate(currently.Year, currently.Month, currently.Day); } </code></pre> <p>}</p> <p>I am trying to disable previous dates from date picker but date change listener is not calling . I want to hide Past dates from datepicker can you please help me how can i do that.</p>
2
Cross-validating an ordinal logistic regression in R (using rpy2)
<p>I'm trying to create a predictive model in Python, comparing several different regression models through cross-validation. In order to fit an ordinal logistic model (<code>MASS.polr</code>), I've had to interface with R through <code>rpy2</code> as follows:</p> <pre><code>from rpy2.robjects.packages import importr import rpy2.robjects as ro df = pd.DataFrame() df = df.append(pd.DataFrame({"y":25,"X":7},index=[0])) df = df.append(pd.DataFrame({"y":50,"X":22},index=[0])) df = df.append(pd.DataFrame({"y":25,"X":15},index=[0])) df = df.append(pd.DataFrame({"y":75,"X":27},index=[0])) df = df.append(pd.DataFrame({"y":25,"X":12},index=[0])) df = df.append(pd.DataFrame({"y":25,"X":13},index=[0])) # Loads R packages. base = importr('base') mass = importr('MASS') # Converts df to an R dataframe. from rpy2.robjects import pandas2ri pandas2ri.activate() ro.globalenv["rdf"] = pandas2ri.py2ri(df) # Makes R recognise y as a factor. ro.r("""rdf$y &lt;- as.factor(rdf$y)""") # Fits regression. formula = "y ~ X" ordlog = mass.polr(formula, data=base.as_symbol("rdf")) ro.globalenv["ordlog"] = ordlog print(base.summary(ordlog)) </code></pre> <p>So far, I have mainly been comparing my models using <code>sklearn.cross_validation.test_train_split</code> and <code>sklearn.metrics.accuracy_score</code>, yielding a number from 0 to 1 which represents the accuracy of the training-set model in predicting the test-set values.</p> <p>How might I replicate this test using <code>rpy2</code> and <code>MASS.polr</code>?</p>
2
How to perform long HTTP requests in expressjs?
<p>I wrote an express.js application and one of my GET requests takes a very long time to complete (it runs a spark query on a Hadoop client).<br> Because the request takes so much time, the client which performed the request (Chrome, Firefox, jQuery) re-sends the same request to the express.js app again and again.<br> Is there a way to handle these recurring requests?</p>
2
Connect to Teradata DB via Postgres
<p>I need to have access to one table stored in Teradata from Postgres. </p> <p>Is there any way to connect to Teradata DB from Postgres DB? </p> <p>I know that I can use export/import functions or create simple ETL process loading data from Teradata to Postgres DB with Talend for example but before I will start I want to be sure that direct linking is not possible (at least I didn't found solution for that on the internet).</p>
2
Is it possible to use so = shellout("linux cmd") outside of Chef in ruby script?
<p>I'm curious, is there a possibility to use shellout in ruby scripts outside of Chef? How to set up this?</p>
2
Java OpenCV FileStorage and Mat.push_back
<p>I'm trying to implement <a href="https://github.com/MicrocontrollersAndMore/OpenCV_3_KNN_Character_Recognition_Cpp/blob/master/GenData.cpp" rel="nofollow">this</a> project, namely GenData.cpp, (written in C++) in Java for KNN classifier. <br> I've reached these lines of code and stuck:</p> <pre><code>matClassificationInts.push_back(intChar); cv::FileStorage fsClassifications("classifications.xml", cv::FileStorage::WRITE); fsClassifications &lt;&lt; "classifications" &lt;&lt; matClassificationInts; fsClassifications.release(); </code></pre> <p>In c++ we can pass integer to push_back(), but in Java I'm getting error: "int cannot be converted to Mat".<br> So, the first question is: how can I pass int to someMat.push_back()?<br> And the second one: how could I implement FileStorage in Java or write Mat to *.xml format (and read Mat from *.xml)?</p> <p>so far, my code:</p> <pre><code> import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import org.opencv.core.Core; import static org.opencv.core.CvType.CV_32FC1; import org.opencv.core.Mat; import org.opencv.core.MatOfInt4; import org.opencv.core.MatOfPoint; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import static org.opencv.imgproc.Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C; import static org.opencv.imgproc.Imgproc.CHAIN_APPROX_SIMPLE; import static org.opencv.imgproc.Imgproc.RETR_EXTERNAL; import static org.opencv.imgproc.Imgproc.THRESH_BINARY_INV; public class genData { private static final int MIN_CONTOUR_AREA = 100, RESIZED_IMAGE_WIDTH = 20, RESIZED_IMAGE_HEIGHT = 30; public static void main(String[] args) throws IOException { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Scanner keyboard = new Scanner(System.in); boolean exit = false; Mat imgTrainingNumbers; Mat imgGrayscale = new Mat(); Mat imgBlurred = new Mat(); Mat imgThresh = new Mat(); Mat imgThreshCopy = new Mat(); ArrayList&lt;MatOfPoint&gt; ptContours = new ArrayList&lt;MatOfPoint&gt;(); MatOfInt4 v4iHierarchy; Mat matClassificationInts = new Mat(); Mat matTrainingImagesAsFlattenedFloats = new Mat(); int[] intValidChars = { '0', '1', '2', 'A', 'B', 'C'}; //Here I did not make List&lt;Integer&gt;, because I can't pass char to Integer. Arrays.sort(intValidChars); //for binary search imgTrainingNumbers = Imgcodecs.imread("test.png"); //here Text on white paper. if (imgTrainingNumbers.empty()) { System.out.println("err"); return; } Imgproc.cvtColor(imgTrainingNumbers, imgGrayscale, Imgproc.COLOR_BGR2GRAY); Imgproc.GaussianBlur(imgGrayscale, imgBlurred, new Size(5, 5), 0); Imgproc.adaptiveThreshold(imgBlurred, imgThresh, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY_INV, 11, 2); /* //imshow class implementation (found via google, works properly, but this block is commented for now) Imshow im = new Imshow("imgThresh"); im.showImage(imgThresh); imgThreshCopy = imgThresh.clone(); */ Imgproc.findContours(imgThreshCopy, ptContours, new Mat(), RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); for (int i = 0; i &lt; ptContours.size(); i++) { if (Imgproc.contourArea(ptContours.get(i)) &gt; MIN_CONTOUR_AREA) { Rect boundingRect = Imgproc.boundingRect(ptContours.get(i)); Imgproc.rectangle(imgTrainingNumbers, boundingRect.tl(), boundingRect.br(), new Scalar(0, 0, 255), 2); Mat matROI = imgThresh.submat(boundingRect.y, boundingRect.y + boundingRect.height, boundingRect.x, boundingRect.x + boundingRect.width); Mat matROIResized = new Mat(); Imgproc.resize(matROI, matROIResized, new Size(RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT)); /* im.showImage(matROI); im.showImage(matROIResized); im.showImage(imgTrainingNumbers); */ String input = keyboard.nextLine(); int intChar = (int)input.charAt(0); if (Arrays.binarySearch(intValidChars, intChar) &gt;=0) { /* matClassificationInts.push_back(intChar); //Here I'm getting an error. */ Mat matImageFloat = new Mat(); matROIResized.convertTo(matImageFloat, CV_32FC1); Mat matImageFlattenedFloat = matImageFloat.reshape(1, 1); matTrainingImagesAsFlattenedFloats.push_back(matImageFlattenedFloat); } } } //Here should go FileStorage stuff. } } </code></pre> <p>Thanks in advance. <br> P.S. Using OpenCV_310 + Java (not JavaCV)</p>
2
Inserting array of data into database using Node.js
<p>As a rookie in web development I was hoping you can point me in the right direction on how to insert JSON data into a mongo database, to be used for automatic graph creation.</p> <p><a href="https://api.twitch.tv/kraken/games/top" rel="nofollow">I have a JSON response from this URL converted to a JavaScipt object looking like this:</a></p> <pre><code>[ { game: { name: 'Counter-Strike: Global Offensive', popularity: 244757, _id: 32399, giantbomb_id: 36113, box: [Object], logo: [Object], _links: {} }, viewers: 246950, channels: 488 }, { game: { name: 'League of Legends', ... </code></pre> <p>However I wonder how I can structure this data in a database so I can later graph my data according to the time and date it was fetched.</p> <p>I figure that I would want to keep a list of Ids related to popularity and date. </p> <p>Can you point me in a direction on how to read a JSON array and update a Mongo collection with the data so it looks something like this?</p> <pre><code>{ _id: "32399", name: "Counter-Strike: Global Offensive", datapoints: [ { 2016-05-18T16:00:00Z viewers: 246950 channels: 488 }, { 2016-04-18T16:00:00Z viewers: 230000 channels: 433 } ] } </code></pre> <p>I guess can iterate over every value using forEach. But is this the right method? and how do I sort the information? do I iteratively go through every entity and find viewer and channel values and save to a new document cache or use updateOne to update my database?</p> <pre><code>games.top.forEach(function(value) { console.log(value) }); </code></pre>
2
How to get a Appium child element from document when child is different based on phone type (Button/TextView)
<p>I am trying to solve this with <code>xpath</code> but I am open to another solution.</p> <p>On different phones the document is created differently. Inside the <code>LinearLayout</code> the child is a <code>Button</code> on Samsung and <code>TextView</code> on LG.</p> <p>I wanted to know if there is a easy way to get one or the other.</p> <p>I tried to do this using <code>xpath</code> to check for the <code>Button</code>. If it exists then its for the <code>samsung</code> and click it. The problem is that <code>Appium</code> just hangs trying to find the <code>Button</code>. I figured it would look and move on.</p> <p>I can setup the code to get the parent and then find by class the child and take the second index but I am wondering if there is a better way.</p> <p>Is there any way to do the xpath to process the child without specifying its name/type?</p> <pre><code>By.xpath("//android.widget.LinearLayout[@index='0'][1]") </code></pre> <p><strong>Here is the current code:</strong></p> <pre><code> if (!StringUtility.isEmptyString(driver.findElement(By.xpath("//android.widget.Button[@index='0']")).getAttribute("name"))) { driver.findElement(By.xpath("//android.widget.Button[@index='0']")).click(); } else { // LG or Other driver.findElement(By.xpath("//android.widget.TextView[@index='0']")).click(); } </code></pre> <p><a href="https://i.stack.imgur.com/WYe9X.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WYe9X.jpg" alt="LG Phone"></a></p> <p><a href="https://i.stack.imgur.com/wJCvf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wJCvf.jpg" alt="Samsung Phone"></a></p> <p><strong>Appium log:</strong></p> <pre><code>&gt; info: [debug] Pushing command to appium work queue: ["find",{"strategy":"xpath","selector":"//android.widget.Button[@index='0']","context":"","multiple":false}] &gt; info: [debug] [BOOTSTRAP] [debug] Got data from client: {"cmd":"action","action":"find","params":{"strategy":"xpath","selector":"//android.widget.Button[@index='0']","context":"","multiple":false}} &gt; info: [debug] [BOOTSTRAP] [debug] Got command of type ACTION &gt; info: [debug] [BOOTSTRAP] [debug] Got command action: find &gt; info: [debug] [BOOTSTRAP] [debug] Finding //android.widget.Button[@index='0'] using XPATH with the contextId: multiple: false &gt; info: [debug] [BOOTSTRAP] [debug] Returning result: {"status":7,"value":"Could not find an element using supplied strategy. "} &gt; info: [debug] Waited for 10987ms so far </code></pre>
2
Ag-grid + React + Redux not styled
<p>I am able to build the example app of app of <a href="https://github.com/ceolter/ag-grid-react-example" rel="nofollow">AG-Grid</a>. It's running smoothly and is styled nicely.</p> <p>Then I would like to move it to my app but it seems that the styles are not applied. I put all the example files from <a href="https://github.com/ceolter/ag-grid-react-example/tree/master/src" rel="nofollow">https://github.com/ceolter/ag-grid-react-example/tree/master/src</a> to a new folder in my project thus making a component that I use in my app:</p> <pre><code>import React from 'react' import AgGrid from './AgGrid/myApp.jsx'; // Pages export default class PatPorts extends React.Component { render() { return ( &lt;div&gt; &lt;h2&gt;Ports&lt;/h2&gt; &lt;div&gt;Some home page content&lt;/div&gt; &lt;AgGrid/&gt; &lt;/div&gt; ) } } </code></pre> <p>My <code>webpack.config</code> is the following:</p> <pre><code>var webpack = require('webpack'); var path = require('path'); var BUILD_DIR = path.resolve(__dirname, '../public/js'); var APP_DIR = path.resolve(__dirname, 'app'); var config = { entry: APP_DIR + '/index.jsx', output: { path: BUILD_DIR, filename: 'bundle.js' }, module: { loaders: [ { test: /\.css$/, loader: "style!css" }, { test: /\.js$|\.jsx$/, loader: 'babel-loader', include: APP_DIR, // Where to look for *.js and *.jsx query: { presets: ['react', 'es2015'] } } ] }, plugins: [ new webpack.NoErrorsPlugin() // do not automatically reload if there are errors ], resolve: { alias: { "ag-grid-root" : __dirname + "/node_modules/ag-grid" } } }; module.exports = config; </code></pre> <p>I am new to react so I may be missing something elementary... Any ideas? I can find <code>myApp.css</code> in the generated bundle. How to make it work?</p>
2
x86-32 / x86-64 polyglot machine-code fragment that detects 64bit mode at run-time?
<p>Is it possible for the same bytes of machine code to figure out whether they're running in 32 or 64 bit mode, and then do different things?</p> <p>i.e. write <a href="https://en.wikipedia.org/wiki/Polyglot_(computing)" rel="nofollow noreferrer">polyglot</a> machine code.</p> <p>Normally you can detect at build time with <code>#ifdef</code> macros. Or in C, you could write an <code>if()</code> with a compile-time constant as the condition, and have the compiler optimize away the other side of it.</p> <p>This is only useful for weird cases, like maybe code injection, or just to see if it's possible.</p> <hr> <p>See also: a <a href="https://stackoverflow.com/a/38056588/224132">polyglot ARM / x86 machine code</a> to branch to different addresses depending on which architecture is decoding the bytes.</p>
2
how to style simple_form with material design or custom css
<p>I want style my simple_form in rails app with material framwork this is my login form code <h2>Log in</h2></p> <pre><code>&lt;%= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %&gt; &lt;div class="form-inputs"&gt; &lt;%= f.input :login %&gt; &lt;%= f.input :password, required: false %&gt; &lt;%= f.input :remember_me, as: :boolean if devise_mapping.rememberable? %&gt; &lt;/div&gt; &lt;div class="form-actions"&gt; &lt;%= f.button :submit, "Log in" %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>And this is sample input , i want sytle my form like this </p> <p><a href="https://codepen.io/sevilayha/pen/IdGKH" rel="nofollow">https://codepen.io/sevilayha/pen/IdGKH</a></p>
2
Spark RDD pipe value from tuple
<p>I have a Spark RDD where each element is a tuple in the form <code>(key, input)</code>. I would like to use the <code>pipe</code> method to pass the inputs to an external executable and generate a new RDD of the form <code>(key, output)</code>. I need the keys for correlation later.</p> <p>Here is an example using the spark-shell:</p> <pre><code>val data = sc.parallelize( Seq( ("file1", "one"), ("file2", "two two"), ("file3", "three three three"))) // Incorrectly processes the data (calls toString() on each tuple) data.pipe("wc") // Loses the keys, generates extraneous results data.map( elem =&gt; elem._2 ).pipe("wc") </code></pre> <p>Thanks in advance.</p>
2
Audio Playing from URI Inside Listview , But Seekbar is not Updating in Android Listview item
<ol> <li>I am Playing a Audio from Uri Its Working Fine.</li> <li>Clicking a Button from Each Listview item.</li> </ol> <p>Problem :<strong>Audio is Playing in the Listview</strong> ,but still <strong>Seekbar</strong> is not Moving(<strong>Updating</strong>).</p> <p><strong>EDIT:1</strong></p> <p>1.<strong>Audio is Playing in the Each Listview Item Perfectly</strong>,<strong>But Seekbar is Not Working(Not Updating)</strong>.</p> <p>Please Help me top solve this Issue.</p> <p>My <strong>Listview Array adapter</strong> Class:</p> <p>Adapter.class</p> <pre><code> private static final int UPDATE_FREQUENCY = 500; int progress=0; public View getView(final int position, View view, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View rowView = inflater.inflate(R.layout.audio_listview, null, true); ListenAUdioButton = (Button) rowView.findViewById(R.id.ListenAudiobuttonxml); seek_bar_view = (SeekBar) rowView.findViewById(R.id.seek_bar); ListenAUdioButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // text_shown.setText("Playing..."); try { try { // get Internet status isInternetPresent = cd1.isConnectingToInternet(); // check for Internet status if (isInternetPresent) { if (!itemname3_AUDIO_FILE[position].equals("") || !itemname3_AUDIO_FILE[position].equals("null")) { System.out.println(" AUDIO FILE :-)" + itemname3_AUDIO_FILE[position]); player = new MediaPlayer(); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.setDataSource(context, Uri.parse(itemname3_AUDIO_FILE[position])); player.prepareAsync(); player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { try { mp.start(); seek_bar_view.setMax(player.getDuration()); updatePosition(); } catch (Exception e) { e.printStackTrace(); } } }); player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { stopPlay(); } }); MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { // returning false will call the OnCompletionListener return false; } }; } else { Toast.makeText(getContext(), "Audio Not Found..!", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getContext(), "Please Check Your Internet Connection..!", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(getContext(), "Audio Not Found..!", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); } } }); return rowView; } private void stopPlay() { player.stop(); player.reset(); // playButton.setImageResource(android.R.drawable.ic_media_play); handler.removeCallbacks(updatePositionRunnable); seek_bar_view.setProgress(0); // isStarted = false; } private final Handler handler = new Handler(); private final Runnable updatePositionRunnable = new Runnable() { public void run() { updatePosition(); } }; private void updatePosition() { handler.removeCallbacks(updatePositionRunnable); seek_bar_view.setProgress(progress); progress=getProgressPercentage(player.getCurrentPosition(),player.getDuration(); notifyDataSetChanged(); handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY); } </code></pre>
2
How to hide text fields and value when input fields is null
<p>I need to hide a field on page load based on the value of a request attribute. I don't want a 'hidden' field because I want to show it again. I don't want to do this with javascript,ajax. How is this done with jsp tags? I have this code, when i run this code my text value has been hide(ie 56785456577) but am not able to hide the text fields(ie Tel No)...I have this code</p> <pre><code> &lt;s:if test="purchaseOrder.company.phone!=''"&gt; &lt;div id="phone_no" class="draggable ui-widget-content resizeable" &lt;s:set var="phone_no" value="#formSetupTemplate.formSetupTemplateElementList. {^#this.drag_id=='phone_no'}"/&gt; &lt;s:if test="#phone_no!=null &amp;&amp; #phone_no.size!=0"&gt; &lt;s:set var="phone_no" value="#phone_no[0]"/&gt; style="position: &lt;s:property value="#phone_no.position"/&gt;; top: &lt;s:property value="#phone_no.top"/&gt;; left:&lt;s:property value="#phone_no.left"/&gt;; width: &lt;s:property value="#phone_no.width"/&gt;; height: &lt;s:property value="#phone_no.height"/&gt;; &lt;/s:if&gt;"&gt; &lt;p&gt;Tel.No: &lt;s:property value="company.phone"/&gt;&lt;/p&gt; &lt;/div&gt; &lt;/s:if&gt;"&gt; </code></pre> <p>Through the above code am able to hide text filed value(ie phone no- 56785456577) but am not able to hide text fields name ie Tel No(Fields Name)Here am also attaching the image <a href="http://i.stack.imgur.com/WtIF2.jpg" rel="nofollow">In the Given Image Am unable to hide Tel No</a></p>
2
Azure Functions - Local development with moq unit testing & Continuous Deployment using VSTS Release pipeline
<p>I am looking for developing Azure Functions as a project in Visual Studio rather than browser based coding that goes to GIT repo and follows Continuous Build and Deployment processes of VSTS existing pipelines. Want to know whether this is possible and also would like to know whether we can build a moq based unit testing for these Function projects?</p>
2
JAXB mapping 1 XML Tag to 2 variables
<p>i am trying to use one class to map the response i get from an XML request. But the xml response differs, depending own some settings. For example in a response i get the tag "owner" which is filled with the ID of the owner object. If i add a setting in my request i will get back the full owner data, like the firstname and lastname. Now i want to map the owner tag to either a String variable or a Class depending on the response.</p> <p>Example :</p> <pre><code>@XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "domain") public class Response { @XmlElement private String name; @XmlElement(name = "owner") private String ownerSimple; @XmlElement(name = "owner") private Owner ownerComplex; } @XmlRootElement(name = "ownerc") public class OwnerC { @XmlElement int id; @XmlElement String fname; @XmlElement String lname; } </code></pre> <p>XML to map :</p> <pre><code>&lt;response&gt; &lt;name&gt;Foo&lt;/name&gt; &lt;owner&gt;1234&lt;/owner&gt; &lt;!-- in this case it's only a id --&gt; &lt;/response&gt; &lt;response&gt; &lt;name&gt;Foo&lt;/name&gt; &lt;owner&gt; &lt;!-- in this case it's the owner class --&gt; &lt;id&gt;1234&lt;/id&gt; &lt;fname&gt;Jon&lt;/fname&gt; &lt;lname&gt;Doe&lt;/lname&gt; &lt;/owner&gt; &lt;/response&gt; </code></pre>
2
Laravel 5.2 - get images of item in blade view
<p>My controller is:</p> <pre><code>public function index() { $details= Food::all(); return view('details.index', compact('details')); } public function show($Food_id) { $detail=Food::findOrFail($Food_id); return view('details.show', compact('detail')); } </code></pre> <p>My index.blade.php is:</p> <pre><code>&lt;h1&gt;Details&lt;/h1&gt; &lt;hr/&gt; @foreach($details as $detail) &lt;detail&gt; &lt;h2&gt; &lt;a href="/details/{{$detail-&gt;Food_id}}"&gt;{{$detail-&gt;FoodName}} &lt;/a&gt; &lt;/h2&gt; &lt;/detail&gt; @endforeach </code></pre> <p>And my show.blade.php is:</p> <pre><code> &lt;h1 align="center"&gt;{{$detail -&gt; FoodName}}&lt;/h1&gt; &lt;detail&gt; &lt;h3&gt;&lt;p&gt;Name:&lt;/h3&gt;&lt;h4&gt;{{$detail-&gt;FoodName}}&lt;/h4&gt;&lt;/p&gt; </code></pre> <p>I want to show the images of food items that are stored in public/uploads folder.How I can get images to show them.</p>
2
External Clients unable to access WCF Communication Listener on Azure Service Fabric
<p>I'm trying to migrate Azure Web Roles running WCF, to stateless services in Azure Service Fabric, using the WCF Communication Listener. Everything works in my local service cluster. After publishing to Azure, other services within the cluster are able to access the stateless WCF service, but external (internet) clients (including my dev machine) are unable to connect with a transient network error. </p> <p>I verified that the load balancer in the resource group has rules/probes for ports 80 and 8080, and have tested with TCP and HTTP. I also tried to setup the partition resolver on the WCF client to point the "client connection endpoint" on the service cluster (from default, which works within the service cluster). </p> <p>At this point, I'm not sure if I have a configuration issue, or if it's even possible for external (internet) clients to connect to stateless services running the WCF Communication Listener.</p> <p>Here is my config:</p> <p><strong>WCF Communication Listener</strong></p> <pre><code> private Func&lt;StatelessServiceContext, ICommunicationListener&gt; CreateListener() { return delegate (StatelessServiceContext context) { var host = new WcfCommunicationListener&lt;IHello&gt;( wcfServiceObject: this, serviceContext: context, endpointResourceName: "ServiceEndpoint", listenerBinding: CreateDefaultHttpBinding() ); return host; }; } </code></pre> <p><strong>WCF Binding</strong> </p> <pre><code> public static Binding CreateDefaultHttpBinding() { var binding = new WSHttpBinding(SecurityMode.None) { CloseTimeout = new TimeSpan(00, 05, 00), OpenTimeout = new TimeSpan(00, 05, 00), ReceiveTimeout = new TimeSpan(00, 05, 00), SendTimeout = new TimeSpan(00, 05, 00), MaxReceivedMessageSize = int.MaxValue, }; var quota = new XmlDictionaryReaderQuotas { MaxArrayLength = int.MaxValue, MaxDepth = int.MaxValue }; binding.ReaderQuotas = quota; return binding; } </code></pre> <p><strong>ServiceManifest.xml</strong> (I've also used the default TCP binding with various ports)</p> <pre><code>&lt;Endpoints&gt; &lt;Endpoint Name="ServiceEndpoint" Protocol="http" Port="8080" /&gt; &lt;/Endpoints&gt; </code></pre> <p><strong>WCF Console App</strong></p> <pre><code>var address = new Uri("fabric:/ServiceFabricWcf.Azure/ServiceFabricWcf"); var client = GetClient(address, CreateDefaultHttpBinding()); try { var results = client.InvokeWithRetry(x =&gt; x.Channel.Hello()); System.WriteLine($"Results from WCF Service: '{results}'"); Console.ReadKey(); } catch (Exception e) { System.Console.WriteLine("Exception calling WCF Service: '{e}'"); } </code></pre> <p><strong>WCF Client</strong></p> <pre><code> public static WcfServiceFabricCommunicationClient&lt;IHello&gt; GetClient(Uri address, Binding binding) { //ServicePartitionResolver.GetDefault(); Works with other services in cluster var partitionResolver = new ServicePartitionResolver("&lt;clientConnectionEndpointOfServiceCluster&gt;:8080"); var wcfClientFactory = new WcfCommunicationClientFactory&lt;IHello&gt;(binding, null, partitionResolver); var sfclient = new WcfServiceFabricCommunicationClient&lt;IHello&gt;(wcfClientFactory, address, ServicePartitionKey.Singleton); return sfclient; } </code></pre> <p><strong>WCF Client Factory</strong></p> <pre><code> public class WcfServiceFabricCommunicationClient&lt;T&gt; : ServicePartitionClient&lt;WcfCommunicationClient&lt;T&gt;&gt; where T : class { public WcfServiceFabricCommunicationClient(ICommunicationClientFactory&lt;WcfCommunicationClient&lt;T&gt;&gt; communicationClientFactory, Uri serviceUri, ServicePartitionKey partitionKey = null, TargetReplicaSelector targetReplicaSelector = TargetReplicaSelector.Default, string listenerName = null, OperationRetrySettings retrySettings = null ) : base(communicationClientFactory, serviceUri, partitionKey, targetReplicaSelector, listenerName, retrySettings) { } } </code></pre>
2
Ionic: Disallow all emoticons
<p>I want to disallow all emoticons in my text inputs and textareas.</p> <p>Currently at every input the whole text will be checked, and if there is an emoticon, a notification is displayed that they are not allowed.</p> <p>How can I achieve, that just the last character will be checked (instead of the whole text, I think this is better perfomance-wise), and if this char is an emoticon, it will not be displayed (blocked)? Furthermore, my current regex just disallows some emoticons (just the special ones, like Eyes or Shoes), not all of them (e.g. the normal Smiley, or Tongue-Smiley). How can I block them all?</p> <p>My code so far (HTML):</p> <pre><code>&lt;textarea ng-model="postcard.textBack" id="message-textarea" no-emoticons&gt;&lt;/textarea&gt; </code></pre> <p>Ionic</p> <pre><code>app.directive('noEmoticons', function ($timeout) { return function (scope, element, attrs) { var emoticonDetected; element.bind("keydown", function (event) { var text = $('#message-textarea').val(); if(text.match(/([\uE000-\uF8FF]|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDDFF])/g, '')){ emoticonDetected = true; } else { emoticonDetected = false; } scope.$emit('clicked-from-directive-emoticon', {emoticonDetected}); }); }; }); </code></pre>
2
Telegram, getting all emoji from sticker pack
<p><strong>Situation</strong></p> <p>I'm writing a Telegram bot. I need to know how many emoji(stickers) in the pack.</p> <p><strong>What found</strong></p> <p>In the telegram <a href="https://core.telegram.org/bots/api#sticker" rel="nofollow">bot api</a> found, that we can get only emoji (and <code>file_id</code>) for sticker.</p> <p>To discover a sticker's <code>file_id</code>:</p> <ol> <li>Send the sticker from Telegram App to bot.</li> <li>Use the bot's <code>getUpdates</code> method to receive the sticker. Receive sticker's <code>file_id</code> in the message.</li> </ol> <p>I.e., it turns out you must send all stickers to bot manualy.</p> <p><strong>Question</strong></p> <p>Some sites(example: <a href="https://vk.com/tstickers" rel="nofollow">1</a>, <a href="http://www.stickerstelegram.com" rel="nofollow">2</a>) extracting stikers preview from stiker pack url: </p> <blockquote> <p><a href="https://telegram.me/addstickers/animals" rel="nofollow">https://telegram.me/addstickers/animals</a></p> </blockquote> <p>Any ideas how to make it automatically?</p>
2
Injecting blueprint bean into camel processor
<p>please help me. How to inject bean declared in blueprint.xml to Camel processor? I am creating OSGI bundle for deployment in Jboss Fuse 6.1 container. My current blueprint.xml:</p> <pre><code> &lt;blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/blueprint" xmlns:camelcxf="http://camel.apache.org/schema/blueprint/cxf" xmlns:cxf="http://cxf.apache.org/blueprint/core" xmlns:jaxws="http://cxf.apache.org/blueprint/jaxws" xsi:schemaLocation=" http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd http://camel.apache.org/schema/blueprint/cxf http://camel.apache.org/schema/blueprint/cxf/camel-cxf.xsd http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd http://cxf.apache.org/blueprint/jaxws http://cxf.apache.org/schemas/blueprint/jaxws.xsd http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd" &gt; &lt;bean id="MyProcessor" class="com.test.MyProcessor" /&gt; &lt;bean id="Sender" class="com.test.Sender" scope="prototype"&gt; &lt;property name="senderId" value="admin" /&gt; &lt;property name="password" value="admin" /&gt; &lt;/bean&gt; &lt;camelContext trace="false" id="blueprintContext" xmlns="http://camel.apache.org/schema/blueprint"&gt; &lt;route&gt; &lt;from uri="activemq:queue:paymentsqueue?username=admin&amp;amp;password=admin" id="NotificationRoute"&gt; &lt;description/&gt; &lt;/from&gt; &lt;log message="The message contains ${body}"/&gt; &lt;process ref="MyProcessor"/&gt; &lt;/route&gt; &lt;/camelContext&gt; &lt;/blueprint&gt; </code></pre> <p>This is camel processor:</p> <pre><code>import org.apache.aries.blueprint.annotation.Inject; public class MyProcessor implements Processor { @Inject private Sender sender; @Override public void process(Exchange x) throws Exception { log.info("test: " +sender.getSenderId()); } </code></pre> <p>But I get NullPointerException. So is it possible to inject bean Sender which created by container into MyProccessor? How it could be done?</p>
2
how to merge matrices in R with different number of rows
<p>I would like to merge several matrices using their row names. These matrices do not have the same number of rows and columns. For instance:</p> <pre><code>m1 &lt;- matrix(c(1, 2, 3, 4, 5, 6), 3, 2) rownames(m1) &lt;- c("a","b","c") m2 &lt;- matrix(c(1, 2, 3, 5, 4, 5, 6, 2), 4, 2) rownames(m2) &lt;- c("a", "b", "c", "d") m3 &lt;- matrix(c(1, 2, 3, 4), 2,2) rownames(m3) &lt;- c("d", "e") mlist &lt;- list(m1, m2, m3) </code></pre> <p>For them I would like to get:</p> <pre><code>Row.names V1.x V2.x V1.y V2.y V1.z V2.z a 1 4 1 4 NA NA b 2 5 2 5 NA NA c 3 6 3 6 NA NA d NA NA 5 2 1 3 e NA NA NA NA 2 4 </code></pre> <p>I have tried to use lapply with the function merge:</p> <pre><code>M &lt;- lapply(mlist, merge, mlist, by = "row.names", all = TRUE) </code></pre> <p>However, it did not work:</p> <blockquote> <p>Error in data.frame(c(1, 2, 3, 4, 5, 6), c(1, 2, 3, 5, 4, 5, 6, 2), c(1, :<br> arguments imply differing number of rows: 3, 4, 2</p> </blockquote> <p>Is there an elegant way to merge these matrices?</p>
2
nginx basic authentication on all pages except a specific URL and it's follow
<p>Am implementing basic authentication on my Ubuntu server. I want to except url and all it follows. example, the url i want to except is sample.com/sample/ and all of it follows like sample.com/sample/1, sample.com/sample/2, sample.com/sample/samdsFFGRwd12, sample.com/sample/FHFEdsa1g65</p> <p>How to make this possible?</p>
2
When to use macros functions in Erlang?
<p>I'm currently following the book <em>Learn You Some Erlang for Great Good</em> by Fred Herbert and one of the sections is regarding Macros.</p> <p>I understand using macros for variables (constant values, mainly), however, I don't understand the use case for macros as functions. For example, Herbert writes:</p> <blockquote> <p><em>Defining a "function" macro is similar. Here's a simple macro used to subtract one number from another:</em></p> </blockquote> <pre><code>-define(sub(X, Y), X-Y). </code></pre> <p>Why not just define this as a function elsewhere? Why use a macro? Is there some sort of performance advantage from the compiler or is this merely just a "<em>this function is so simple, let's just define it in one line</em>" type of thing?</p> <p>I'm not trying to start a debate or preference argument, but after seeing some production Erlang code, I've started noticing lots of macros function usage.</p>
2
deleting a file after uploading to s3 in python
<pre><code>def upload(s): conn=tinys3.Connection("AKIAJPOZEBO47FJYS3OA","04IZL8X9wlzBB5LkLlZD5GI/",tls=True) f = open(s,'rb') z=str(datetime.datetime.now().date()) x=z+'/'+s conn.upload(x,f,'crawling1') os.remove(s) </code></pre> <p>The file is not deleting after i upload to <code>s3</code> it is not deleting in the local directory any alternate solutions?</p>
2
#slack RTM api disconnection following "{}" message in scala
<p>I'm currently experimenting on creating a #slack bot with Scala using the RTM API available.</p> <p>I have managed to get a basic functional bot that responds to a "ping" with a "pong".</p> <p>The issue that I am currently experiencing is that the websocket connection is closed systematically every few minutes after the opening of the stream.</p> <p>I am currently using the following library for the websockets: <a href="https://github.com/jfarcand/WCS" rel="nofollow">https://github.com/jfarcand/WCS</a></p> <p>At this point, I am not entirely sure what is causing the connection drop following the empty JSON message (<code>{}</code>) that is received from the #slack RTM stream.</p> <p>Any help would be greatly appreciated.</p> <p>Here's the relevant connection and listener code:</p> <pre><code>def connect(): Unit ={ if(rec_url == "") slack = ws.open(rtm_url) else { h.debug("Attempting to reconnect") slack = WebSocket().open(rec_url) // TODO: need to completely close the connection before trying to create a new one. } initRTM() } // Initialize Real Time Messaging def initRTM(): Unit = { h.debug("\nOpening Real Time Messaging socket") slack.listener(new TextListener { override def onOpen: Unit = { h.debug("Websocket connection open") status = 1 } override def onClose: Unit = { h.debug("Websocket connection closed, reconnecting...") slack.shutDown status = 0 } override def onError(t: Throwable): Unit ={ h.debug("Websocket Error encountered") t.printStackTrace() h.debug(t.getMessage) } override def onMessage(message: String) { h.debug("Message received: "+message) val body: JsValue = Json.parse(message) try { if(body.as[JsObject].keys.contains("type")){ val m_type = (body \ "type").as[String] m_type match { case "hello" =&gt; ; case "reconnect_url" =&gt; setReconnectUrl((body \ "url").as[String]) case "message" =&gt; processMessage(body) case _ =&gt; h.debug("Unprocessed message type: " + m_type) } } } catch { case e: Exception=&gt; e.printStackTrace() } } }) while(slack.isOpen){ } h.debug("connection is closed") connect() } </code></pre> <p>Here is the output from the console:</p> <pre><code>Opening Real Time Messaging socket INFO - Websocket connection open INFO - Message received: {"type":"hello"} INFO - Message received: {"reply_to":0,"type":"message","channel":"D1NCSAU12","user":"U1NCSAU0L","text":"pong","ts":"1467558776.000079"} INFO - Message received: {"type":"reconnect_url","url":"wss://mpmulti-c6k1.slack-msgs.com/websocket/x4UkvMwZeNqFuyZ_YsxjLNi_OIOzqHisL6sHC3DB0QRnKoG-VH8Qr361SlSprlWb6WjzDhw6j5Pj0FiFFYTjoiCLwM-i863os0xWkjUGJJbUoKUmtlG22e3lTTAFuuIFg2TTI7W-0XfU4HJB2nvbjy_hKCwVQ7uIIlrr6fYi_ms="} INFO - Reconnect URL Set to: wss://mpmulti-c6k1.slack-msgs.com/websocket/x4UkvMwZeNqFuyZ_YsxjLNi_OIOzqHisL6sHC3DB0QRnKoG-VH8Qr361SlSprlWb6WjzDhw6j5Pj0FiFFYTjoiCLwM-i863os0xWkjUGJJbUoKUmtlG22e3lTTAFuuIFg2TTI7W-0XfU4HJB2nvbjy_hKCwVQ7uIIlrr6fYi_ms= INFO - Message received: {"type":"presence_change","presence":"active","user":"U1NCSAU0L"} INFO - Unprocessed message type: presence_change 11:23:18.790 [Hashed wheel timer #1] DEBUG com.ning.http.client.providers.netty.channel.pool.DefaultChannelPool - Closed 0 connections out of 0 in 0ms INFO - Message received: {"type":"user_typing","channel":"D1NCSAU12","user":"U1MP4A19R"} INFO - Unprocessed message type: user_typing INFO - Message received: {"type":"message","channel":"D1NCSAU12","user":"U1MP4A19R","text":"ping","ts":"1467559430.000080","team":"T1MQWNFR8"} INFO - User typed 'ping' INFO - Answer: {"id":0,"type":"message","channel":"D1NCSAU12","text":"pong"} INFO - Message received: {"ok":true,"reply_to":0,"ts":"1467559430.000081","text":"pong"} INFO - Message received: {"type":"user_typing","channel":"D1NCSAU12","user":"U1MP4A19R"} INFO - Unprocessed message type: user_typing INFO - Message received: {"type":"message","channel":"D1NCSAU12","user":"U1MP4A19R","text":"ping","ts":"1467559432.000082","team":"T1MQWNFR8"} INFO - User typed 'ping' INFO - Answer: {"id":1,"type":"message","channel":"D1NCSAU12","text":"pong"} INFO - Message received: {"ok":true,"reply_to":1,"ts":"1467559432.000083","text":"pong"} INFO - Message received: {"type":"user_typing","channel":"D1NCSAU12","user":"U1MP4A19R"} INFO - Unprocessed message type: user_typing INFO - Message received: {"type":"message","channel":"D1NCSAU12","user":"U1MP4A19R","text":"ping","ts":"1467559434.000084","team":"T1MQWNFR8"} INFO - User typed 'ping' INFO - Answer: {"id":2,"type":"message","channel":"D1NCSAU12","text":"pong"} INFO - Message received: {"ok":true,"reply_to":2,"ts":"1467559434.000085","text":"pong"} INFO - Message received: {"type":"user_typing","channel":"D1NCSAU12","user":"U1MP4A19R"} INFO - Unprocessed message type: user_typing INFO - Message received: {"type":"message","channel":"D1NCSAU12","user":"U1MP4A19R","text":"ping","ts":"1467559448.000086","team":"T1MQWNFR8"} INFO - User typed 'ping' INFO - Answer: {"id":3,"type":"message","channel":"D1NCSAU12","text":"pong"} INFO - Message received: {"ok":true,"reply_to":3,"ts":"1467559448.000087","text":"pong"} INFO - Message received: {"type":"user_typing","channel":"D1NCSAU12","user":"U1MP4A19R"} INFO - Unprocessed message type: user_typing INFO - Message received: {"type":"message","channel":"D1NCSAU12","user":"U1MP4A19R","text":"ping ping","ts":"1467559452.000088","team":"T1MQWNFR8"} 11:24:18.889 [Hashed wheel timer #1] DEBUG com.ning.http.client.providers.netty.channel.pool.DefaultChannelPool - Closed 0 connections out of 0 in 0ms INFO - Message received: {"type":"reconnect_url","url":"wss://mpmulti-lbww.slack-msgs.com/websocket/u61Fem7nt3c1DP35C1So6S-Q3QnP0wcY4BeKMG6GZBpjo32E_rGM0YhwH-M_i6uGdezSgzr8R6BmM4eC7ZcwGaAR38GRi2VFyEM7REgtCO0Hd6FAsguHS63TwCI65UwBCkcS_gEFdpoI5tD0az4cBWtdfj1yXbn1iOwpiH_BALg="} INFO - Reconnect URL Set to: wss://mpmulti-lbww.slack-msgs.com/websocket/u61Fem7nt3c1DP35C1So6S-Q3QnP0wcY4BeKMG6GZBpjo32E_rGM0YhwH-M_i6uGdezSgzr8R6BmM4eC7ZcwGaAR38GRi2VFyEM7REgtCO0Hd6FAsguHS63TwCI65UwBCkcS_gEFdpoI5tD0az4cBWtdfj1yXbn1iOwpiH_BALg= 11:25:18.989 [Hashed wheel timer #1] DEBUG com.ning.http.client.providers.netty.channel.pool.DefaultChannelPool - Closed 0 connections out of 0 in 0ms INFO - Message received: {} 11:26:13.918 [New I/O worker #1] DEBUG com.ning.http.client.providers.netty.handler.Processor - Channel Closed: [id: 0x0e0d06c0, /192.168.99.102:46345 :&gt; mpmulti-6wbl.slack-msgs.com/54.172.207.190:443] with attribute NettyResponseFuture{currentRetry=5, isDone=true, isCancelled=false, asyncHandler=com.ning.http.client.ws.WebSocketUpgradeHandler@e9cba57, nettyRequest=com.ning.http.client.providers.netty.request.NettyRequest@b3f8453, content=NettyWebSocket{channel=[id: 0x0e0d06c0, /192.168.99.102:46345 :&gt; mpmulti-6wbl.slack-msgs.com/54.172.207.190:443]}, uri=wss://mpmulti-6wbl.slack-msgs.com/websocket/0WNxIQsK_mzw561vkxWrN4B3tSPO-oBBR6fPtGnD2GLP_47Cms8s8GzyNl8ujheXVnNIw0RygTwglxlZYdfChlNf_0MfCwihOeQMUI-hjgCcwxXuMZFUSYrZphQpu1w7VYP5j3dc0nOVnL0YZX_oi62cgeoaWgwn5GjUiif-0AM=, keepAlive=true, httpHeaders=org.jboss.netty.handler.codec.http.DefaultHttpHeaders@790add3d, exEx=null, redirectCount=0, timeoutsHolder=null, inAuth=false, statusReceived=false, touch=530188604} INFO - Websocket connection closed, reconnecting... 11:26:13.920 [New I/O worker #1] DEBUG com.ning.http.client.providers.netty.channel.ChannelManager - Closing Channel [id: 0x0e0d06c0, /192.168.99.102:46345 :&gt; mpmulti-6wbl.slack-msgs.com/54.172.207.190:443] </code></pre>
2
BLE characteristic changed callback executed only for first change after write
<p>I try to subscribe to BLE characteristic notification using typical approach:</p> <pre><code>stCharacteristic = stService.GetCharacteristics(stCharacteristicGUID)[0]; await stCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); stCharacteristic.ValueChanged += stData_ValueChanged; </code></pre> <p>The callback function has also standard form:</p> <pre><code>async void stData_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args) { var values = (await sender.ReadValueAsync()).Value.ToArray(); } </code></pre> <p>The problem is that the callback is not always called when the BLE device changes characteristic's value. When I write something to the characteristic and the device writes something in reponse, then the callback is called. But if the devices writes to characteristic just by itself the callback is not called. The funny part is that the data are not lost. When I write something again, I get several calls to my callback with all the data sent by the BLE device in meantime. In other words it looks like Windows or .NET Framework caches subsequent incoming data until a write is made. After write only first characteristic change causes callback to be fired.</p> <ul> <li>incoming data - no callback</li> <li>sending data</li> <li>incoming data - two callbacks!</li> <li>sending data</li> <li>incoming data - one callback</li> <li>incoming data</li> <li>incoming data</li> <li>incoming data</li> <li>sending data - three callbacks!</li> </ul> <p>Windows 10, VS2015</p>
2
no supported kernel for GPU devices is available for SparseTensorDenseMatMul_grad
<p>I meet a issue when building a model with <strong>tf.sparse_tensor_dense_matmul</strong> op in my graph. Part of the error info pasted as below,</p> <p>Does that mean there is no GPU kernel support to compute the gradient of "<strong>SparseTensorDenseMatMul_grad</strong>"? I can build the model successfully with "<strong>allow_soft_placement=Ture</strong>" in the session config. However, I need all the computation keep on GPU for some special reason. Does anyone know how to fixed this issue? Or I need to implement the CUDA kernel of this op by myself? Thanks a lot.</p> <pre><code>tensorflow.python.framework.errors.InvalidArgumentError: Cannot assign a device to node 'gradients/softmax_linear/SparseTensorDenseMatMul/SparseTensorDenseMatMul_grad/Slice_1': Could not satisfy explicit device specification '/device:GPU:0' because no supported kernel for GPU devices is available. [[Node: gradients/softmax_linear/SparseTensorDenseMatMul/SparseTensorDenseMatMul_grad/Slice_1 = Slice[Index=DT_INT32, T=DT_INT64, _device="/device:GPU:0"](Placeholder_2, gradients/softmax_linear/SparseTensorDenseMatMul/SparseTensorDenseMatMul_grad/Slice_1/begin, gradients/softmax_linear/SparseTensorDenseMatMul/SparseTensorDenseMatMul_grad/Slice_1/size)]] Caused by op u'gradients/softmax_linear/SparseTensorDenseMatMul/SparseTensorDenseMatMul_grad/Slice_1', defined at: </code></pre>
2
How to fireselectionChanged Event in igCombo only with mouse click?
<p>I am using infragistics combo box. The data is loaded into the combobox after rendering. I have turned on the auto-suggest feature. The problem is that when i start typing in the combobox, selectionChanged event is fired as the first item in the dropdown list is selected automatically. I only want the selectionChanged to be fired when a user selects options from the dropdown using mouse click or by pressing the enter. Following is the my render code for igCombo. </p> <pre><code>searchTextCombo &amp;&amp; searchTextCombo.igCombo({ valueKey: "Value", textKey: "Key", multiSelection: "off", enableClearButton: true, closeDropDownOnSelect: true, virtualization: true, dataSource: configuration.testUrl, showDropDownButton: false, filteringType: "local", filteringCondition: "contains", highlightMatchesMode: "contains", selectionChanged: function (evt, ui) { } }); </code></pre>
2
Memory monitor is disabled in android studio
<p><a href="http://i.stack.imgur.com/OVbT9.png" rel="nofollow">snap of android studio</a></p> <p>I have checked all the options on the list mentioned here on <a href="https://developer.android.com/studio/profile/am-basics.html#byb" rel="nofollow">https://developer.android.com/studio/profile/am-basics.html#byb</a></p> <p>I also have tried to make it work on emulator as well as on device. Nothing seems to work .</p>
2
Intermec printer stopped printing after sending IPL commands
<p>I tried printing a label to an Intermec printer from php using the following code:</p> <pre><code> $cmds .= "&lt;STX&gt;&lt;ESC&gt;C&lt;ETX&gt;"; $cmds .= "&lt;STX&gt;&lt;ESC&gt;P&lt;ETX&gt;"; $cmds .= "&lt;STX&gt;E4;F4;&lt;ETX&gt;"; $cmds .= "&lt;STX&gt;H0;o102,51;f0;c25;h20;w20;d0,30;&lt;ETX&gt;"; $cmds .= "&lt;STX&gt;L1;o102,102;f0;l575;w5;&lt;ETX&gt;"; $cmds .= "&lt;STX&gt;B2;o203,153;c0,0;h100;w2;i1;d0,10;&lt;ETX&gt;"; $cmds .= "&lt;STX&gt;I2;h1;w1;c20;&lt;ETX&gt;"; $cmds .= "&lt;STX&gt;R;&lt;ETX&gt;"; $cmds .= "&lt;STX&gt;&lt;ESC&gt;E4&lt;ETX&gt;"; $cmds .= "&lt;STX&gt;&lt;CAN&gt;&lt;ETX&gt;"; $cmds .= "&lt;STX&gt;RO503C001IP0722RZ001-050&lt;CR&gt;&lt;ETX&gt;"; $cmds .= "&lt;STX&gt;RO503C001IP0722RZ001-050&lt;ETX&gt;"; $cmds .= "&lt;STX&gt;&lt;ETB&gt;&lt;ETX&gt;"; $handle = printer_open("Intermec"); printer_set_option($handle, PRINTER_MODE, "raw"); printer_write($handle,$cmds); printer_close($handle); </code></pre> <p><a href="http://intermec.custhelp.com/app/answers/detail/a_id/416/~/another-sample-ipl-program" rel="nofollow noreferrer">This</a> is the site from which I copied the Intermec Programming Language commands.</p> <p>The script connected to the printer successfully but after running it, <strong>the printer won't print anything, anything at all.</strong> The Printer Monitor keeps showing Syntax Error. </p> <p>Did I do something really wrong? Is there a way to make it print again?</p> <p>I didn't have the inspiration to note down the printer type (I won't have access to it until tomorrow), but it looks exactly like the one in the picture below:</p> <p><a href="https://i.stack.imgur.com/4prQY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4prQY.jpg" alt="enter image description here"></a></p> <p>Please help me, I have no idea what to do...</p>
2
How can I run state.sls from a reactor
<p><strong>TL;DR</strong></p> <p>I want to use the reactor, to call something similar to a simple <code>salt '*' state.sls examplestate</code></p> <hr> <p>I'm new(ish) to saltstack reactors, and I'm having issues with one of the features.</p> <p>In the reactor documents located <a href="https://docs.saltstack.com/en/latest/topics/reactor/" rel="nofollow">here</a>, under "Advanced State System Capabilities", there is the following example:</p> <p><strong>/etc/salt/master.d/reactor.conf</strong></p> <pre><code># A custom event containing: {"foo": "Foo!", "bar: "bar*", "baz": "Baz!"} reactor: - myco/custom/event: - /srv/reactor/some_event.sls </code></pre> <p><strong>/srv/reactor/some_event.sls</strong></p> <pre><code>invoke_orchestrate_file: runner.state.orchestrate: - mods: orch.do_complex_thing - pillar: event_tag: {{ tag }} event_data: {{ data | json() }} </code></pre> <p><strong>/srv/salt/orch/do_complex_thing.sls</strong></p> <pre><code>{% set tag = salt.pillar.get('event_tag') %} {% set data = salt.pillar.get('event_data') %} # Pass data from the event to a custom runner function. # The function expects a 'foo' argument. do_first_thing: salt.runner: - name: custom_runner.custom_function - foo: {{ data.foo }} # Wait for the runner to finish then send an execution to minions. # Forward some data from the event down to the minion's state run. do_second_thing: salt.state: - tgt: {{ data.bar }} - sls: - do_thing_on_minion - pillar: baz: {{ data.baz }} - require: - salt: do_first_thing </code></pre> <p>In this example, assuming that I'm following it correctly, the reactor <code>event</code> sets off the <code>some_event.sls</code> located in the reactor directory. The <code>some_event.sls</code> then uses runner.state.orchestrate to run <code>do_complex_thing.sls</code>.</p> <p>What I'm trying to do is very similar but I've been unable to make it work. I'd like to have the reactor <code>event</code> set off <code>some_event.sls</code>. In some_event.sls I'd just like it to call a state that I've written. For example, a simple state that uses file.managed to move a file from the master, to the minion. I've attempted this below:</p> <p><strong>/etc/salt/master.d/reactor.conf</strong></p> <pre><code>reactor: - 'salt/netapi/hook/test': - /srv/reactor/testdirectory/configure.sls </code></pre> <p><strong>/srv/reactor/testdirectory/configure.sls</strong></p> <pre><code>{% set postdata = data.get('post', {}) %} {% if grains['os_family']=="Debian" %} testifthisworks: salt.state: - mods: transferfile.init - tgt: {{ postdata.tgt }} {% endif %} </code></pre> <p><strong>/srv/salt/transferfile/init.sls</strong></p> <pre><code>/root/testfile.txt: file.managed: - source: salt://testfiles/testfile.txt - makedirs: True - mode: 700 - template: jinja </code></pre> <p>In the configure.sls file, I'm trying to use salt.state to kick off the state.sls, this isn't working with the error <code>"ReactWrap" object has no attribute salt</code></p> <p>When I try to do the same thing, but using the runner.state.orchestrate from the original example (I dont need orchestrate), it works, but it moves the file to /root/ on my master.</p> <p>I'm not sure what I can use other than salt.state to just run state.sls. Any help is appreciated.</p>
2
Google Chrome Dev Tools: Padding vs Margin
<p>Can someone explain why padding and margins make Google Chrome Dev Tools report a different width for content.</p> <p>Here's an example:</p> <p>HTML</p> <pre><code>&lt;div class="box"&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>// Dev Tools reports the DIV has a width of 320px .box { padding: 10px; } // BUT here Dev Tools reports the DIV has a width of 300px .box { margin: 10px; } </code></pre>
2
How to copy strings from StringList to multiple Memos
<p>i have a text file and 10 StringLists, i want to open the txt files in the 10 StringLists, for example the text file has 1000 line, i want the first 100 line in StringList1 and the second 100 in StringLists2 and so on, my idea is to get text file lines count and divide it by 10 then copy each 100 in the 10 StringLists</p> <pre><code>var i, x :integer; U : TStrings; DatFile ,ExePath:string; begin U := TStringList.Create; ExePath := ExtractFilePath(Application.ExeName); DatFile := ExePath + 'Test.txt'; U.LoadFromFile(DatFile); x := U.Count Div 10; Edit1.Text := IntToStr(x); /// Stoped here end; </code></pre> <p>how to continue this?</p>
2
Get json data from a posted URI in postman in java
<p>I have been trying to get <code>JSON</code> data but it seems I am using the wrong syntax. What syntax is appropriate? This is my code</p> <pre><code>@Path("/jsondata") @POST @Consumes("application/json") @Produces("application/json") public JSONObject personal(@JSONParam("")JSONObject json) throws JSONException{ String name = json.getString("name"); String age = json.getString("age"); String msg = "You entered two things"; String doc = "{\"name\":\""+name+"\",\"age\":\""+age+"\",\"msg\":\""+msg+"\"}"; JSONObject outJson = new JSONObject(doc); return outJson; } </code></pre> <p>Am getting error on the fifth line at <code>@JSONParam</code>. What should i do. And how do I get the name and age from the json</p>
2
Replacing a label's text if there's a nested input element
<p>Changing the text of a label seems <a href="https://stackoverflow.com/questions/3584145">easy</a>:</p> <pre class="lang-js prettyprint-override"><code>var /**HTMLLabelElement*/ label = ...; label.innerHTML = "..."; </code></pre> <p>or, using <em>jQuery</em>:</p> <pre class="lang-js prettyprint-override"><code>var /**HTMLLabelElement*/ label = ...; $(label).text("..."); </code></pre> <p>Neither of the above works correctly if the label wraps the <code>&lt;input/&gt;</code> element:</p> <pre class="lang-html prettyprint-override"><code>&lt;label&gt;&lt;input type="checkbox"&gt;Text&lt;/label&gt; </code></pre> <p>-- in this case, the <code>&lt;input/&gt;</code> element is replaced along with the old text. </p> <p>How do I change just the text of a label, without affecting its child elements?</p>
2
Java Try-with-resource storing input stream in Map
<p>In my API (Spring boot) I have an endpoint where users can upload multiple file at once. The endpoint takes as input a list of <code>MultipartFile</code>.</p> <p>I wish not to directly pass this <code>MultipartFile</code> object to the service directly so I loop through each <code>MultipartFile</code> and create a simple map that stored the filename and its <code>InputStream</code>.</p> <p>Like this:</p> <pre><code>for (MultipartFile file : files) { try (InputStream is = multipartFile.getInputStream()) { filesMap.put(file.getOriginalFilename(), is); } } service.uploadFiles(filesMap) </code></pre> <p>My understanding for Java streams and streams closing is quite limited. I thought that <code>try-with-resources</code> automatically closes the <code>InputStream</code> once the code reached the end of the try block.</p> <p>In the above code when does exactly the the <code>multipartFile.getInputStream()</code> gets closed? </p> <p>The fact that I'm storing the stream in a map will that cause a memory leak?</p>
2
Firebase Notification Line break
<p>Can I know how to put a new line or line break in Firebase Notification body parameter? The notification from the phone shown as:</p> <pre> Title: Title 1 Author: Author 1 </pre> <p>What I expected was: </p> <pre> Title: Title 1 Author: Author 1 </pre> <p>Any clue on this? Below is the code, I have tried with \n \n \n\r, but they are not working at all.</p> <pre><code>JSONObject body = new JSONObject(); body.put("body", "Title: Title 1\n" + "Author: Author 1"); </code></pre>
2
Cannot access element's style.height in JS
<p>I'm trying to modify an elements height (elementTwo) using another element's height (elementOne) using JS (<strong>No jQuery)</strong></p> <p>When I try logging elementOne.style.height, I get an empty string Using Safari and Chrome inspector's I can see the computed height but cannot access it using JS. It shows up as faded (See screenshots)</p> <p><a href="http://i.stack.imgur.com/bZMga.png" rel="nofollow">Screenshot of Safari inspector</a> | <a href="http://i.stack.imgur.com/97xnr.png" rel="nofollow">Screenshot of Chrome inspector</a></p> <pre><code>.elementOne { min-height: 100vh; width:100%; } </code></pre> <p>ElementOne has a min-height set to be 100vh but automatically increases in size based on the device / size of child elements. It does not have a height set. ElementTwo does not have any css by default</p> <p>I am trying to do this using JS only and <strong>do not want to use jQuery</strong> at all.</p>
2
How to handle upload File in Plone using plone.api create and NamedBlobFile
<p>Dears,</p> <p>I have been create a script to read a txt and do a upload in Plone site (Plone 4.3.10). The script is here: <a href="https://stackoverflow.com/questions/38351633/script-python-using-plone-api-to-create-file-appear-error-wrongtype-when-set-a-f">Script Python using plone.api to create File appear error WrongType when set a file</a></p> <p>I use a tip described by MrTango: <a href="https://stackoverflow.com/questions/29408529/save-file-to-plone-site-using-python/29410325#29410325">Save file to plone site using python</a></p> <p>My difficulty is attach the file into a new item created in begin of FOR, specifically in the following passage:</p> <pre><code> file_obj.file = NamedBlobFile( data=open(pdf_path, 'r').read(), contentType='application/pdf', filename=unicode(file_obj.id, 'utf-8'), ) </code></pre> <p>The parameter "data", receave file PDF from filesystem, but, don't set up file in a new object, newly created.</p> <p>Thank You for your attention!</p> <p><strong>[UPDATE]</strong></p> <p>Using pdb, I saw some outputs, data, contentType n filename is apparently setted up correct.</p> <p>So, Where I went wrong? Or what kind type is input of data? <em>I ain't expert python programmer... like you see...</em> If someone used plone.api and upload pdf to plone, how you did it?</p> <pre><code> 36 pdf_path, 37 filename=unicode(file_obj.id, 'utf-8'), 38 ) 39 print('\n \n Criado: '+row['NDOPROCESSO']+'.') 40 transaction.commit() 41 42 pdf_file.close() 43 -&gt; break 44 csvfile.close() 45 (Pdb) file_obj.file.data 'INMEQ/PastaGeral/PROCESSOINMEQ-AL.PDF' (Pdb) file_obj.file.contentType 'application/pdf' (Pdb) file_obj.file.filename u'processoinmeq-al.pdf' </code></pre> <p><strong>[UPDATE 2]</strong></p> <p>@Mathias, first thks, you're great!</p> <p>My O.S. is:</p> <pre><code>jaf@ocs:~/plone4310/zinstance$ uname -a Linux ocs 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU/Linux </code></pre> <p>Look my attempt:</p> <pre><code>jaf@ocs:~/plone4310/zinstance$ bin/instance -O a debug Starting debugger (the name "app" is bound to the top-level Zope object) &gt;&gt;&gt; plone = app.a &gt;&gt;&gt; plone &lt;PloneSite at /a&gt; &gt;&gt;&gt; from zope.component.hooks import setSite &gt;&gt;&gt; setSite(plone) &gt;&gt;&gt; from plone import api &gt;&gt;&gt; pdfpath = 'INMEQ/PastaGeral/PROCESSOINMEQ-AL.PDF' #I tried too with a full path, like you see in image print below #'/home/jaf/plone4310/zinstance/INMEQ/PastaGeral/PROCESSOINMEQ-AL.PDF' &gt;&gt;&gt; pdfpath 'INMEQ/PastaGeral/PROCESSOINMEQ-AL.PDF' &gt;&gt;&gt; obj = api.content.create(type='File', title='a file', container=plone) &gt;&gt;&gt; obj &lt;ATFile at /a/a-file&gt; #unique difference, between you and me, is ATFile not File. &gt;&gt;&gt; obj.id 'a-file' &gt;&gt;&gt; file_ = plone.get(obj.id) &gt;&gt;&gt; file_ &lt;ATFile at /a/a-file&gt; &gt;&gt;&gt; file_ = plone.get('a-file') &gt;&gt;&gt; file_ &lt;ATFile at /a/a-file&gt; &gt;&gt;&gt; from plone.namedfile.file import NamedFile &gt;&gt;&gt; pdf = open(pdfpath, 'r') &gt;&gt;&gt; pdf &lt;open file 'INMEQ/PastaGeral/PROCESSOINMEQ-AL.PDF', mode 'r' at 0x7f41b7b48030&gt; &gt;&gt;&gt; file_.file = NamedFile(data=pdf, filename=unicode(obj.id, 'utf-8'), contentType='application/pdf') &gt;&gt;&gt; file_.file &lt;plone.namedfile.file.NamedFile object at 0x7f41b7b42500&gt; &gt;&gt;&gt; import transaction &gt;&gt;&gt; transaction.commit() &gt;&gt;&gt; file_.file &lt;plone.namedfile.file.NamedFile object at 0x7f41b7b42500&gt; &gt;&gt;&gt; </code></pre> <p>The local of files: <a href="https://i.stack.imgur.com/wXeEp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wXeEp.png" alt="Image Print"></a></p> <p>And after transaction.commit(), we have it.</p> <p><a href="https://i.stack.imgur.com/8YtGX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8YtGX.png" alt="Plone Site with empty File after commit."></a></p> <p><strong>[UPDATE 3 - AND WORKS]</strong></p> <p>With the SUPER HELP of @Mathias, the script python for upload <code>File</code> Archetypes from txt and separation with semicolon.</p> <pre><code>from zope.site.hooks import setSite from plone import api import transaction import csv import os local_path = '/path_to_plone_instace/plone4310/zinstance' scan_path = 'path_with_txt_and_PDFs' geral_path = 'folder_with_pdf_only' txt_name = 'file_with_content.txt' plone_site = 'plone_site' plone_site_pasta = 'folder_upload_in_plone' portal = app[plone_site] setSite(portal) container = portal[plone_site_pasta] with open(os.path.join(local_path, scan_path, txt_name), 'rb') as csvfile: reader = csv.DictReader(csvfile, delimiter=';', quotechar='|') for row in reader: pdf_id = str(row['PDF_ID']) pdf_file = open(os.path.join(local_path, scan_path, geral_path, str(pdf_id)), 'r') file_obj = api.content.create( container=container, type='File', title=str(row['PDF_TITLE']), description=str(row['PDF_DESCRIPTION']), safe_id=True, excludeFromNav=True ) file_ = container.get(file_obj.id) file_.setFile(pdf_file) if int(file_obj.getFile().size()) &lt;= 0: print str(file_obj.id) + ', Empty FILE!!! size: ' + str(file_obj.getFile().size()) else: print str(file_obj.title) + ', success created, with size: ' + str(file_obj.getFile().size()) transaction.commit() csvfile.close() </code></pre>
2
spring-boot dependencies and security fixes
<p>im using spring boot in a recommended way, that is by adding</p> <pre><code>classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") </code></pre> <p>and then adding dependencies i need, like:</p> <pre><code>compile('org.springframework.boot:spring-boot-starter-web') </code></pre> <p>That dependency pulls some predefined version of tomcat that will host my microservice. </p> <p>but what happens when there is a security fix for tomcat released? does spring team track all the security issues in all the project they use and bump spring-boot version when new fix is released? or do i have to track it by myself and control dependencies (like tomcat) manually instead of using 'the spring-boot way'?</p>
2
How to change the Location of the JDK in Android studio
<p>I tried to change the location by the following way</p> <p>Project Structure > SDK location > JDK Location > ...</p> <p>But it always reverts to the old address saved in it.</p> <p>It's not saving the new location entered in it. </p> <p>Please help me to solve this issue</p> <p><a href="https://i.stack.imgur.com/L1yUL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L1yUL.png" alt="enter image description here"></a></p>
2
how to hide connection string from a web query in excel
<p>I need to send reports to clients. The report is generated in excel via web query. The draw back is everyone has access to the excel, can see the connection string, which could be used for unauthorized access to other reports. I am considering to add password using VBA. Is there any way that I can remove/hide the connection string from connection->property? </p>
2
Can't change layout params of Nestedscrollview Dynamically (android)
<p>I want to change the height of a <code>NestedScrollView</code> dynamically. but i am getting <code>FATAL error</code>. basically this is a <em>bottomsheet</em>, and i want to change the height before it is in <code>STATE_EXPANDED</code>.</p> <p><strong><em>My Java Code :</em></strong></p> <pre><code>bottomsheet_nestedscrollview = (NestedScrollView) findViewById(R.id.bottom_sheet_landing_screen); NestedScrollView.LayoutParams params = (NestedScrollView.LayoutParams) bottomsheet_nestedscrollview.getLayoutParams(); params.height = bottom_relativeLayout.getHeight(); bottomsheet_nestedscrollview.setLayoutParams(params); </code></pre> <p><strong><em>My layout is :</em></strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.csm.hptcp.hptcpmobileapp.Landing_Screen"&gt; &lt;include layout="@layout/content_landing__screen" /&gt; &lt;android.support.v4.widget.NestedScrollView android:id="@+id/bottom_sheet_landing_screen" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/holo_orange_light" android:clipToPadding="true" app:layout_behavior="android.support.design.widget.BottomSheetBehavior"&gt; &lt;include layout="@layout/landing_screen_bottomsheet" /&gt; &lt;/android.support.v4.widget.NestedScrollView&gt; &lt;android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="@dimen/fab_margin" android:src="@android:drawable/ic_dialog_email" app:layout_anchor="@id/bottom_sheet_landing_screen" app:layout_anchorGravity="top|center" /&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre> <p><strong><em>Logcat :</em></strong></p> <pre><code>FATAL EXCEPTION: main Process: com.csm.hptcp.hptcpmobileapp, PID: 16854 java.lang.ClassCastException: android.support.design.widget.CoordinatorLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams </code></pre> <p><em>Do anyone have a suggestion ?</em></p>
2
PortfolioAnalytics Error with function gmv_opt
<p>I have below script which creates an error. Does anyone know how to solve this. I'm running the latest version of R &amp; RStudio, and all packages are up to date. </p> <pre><code>library('quantmod') library('PortfolioAnalytics') library('PerformanceAnalytics') ETF_Names &lt;- c("IVV","IJH","IWM","EZU","EEM","SCZ","ILF","EPP") ETF_All &lt;- lapply(ETF_Names, function(x) getSymbols(x,from="2006-01-01",auto.assign = FALSE)) names(ETF_All) &lt;- ETF_Names ETF_MR &lt;- do.call(merge,lapply(ETF_All,monthlyReturn)) colnames(ETF_MR) &lt;- ETF_Names ETF_spec &lt;- portfolio.spec(assets = colnames(ETF_MR)) ETF_spec &lt;- add.constraint(portfolio=ETF_spec, type="full_investment") ETF_spec &lt;- add.constraint(portfolio=ETF_spec, type="box", min=0, max=1) ETF.ef &lt;- create.EfficientFrontier(R=ETF_MR['2015'], portfolio=ETF_spec, type="mean-StdDev") </code></pre> <p>Below the Error message:</p> <pre><code>Error in gmv_opt(R = R, constraints = constraints, moments = moments, : No solution found: Error in UseMethod("as.constraint") : no applicable method for 'as.constraint' applied to an object of class "c('matrix', 'list')" </code></pre> <p>There have never been issues before (I just recently updated RStudio and the relevant packages). And that is when the error popped up. </p> <p>Hope someone can help</p>
2
Installer waiting when EXE is run as custom action during installation
<p>I am installing Mosquitto using WIX and once the files are copied I'm trying to run the mosquitto.exe using a custom action. It launches a new command prompt and the installation pauses there. It resumes only when I terminate that command prompt. Below is my code.</p> <pre><code>&lt;Feature Id="ProductFeature" Title="MosquittoInstaller" Level="1"&gt; &lt;ComponentGroupRef Id="MosquittoFilesGroup"/&gt; &lt;/Feature&gt; &lt;InstallExecuteSequence&gt; &lt;Custom Action="RunMosquitto" Before="InstallFinalize" /&gt; &lt;/InstallExecuteSequence&gt; &lt;Directory Id="TARGETDIR" Name="SourceDir"&gt; &lt;Directory Id="INSTALLLOCATION"&gt; &lt;Directory Id="KubeInstallDir" Name="Kube2.0"&gt; &lt;Directory Id="MyProgramDir" Name="Mosquitto" /&gt; &lt;/Directory&gt; &lt;/Directory&gt; &lt;/Directory&gt; &lt;CustomAction Id='RunMosquitto' FileKey="fil7D28AEF774656849395A2FA20A5C963D" Execute="deferred" ExeCommand='-v' Return="check" HideTarget="no" Impersonate="no"/&gt; </code></pre> <p>What am I doing wrong here? Please advice.</p>
2
Splunk: Different color on one bar-graph
<p>In my application i am trying display logs from logger.<br> So my source structure:<br></p> <p><code>Application</code> - application name <br> <code>Interface</code> - logger name <br> <code>Level</code> - log level <br></p> <p>My search query :<br></p> <pre><code>index="log_index" sourcetype=log_source | eval logger = Application + ":" + Interface + " - " + Level | eval error= if(Level == "Error", 1, 0) | eval warn= if(Level == "Warn", 1, 0) | eval info= if(Level == "Info", 1, 0) | eval fatal= if(Level == "Fatal", 1, 0) | search fatal=1 OR error=1 OR warn=1 OR info=0 | stats count(Level) by logger sort by count(Level) desc </code></pre> <p>I set my options as:</p> <pre><code>&lt;option name="charting.axisLabelsX.majorLabelStyle.overflowMode"&gt;ellipsisNone&lt;/option&gt; &lt;option name="charting.axisLabelsX.majorLabelStyle.rotation"&gt;0&lt;/option&gt; &lt;option name="charting.axisTitleX.visibility"&gt;visible&lt;/option&gt; &lt;option name="charting.axisTitleY.visibility"&gt;visible&lt;/option&gt; &lt;option name="charting.axisTitleY2.text"&gt;title&lt;/option&gt; &lt;option name="charting.axisTitleY2.visibility"&gt;visible&lt;/option&gt; &lt;option name="charting.axisX.scale"&gt;linear&lt;/option&gt; &lt;option name="charting.axisY.scale"&gt;linear&lt;/option&gt; &lt;option name="charting.axisY2.enabled"&gt;0&lt;/option&gt; &lt;option name="charting.axisY2.scale"&gt;inherit&lt;/option&gt; &lt;option name="charting.chart"&gt;bar&lt;/option&gt; &lt;option name="charting.chart.bubbleMaximumSize"&gt;500&lt;/option&gt; &lt;option name="charting.chart.bubbleMinimumSize"&gt;10&lt;/option&gt; &lt;option name="charting.chart.bubbleSizeBy"&gt;area&lt;/option&gt; &lt;option name="charting.chart.nullValueMode"&gt;gaps&lt;/option&gt; &lt;option name="charting.chart.showDataLabels"&gt;minmax&lt;/option&gt; &lt;option name="charting.chart.sliceCollapsingThreshold"&gt;0.01&lt;/option&gt; &lt;option name="charting.chart.stackMode"&gt;default&lt;/option&gt; &lt;option name="charting.chart.style"&gt;shiny&lt;/option&gt; &lt;option name="charting.drilldown"&gt;all&lt;/option&gt; &lt;option name="charting.layout.splitSeries"&gt;1&lt;/option&gt; &lt;option name="charting.layout.splitSeries.allowIndependentYRanges"&gt;0&lt;/option&gt; &lt;option name="charting.legend.labelStyle.overflowMode"&gt;ellipsisMiddle&lt;/option&gt; &lt;option name="charting.legend.placement"&gt;right&lt;/option&gt; &lt;option name="charting.chart"&gt;column&lt;/option&gt; &lt;option name="charting.chart.stackMode"&gt;stacked&lt;/option&gt; &lt;option name="charting.fieldColors"&gt;{"error":0xFF0000,"warn":0xFFFF00, "info":0x73A550, "fatal": 0x000000}&lt;/option&gt; &lt;option name="charting.seriesColors"&gt;[0xFF0000,0xFFFF00,0x00FF00, 0x000000]&lt;/option&gt; </code></pre> <p>My aim: I would like to match bar color to level for each logger (application plus interface plus level). So bar with level fatal should be red, error black etc etc.</p> <p>I hope someone of you will know how to configure that tool.</p>
2
What is IDA and how does it help me view .so files?
<p>So I'm reverse engineering an Android app and looking for a string that I know is inside the app, somewhere.</p> <p>I've decompiled the app.</p> <p>I've done a search for the string in all files, looking for the string, but nothing is returned.</p> <p>I was told to use "IDA" to view all of the files with ".so" extension.</p> <p>What is IDA? Am I going about this right?</p>
2
Migrating a JavaScript\Ionic\Angular 1 App to Typescript\Ionic 2\Angular 2 App
<p>I'm working on migrating an App from JavaScript\Ionic\Angular1 to Typescript\Ionic2\Angular2 one file at a time. I've poured over dozens of how-to's and such about migrating from one to the other, done the Angular 2 quick start and tutorial, and seen how to go from .js to .ts as well as installed all of the npm packages I need. Assuming I have everything I need to start the migration process, I really need help actually starting. I have dozens of files to convert, and it would help me greatly to just get one file converted correctly with the old code commented out to use as a reference to convert the others. </p> <p>Here is a sample file. If you could convert this for me, or walk me through converting it, I would be very appreciative. </p> <pre><code>angular.module('myApp.app', ['ionic']) .controller('myApp.app', function($rootScope, $scope, AService, BService, CService){ $scope.setUserName = function (user){ $scope.user = user; }; document.addEventListener('deviceready', function() { $rootScope.$on('$cordovaNetwork:online', function (e, nState) { BService.setOnline(true); }) }) }) </code></pre> <p>Thank you.</p>
2
Spring Webflow action-state else
<p>I have a problem with a webflow action-state. The structure I want is: <em>if...else if....else if .....else</em></p> <p>In my action state (see below), </p> <ul> <li>I call getTestTypeName();</li> <li>This method returns a string. There could be ten valid values although currently there are only two. </li> <li>However, I may also get an invald String which is not an error but needs to be sent to a specified view-state.</li> <li>How do I do this. Currently, I get an error</li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;action-state id="selectPostITSAction"&gt; &lt;evaluate expression="testEntranceViewService.getTestTypeName(flowScope.vwUser)" /&gt; &lt;transition on="ProgramChoiceTemplate" to="paymentGateway" /&gt; &lt;transition on="CPCFeedbackTemplate" to="report" &gt; &lt;evaluate expression="testEntranceViewService.reactivateTestOnHold(vwUser, flowRequestContext)" result="flowScope.vwUser" /&gt; &lt;/transition&gt; &lt;transition on="error" to="entry" /&gt; &lt;/action-state&gt;</code></pre> </div> </div> </p> <p>"Prototype Test Template1467832258812" is an invalid option but I cannot handle with webflow. I get this error is </p> <blockquote> <p>ExceptionNo transition was matched on the event(s) signaled by the [1] action(s) that executed in this action state 'selectPostITSAction' of flow 'flow-entry'; transitions must be defined to handle action result outcomes -- possible flow configuration error? Note: the eventIds signaled were: 'array['Prototype Test Template1467832258812']', while the supported set of transitional criteria for this action state is 'array[ProgramChoiceTemplate, CPCFeedbackTemplate, error]'org.springframework.webflow.engine.NoMatchingTransitionException</p> </blockquote>
2
QDirModel setNameFilters hides folders
<p>I want to have a <code>QDirModel</code> that contains both folders and files (so I am using <code>AllEntries</code>).</p> <p>The problem is that when I am calling <code>setNameFilters()</code> on my <code>QDirModel</code>, I'll loose all the folders. Is there any way that I can exclude folders from filtering?</p> <p>Thank you.</p>
2
correlation matrix of one dataframe with another
<p>I was reading through the answers to <a href="https://stackoverflow.com/questions/38422001/pandas-dataframe-corrwith-method">this question</a>. Then question came up on how to calculate the correlations of all columns from one dataframe with all columns from the other dataframe. Since it seemed this question wasn't going to get answered, I wanted to ask it as I need something just like that.</p> <p>So say I have dataframes <code>A</code> and <code>B</code>:</p> <pre><code>import pandas as pd import numpy as np A = pd.DataFrame(np.random.rand(24, 5), columns=list('abcde')) B = pd.DataFrame(np.random.rand(24, 5), columns=list('ABCDE')) </code></pre> <p>how do I get a dataframe that looks like this:</p> <pre><code>pd.DataFrame([], A.columns, B.columns) A B C D E a NaN NaN NaN NaN NaN b NaN NaN NaN NaN NaN c NaN NaN NaN NaN NaN d NaN NaN NaN NaN NaN e NaN NaN NaN NaN NaN </code></pre> <p>But filled with the appropriate correlations?</p>
2
How to find the difference, mean, sum between all pairs of rows in pandas dataframe?
<p>I have the following pandas DataFrame.</p> <pre><code>import pandas as pd df = pd.read_csv('filename.csv') print(df) dog A B C 0 dog1 0.787575 0.159330 0.053095 1 dog10 0.770698 0.169487 0.059815 2 dog11 0.792689 0.152043 0.055268 3 dog12 0.785066 0.160361 0.054573 4 dog13 0.795455 0.150464 0.054081 5 dog14 0.794873 0.150700 0.054426 .. .... 8 dog19 0.811585 0.140207 0.048208 9 dog2 0.797202 0.152033 0.050765 10 dog20 0.801607 0.145137 0.053256 11 dog21 0.792689 0.152043 0.055268 .... </code></pre> <p>I want to find the absolute difference of <code>A</code> between all rows. How does one do this (keeping in mind the data grows very quickly)? </p> <p>One way to "pair" the data is to try:</p> <pre><code>df1 = df.set_index("dog") from itertools import combinations cc = list(combinations(df,2)) out = pd.DataFrame([df1.loc[c,:].sum() for c in cc], index=cc) </code></pre> <p>However, this is only summing. How do you do multiple operations? </p>
2
jackson - ignoring case in snake case keys
<p>I have a requirement to receive JSON with keys that contain underscore and even ignore the case in words. For e.g. Device_control_API, device_control_API, Device_Control_API, device_control_aPI etc all should map to same property.</p> <p>Now I know that I can create multiple setter methods using @JsonSetter with all combinations possible, but I don't think that will be good. </p> <p>I have seen other questions which suggest using <code>mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)</code> for ObjectMapper object to ignore case, but I can't do that because I am using spring-boot and want my REST API to get payload in the form POJO object.</p> <p>Is there any annotation or some way to do so </p> <p>Please help !!!</p>
2
RxJS Angular 2 Syntax
<p>I am currently doing some reading on the RxJS libraries and taking some time to go through some of the classes offered by some of its architects and contributors with the goal of incorporating this knowledge into an angular2 application. I am finding it difficult though because I can't seem to figure out how to change the syntax so I can use RxJS like i am seeing in any of the examples that aren't angular2 specific. For instance, if I try to create an observer in a constructor: </p> <pre><code>this.$mouseObserver = Rx.Observer.create( function (x) { console.log('Next: %s', x); }, function (err) { console.log('Error: %s', err); }, function () { console.log('Completed'); }); </code></pre> <p>Rx always comes up undefined, even after importing it. Observer and Observable import fine, as well as the methods for them. Am i missing something basic? Every piece of documentation for RxJS starts almost everything with <code>Rx.</code> but I haven't seen a single Angular 2 tutorial that uses that syntax.</p>
2
Wordpress: Resize $term attachment using url
<p>I've submitted this question into Wordpress Section without success for the moment. The question can be found <a href="https://wordpress.stackexchange.com/questions/232340/resize-term-attachment-using-url">here</a>.</p> <p>I'm using this plugin for attaching an image to a custom taxonomy. The plugin's function returns the attached term's image as following:</p> <pre><code>function get_wp_term_image($term_id){ return get_option('_category_image'.$term_id); } </code></pre> <p><strong>EDIT</strong>: <code>get_wp_term_image($term_id)</code> returns the image's url.</p> <p>It works fine but I'd like to resize the returned image because I'm using it in a page displaying all taxonomy categories with relative thumbs. It means that if you upload a big image you get that and the page becomes very heavy to load. I've tried to add this hook without success, in my page loop:</p> <pre><code>$term_id = $term-&gt;term_id; if (function_exists('get_wp_term_image')) { $meta_image = get_wp_term_image($term_id); //tried this $term_image = wp_get_attachment_image_src($term_id, 'smalltax'); //and this $image_id = attachment_url_to_postid($meta_image); //no success } </code></pre> <ul> <li>In the first case I've assumed that <code>wp_get_attachment_image_src</code> hook considers the attachment from whatever id but I was wrong. <strong>NB.</strong> I don't have the image ID, I have the <code>image url</code> and the <code>term_id</code></li> <li>In the second case I've thought to get the $image_id with the <code>attachment_url_to_postid</code> hook and then resize with some other tweaking.</li> </ul> <p>Can you provide a solution? Even helping to modify the plugin itself. Thanks!</p>
2
Django Admin how to change text in relations field
<p>I have the following code:</p> <p>models.py</p> <pre><code>from django.db import models from parler.models import TranslatableModel, TranslatedFields class Federation(TranslatableModel): translations = TranslatedFields( name = models.CharField('name', max_length=50) ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Athlete(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) federation = models.ForeignKey('Federation', on_delete=models.SET_NULL, null=True) height = models.IntegerField(); weight = models.IntegerField(); created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) </code></pre> <p>admin.py</p> <pre><code>from django.contrib import admin from parler.admin import TranslatableAdmin from .models import Athlete, Federation class AthleteAdmin(admin.ModelAdmin): list_display = ['first_name', 'last_name', 'height', 'weight', 'get_federation_name'] fields = ['first_name', 'last_name', 'height', 'weight', 'federation'] def get_federation_name(self, obj): obj.federation.set_current_language('en') return obj.federation.name get_federation_name.short_description = 'Federation' class FederationAdmin(TranslatableAdmin): search_fields = ['translations__name'] list_display = ['name'] fields = ['name'] admin.site.register(Federation, FederationAdmin) admin.site.register(Athlete, AthleteAdmin) </code></pre> <p>The federation field is shown as a list but the text in the select menu is shown as "Federation object." For the list, I created a function to fetch the data from related Federation model's translation relation. I want to do the same with the form fields. If I get this to work in form fields without a function, I will also change the list display to work the same way.</p> <p>I am new to Python and Django (first time) and I can't seem to find a solution to this problem.</p> <p>Thank you!</p>
2
Set VoiceOver to ignore placeholder text in UITextField?
<p>I have a UITextField for the user to enter their phone number. The placeholder text for the field is (XXX) XXX-XXXX. For sighted users, this works great, but with VoiceOver turned on, it sounds pretty bad to just read out all the X's. </p> <p>I have accessibilityLabel set to "Phone Number" and accessibilityHint set to "Requires 10-digit phone number". Right now, VoiceOver will read the label, then placeholder text, then the hint. Is it possible to set VoiceOver to ignore the placeholder text?</p>
2
(cv2,capture) object is not callable
<p>Basically, this code will detect object's motion in the scene. When the motion is detected, a red rectangle frame will track the object's motion. But, I added a new function into the code which is frame differencing. In general it is thresholding. When i run the code it says:"cv2.capture" object is not callable.</p> <pre><code>import cv2.cv as cv class Target: def __init__(self): self.capture = cv.CaptureFromCAM(0) cv.NamedWindow("Target", 1) def run(self): # Capture first frame to get size ret, current_frame = self.capture() previous_frame = current_frame frame = cv.QueryFrame(self.capture) frame_size = cv.GetSize(frame) color_image = cv.CreateImage(cv.GetSize(frame), 8, 3) grey_image = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 1) moving_average = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_32F, 3) first = True while True: current_frame_gray = cv2.cvtColor(current_frame,cv2.COLOR_BGR2GRAY) previous_frame_gray = cv2.cvtColor(previous_frame, cv2.COLOR_BGR2GRAY) frame_diff = cv2.absdiff(current_frame_gray,previous_frame_gray) closest_to_left = cv.GetSize(frame)[0] closest_to_right = cv.GetSize(frame)[1] color_image = cv.QueryFrame(self.capture) # Smooth to get rid of false positives cv.Smooth(color_image, color_image, cv.CV_GAUSSIAN, 3, 0) if first: difference = cv.CloneImage(color_image) temp = cv.CloneImage(color_image) cv.ConvertScale(color_image, moving_average, 1.0, 0.0) first = False else: cv.RunningAvg(color_image, moving_average, 0.020, None) # Convert the scale of the moving average. cv.ConvertScale(moving_average, temp, 1.0, 0.0) # Minus the current frame from the moving average. cv.AbsDiff(color_image, temp, difference) # Convert the image to grayscale. cv.CvtColor(difference, grey_image, cv.CV_RGB2GRAY) # Convert the image to black and white. cv.Threshold(grey_image, grey_image, 70, 255, cv.CV_THRESH_BINARY) # Dilate and erode to get people blobs cv.Dilate(grey_image, grey_image, None, 18) cv.Erode(grey_image, grey_image, None, 10) storage = cv.CreateMemStorage(0) contour = cv.FindContours(grey_image, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE) points = [] while contour: bound_rect = cv.BoundingRect(list(contour)) contour = contour.h_next() pt1 = (bound_rect[0], bound_rect[1]) pt2 = (bound_rect[0] + bound_rect[2], bound_rect[1] + bound_rect[3]) points.append(pt1) points.append(pt2) cv.Rectangle(color_image, pt1, pt2, cv.CV_RGB(255,0,0), 1) cv.ShowImage("Target", color_image) cv.ShowImage("frame_diff", frame_diff) # Listen for ESC key c = cv.WaitKey(7) % 0x100 if c == 27: break if __name__=="__main__": t = Target() t.run() </code></pre> <p>This is the original frame differencing code that I wanted transfer from:</p> <pre><code>import cv2 cap = cv2.VideoCapture(0) ret, current_frame = cap.read() previous_frame = current_frame while(cap.isOpened()): current_frame_gray = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY) previous_frame_gray = cv2.cvtColor(previous_frame, cv2.COLOR_BGR2GRAY) frame_diff = cv2.absdiff(current_frame_gray,previous_frame_gray) cv2.imshow('frame diff ',frame_diff) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break previous_frame = current_frame.copy() ret, current_frame = cap.read() cap.release() cv2.destroyAllWindows() </code></pre>
2
Missing parameters that are passed to route using return redirect - Laravel
<p>Please confirm if the below steps are correct (Specially the return redirect() part)</p> <p>Route "Dashboard2" is expecting 2 variables as follows to open the Dashboard view through the getDashboard function :</p> <pre><code>Route::get('/dashboard2/{wordsRowB}/{wordsRowId}', [ 'uses' =&gt; 'DashController@getDashboard', 'as' =&gt; 'dashboard2', 'middleware' =&gt; 'auth' ]); </code></pre> <p>So I passed to it these 2 variables as follows :</p> <p><strong>View Code :</strong></p> <pre><code>&lt;a href="{{ route('post.pin', [ 'wordsRowId' =&gt; $wordsRowId, 'wordsRowB' =&gt; $wordsRowB ]) }}"&gt;Test&lt;/a&gt; </code></pre> <p><strong>Controller Code :</strong></p> <pre><code>public function postPin($wordsRowId,$wordsRowB) { return redirect()-&gt;route('dashboard2') -&gt;with(['wordsRowId' =&gt; $wordsRowId]) -&gt;with(['wordsRowB' =&gt; $wordsRowB]); </code></pre> <p><strong>I'm getting this error :</strong> (You'll find 2 more variables in the error, that I removed from the above code for clarity)</p> <pre><code>Missing required parameters for [Route: dashboard2] [URI: dashboard2/{wordsRowB}/{wordsRowId}]. in UrlGenerationException.php line 17 at UrlGenerationException::forMissingParameters(object(Route)) in UrlGenerator.php line 332 at UrlGenerator-&gt;toRoute(object(Route), array(), true) in UrlGenerator.php line 304 at UrlGenerator-&gt;route('dashboard2', array()) in Redirector.php line 157 at Redirector-&gt;route('dashboard2') in DashController.php line 323 at DashController-&gt;postPin('62', '1', '39', 'kokowawa') at call_user_func_array(array(object(DashController), 'postPin'), array('post_id' =&gt; '62', 'user_id' =&gt; '1', 'wordsRowB' =&gt; '39', 'wordsRowId' =&gt; 'kokowawa')) in Controller.php line 80 </code></pre> <p>Please note that using var_dump shows that the variables are passed to the postPin function, but I don't know how to check if they were successfully redirected to the route ?</p>
2
Exception: cvc-complex-type.2.1: Element 'Date' must have no character or element information item [children]
<p>I am doing validation XSD file with XML file but I am getting below exception:</p> <blockquote> <p><strong>Exception:</strong> cvc-complex-type.2.1: Element 'Date' must have no character or element information item [children], because the type's content type is empty.</p> </blockquote> <p>Basically in my XML file <code>Date</code> element is empty </p> <p>My XML Date element: </p> <pre><code>&lt;Date&gt; &lt;/Date&gt; </code></pre> <p>Generated XSD file:</p> <pre><code>&lt;xs:element name="Date"&gt; &lt;xs:complexType/&gt; &lt;/xs:element&gt; </code></pre> <p>based on this I have created XSD file and validate then it's getting above exception</p> <p>But if I did without space between date element.</p> <p>Example:</p> <pre><code>&lt;Date&gt;&lt;/Date&gt; </code></pre> <p>Then it's working fine. How can I handle that empty space?</p>
2
Binding not working for innerHTML in nested component
<p>I'm trying to come up with a custom select control, </p> <pre><code>&lt;my-select&gt; &lt;my-option&gt;Option 1&lt;/my-option&gt; &lt;my-option&gt;Option 2&lt;/my-option&gt; ... &lt;/my-select&gt; </code></pre> <p>which works alright with static text. However, if I introduce bindings</p> <pre><code>&lt;my-select&gt; &lt;my-option *ngFor="let option of options"&gt;{{option}}&lt;/my-option&gt; &lt;/my-select&gt; </code></pre> <p><code>{{option}}</code> always renders as empty string (if I replace <code>{{option}}</code> with, say <code>test</code> then everything is working again). Here are my components:</p> <pre><code>@Component({ selector: 'my-select', template: ` &lt;ul&gt; &lt;li *ngFor="let option of options"&gt; {{option.text}} &lt;/li&gt; &lt;/ul&gt; ` }) export class SelectComponent { options: OptionComponent[] = []; addOption(option): OptionComponent { this.options.push(option); } } @Component({ selector: 'my-option', template: ` &lt;div #wrapper&gt; &lt;ng-content&gt;&lt;/ng-content&gt; &lt;/div&gt; `, directives: [] }) export class OptionComponent implements AfterContentInit { @ViewChild('wrapper') wrapper: ElementRef; text: string; constructor(private select: SelectComponent) { } ngAfterContentInit() { let text = this.wrapper.nativeElement.innerHTML; this.text = text ? text : 'EMPTY'; this.select.addOption(this); } } </code></pre> <p>How can I get this to work?</p> <p>EDIT: Almost forgot, <a href="http://plnkr.co/edit/Dnf3L54My4ZcCVWnC5Ul" rel="nofollow">here's a plnkr</a> showing the problem.</p>
2
access the data from the resolve function without relading the controller
<p>How do we access the data from the resolve function without relading the controller?</p> <p>We are currently working on a project which uses <code>angular-ui-router</code>. We have two seperated views: on the left a list of parent elements, on the right that elements child data.</p> <p>If selecting a parent on the left, we resolve it's child data to the child-view on the right.</p> <p>With the goal not to reaload the childs controller (and view), when selecting a different parent element, we set <code>notify:false</code>.</p> <p>We managed to 're-resolve' the child controllers data while not reloading the controller and view, but the data (scope) won't refresh.</p> <p>We did a small plunker to demonstrate our problem <a href="https://plnkr.co/edit/rJ5RV9vwSNGJXfmAb5VE?p=preview" rel="noreferrer">here</a></p> <p>First click on a number to instantiate the controllers <code>childCtrl</code>. Every following click should change the child scopes data - which does not work. You might notice the <code>alert</code> output already has the refreshed data we want to display.</p>
2
Not receiving certain notifications on OnePlus 3 running Android Marshmallow unless I wake the screen
<p>I was wondering if anyone might have any suggestions on how I could disable the Android Marshmallow doze/deep sleep mode that is default on new devices to save battery. I have a OnePlus 3 and have made every effort to check that all my notifications for calendar, whatsapp, emailing, etc. are set to both vibrate and make a sound, disabled all battery optimization features for apps, tried using screenlock wake apps to avoid missing notifications, and more. However, I am still unable to get notifications for whatsapp, emails, calendar reminders and events once my screen goes to sleep or I lock then phone and it's idle (so after about 15-30 minutes of it sleeping), but calls and texts seem to come through fine (or at least I haven't noticed these being an issue as much). This is a HUGE inconvenience, as my main reason to have a smartphone is so I can check emails, calendar events and such right as I receive them, and not only when I wake up my screen (which then bombards me with all my previous missed notifications from hours before). I have a feeling this is an android 6.0 issue and not due to the OnePlus 3, because it's been reported in other sites and by people with phones also using either this OS or lollipop. My older Samsung galaxy S4 running kitkat never had these problems, and at this point I'm very keen on going back if I can't get my new phone (or this OS, as I predict) to notify me right away even when my screen is locked and phone asleep (I can't always remember to check it especially if I'm busy at work). I am willing to root the phone and change settings if that's an option, but I would please like to see if you guys have any other suggestions for allowing my phone to receive notifications right away even when in sleep mode/idle/dozing. Thank you for your time in advance :)</p>
2
Angular 2 deploy with SystemJS and Gulp is too heavy
<p>I've been developing with Angular for a while but I just started with Angular 2, and after finishing the quickstarter from the Angular 2 tutorial y thought about trying to develop the finished application in a server as in production mode.</p> <p>I had no experience with SystemJS nor Gulp, so it took me a while, but I finally managed to make it work. Now I have 2 issues:</p> <p>For a Hello World application, it's really heavy, about 20MB, because I had to download lots of files from Angular 2 libraries. My guess is I don´t really need so many, but although I started with only @angular/core and @angular/platform-browser-dynamic, which are the ones referenced in my application ts files, angular kept throwing error messages in deployment until I included the whole @angular library.</p> <p>On the other hand, when I run the application I see again many single files being downloaded, which is not what I had in mind. There has to be a way to download only a single (minified) file with all the libraries (a bundle?) but I have no idea how to do that.</p> <p>Can anyone give me a hand with that?</p> <p>Here are my main configuration files.</p> <p>system.config.js</p> <pre><code>(function(global) { // map tells the System loader where to look for things var map = { 'app': 'app', // 'dist', '@angular': 'lib/@angular', 'rxjs': 'lib/rxjs' }; // packages tells the System loader how to load when no filename and/or no extension var packages = { 'app': { main: 'main.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' } }; var ngPackageNames = [ 'common', 'compiler', 'core', 'http', 'platform-browser', 'platform-browser-dynamic' ]; // Individual files (~300 requests): function packIndex(pkgName) { packages['@angular/' + pkgName] = { main: 'index.js', defaultExtension: 'js' }; } // Add package entries for angular packages ngPackageNames.forEach(packIndex); var config = { map: map, packages: packages }; System.config(config); })(this); </code></pre> <p>index.html</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Angular 2 QuickStart&lt;/title&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="icon" type="image/x-icon" href="favicon.ico"&gt; &lt;link rel="stylesheet" href="./css/styles.css"&gt; &lt;!-- 1. Load libraries --&gt; &lt;!-- Polyfill(s) for older browsers --&gt; &lt;script src="lib/shim.min.js"&gt;&lt;/script&gt; &lt;script src="lib/zone.js"&gt;&lt;/script&gt; &lt;script src="lib/Reflect.js"&gt;&lt;/script&gt; &lt;script src="lib/system.src.js"&gt;&lt;/script&gt; &lt;!-- 2. Configure SystemJS --&gt; &lt;script src="systemjs.config.js"&gt;&lt;/script&gt; &lt;script&gt; System.import('app').catch(function(err){ console.error(err); }); &lt;/script&gt; &lt;/head&gt; &lt;!-- 3. Display the application --&gt; &lt;body&gt; &lt;my-app&gt;Loading...&lt;/my-app&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>gulpfile.js</p> <pre><code>var gulp = require('gulp'); var ts = require('gulp-typescript'); const babel = require('gulp-babel'); var tsProject = ts.createProject('tsconfig.json'); gulp.task('babel-dp', ['resources', 'babel']); gulp.task('ts-dp', ['resources', 'ts']); gulp.task('resources', () =&gt; { gulp.src([ 'node_modules/core-js/client/shim.min.js', 'node_modules/zone.js/dist/zone.js', 'node_modules/reflect-metadata/Reflect.js', 'node_modules/systemjs/dist/system.src.js' ]).pipe(gulp.dest('web/lib')); gulp.src([ 'node_modules/@angular/**/*', ]).pipe(gulp.dest('web/lib/@angular')); gulp.src([ 'node_modules/rxjs/**/*', ]).pipe(gulp.dest('web/lib/rxjs')); gulp.src([ 'app/**/*.js' ]).pipe(gulp.dest('web/app')); gulp.src([ 'styles.css' ]).pipe(gulp.dest('web/css')); gulp.src([ 'index.html', 'systemjs.config.js', 'favicon.ico' ]).pipe(gulp.dest('web')); }); gulp.task('babel', () =&gt; { return gulp.src([ 'app/**/*.ts' ]) .pipe(babel({presets: ['es2015']})) .pipe(gulp.dest('web/js')); }); gulp.task('ts', function(done) { var tsResult = tsProject.src([ 'app/**/*.ts' ]) .pipe(ts(tsProject)); return tsResult.js.pipe(gulp.dest('web/js')); }); </code></pre> <p>Let me know if you need any other file. Many thanks!</p> <p><strong>UPDATE</strong></p> <p>I just found out that I can use the umd.min.js files inside @angular instead of the single js files. That is something, from 20 to 5MB, but still seems quite a lot, when the minified version of Angular 1 is less than 1MB.</p> <p>On the other hand, even though I used these umd.min.js files, chrome is still downloading single files when loading the application.</p> <p><strong>UPDATE 2</strong></p> <p>I managed to create a single bundle file using systemjs-builder as suggested in the comments. Now I have a single file bundle.app.js with all my application code, and my index.html now looks like this</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Angular 2 QuickStart&lt;/title&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="icon" type="image/x-icon" href="favicon.ico"&gt; &lt;link rel="stylesheet" href="css/styles.css"&gt; &lt;!-- 1. Load libraries --&gt; &lt;script src="app/bundle.app.js"&gt; &lt;/script&gt; &lt;!-- Polyfill(s) for older browsers --&gt; &lt;script src="node_modules/core-js/client/shim.min.js"&gt;&lt;/script&gt; &lt;script src="node_modules/zone.js/dist/zone.js"&gt;&lt;/script&gt; &lt;script src="node_modules/reflect-metadata/Reflect.js"&gt;&lt;/script&gt; &lt;script src="node_modules/systemjs/dist/system.src.js"&gt;&lt;/script&gt; &lt;script&gt; System.import('app').catch(function(err) { console.error(err); }); &lt;/script&gt; &lt;/head&gt; &lt;!-- 2. Display the application --&gt; &lt;body&gt; &lt;my-app&gt;Loading...&lt;/my-app&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>but now chrome can´t find the js imported in html: shim.min.js, zone.js, Reflect.js and system.src.js. I added a line in systemjs.config.js to include node_modules just in case, but I don´t think it's necessary. Anyway, it's not working either. Shouldn´t these imports be included in the bundle already?</p>
2
I cannot execute ShellExecute from javascript to run a Windows Form with parameters
<p>is it really possible to run an application installed on a users machine with parameters using an activex control. I can successfully run the application in this form: </p> <pre><code>$('#ejecutarActivo').click(function () { var Comando = $('#Comando').val(); if (Comando.trim() != "") { try { var objShell = new window.ActiveXObject("shell.application"); objShell.ShellExecute('C:\\Users\\Jerry\\Documents\\visual studio 2012\\Projects\\PruebaComandos\\PruebaComandos\\bin\\Debug\\PruebaComandos.exe', '', '', 'open',1); } catch (e) { alert('Active opciones de seguridad y utilice el navegador Internet Explorer'); } } }); </code></pre> <p>However I don't seem to be able to run it with parameters. I really need to run it that way and I'm able to run it with the parameters from the command line, but I've tried almost every combination of single and double quotes, and also simply putting the variable name (e.g. "Comando") in the invocation but everytime I put something inside the parameter section, (which according to Microsoft documentation <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/gg537745(v=vs.85).aspx" rel="nofollow noreferrer">MSDN</a> is the second parameter to ShellExecute) the application starts in my computer but nothing is displayed on the screen (I mean, I see the application is running in the Task Manager but something goes wrong and nothing displays). I need to check also the application to see if something is going wrong in the windows form. But I would like to know what's wrong in the way I'm invoking the activex.</p> <p>Can anybody help?</p>
2
Creating package folder in Android/data with Android Studio
<p>I'm trying to create a package folder for my application but i can't understand why I can't find it.</p> <p>I've set the permission <code>WRITE_INTERNAL_STORAGE</code> and I've tried with theese samples called in the MainActivity.onCreate().</p> <pre><code>//sample 1 File myDir = new File(getCacheDir(), "folder"); boolean created1 = myDir.mkdir(); //this returns True boolean created2 = myDir.mkdirs(); //this returns False //sample 2 File myDir = this.getFilesDir(); File documentsFolder = new File(myDir, "documents/data"); boolean Created3 = documentsFolder.mkdirs(); //this returns True </code></pre> <p>The application is always cleaned and rebuild before each test but when I look for the folder in Android/data i can see the package folders of the other applications but not the mine.</p> <p>I've read somewhere that I could see it only with a rooted device but in this case why can I see the folders of the other applications? I can't understand :s</p>
2
Possible to use `attribute` with `store_accessor`
<p>In Rails 5, is it possible to use the new attributes API with a field exposed via <code>store_accessor</code> on a <code>jsonb</code> column?</p> <p>For example, I have:</p> <pre><code>class Item &lt; ApplicationRecord # ... store_accessor :metadata, :publication_date attribute :publication_date, :datetime end </code></pre> <p>Then I'd like to call <code>i = Item.new(publication_date: '2012-10-24')</code>, and have <code>metadata</code> be a hash like: <code>{ 'publication_date' =&gt; #&lt;DateTimeInstance&gt; }</code>.</p> <p>However, the <code>attribute</code> call doesn't seem to be doing any coercion.</p> <p>Hopefully I am missing something--it seems like being able to use these two features in conjunction would be very useful when working with <code>jsonb</code> columns. (Speaking of which, why doesn't the attributes API expose a generic <code>array: true</code> option? That would also be very useful for this case.)</p>
2
WooCommerce Adding Parent attribute automatically
<p>I have a WooCommerce site with auto-imported products, which refresh them every week. These products have attributes called COLOR and SIZE.</p> <p>However, the COLOR red has these sub-attributes:</p> <ul> <li>Crimson Red</li> <li>Cola Red</li> <li>Puma Red</li> </ul> <p>Normally, I have to manually add and assign these sub-attributes to the &quot;parent RED&quot; attribute and that is a lot of work.</p> <p>I wonder if there is a way to do this automatically?</p> <p>For example, IF the attribute contains the word RED, assign it to parent attribute RED.</p>
2
How to Establish a connection to ALM using REST API
<p>I have a Couple of Questions which need to be clarified below 1)What is Meant by a REST client 2)What is the difference between OTA API vs REST API in ALM during connectivity. I have already established a connection with OTA. Can anyone provide a sample code to establish a connection with ALM using REST API</p>
2
How to retrieve user information from Azure Active Directory
<p>I'm a bit new to Xamarin and Azure Active Directory so please bear with me. I'm having trouble trying to retrieve user information (first name, last name, and picture) from Azure Active Directory. Mind you the emails in the Azure Active Directory are Google accounts. </p> <p>Every time I try to retrieve it, I only get an error and it requires to me to authenticate AGAIN just to retrieve what I want. Here's my code:</p> <pre><code> // Use MobileServices Login to authenticate user private async Task&lt;bool&gt; AuthenticateUsingMobileServices(Activity activity) { var success = false; try { // Sign in with Active Directory MobileUser = await MobileService.LoginAsync(activity, MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory); System.Diagnostics.Debug.WriteLine("you are now logged in - Logged in!"); System.Diagnostics.Debug.WriteLine([insert user name here]); success = true; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Authentication failed " + ex.ToString()); } } </code></pre> <p>I've tried adding this in addition to my already defined ResourceUri and ClientId:</p> <pre><code> AuthenticationContext authContext = new AuthenticationContext(CommonAuthority); AuthResult = await authContext.AcquireTokenAsync(ResourceUri, ClientId, UserCredential); </code></pre> <p>But I'm clueless on what to put for ClientAssertion or UserAssertion.</p>
2
What to do with replication factor when reducing a Cassandra cluster?
<p>I have a 3 nodes Cassandra cluster with 2 keyspaces. One of them has replication factor 1 and the other, replication factor 2. I want to reduce the cluster, using nodetool decommission, to remove 2 nodes and leave only one (single node cluster). </p> <p>So, what must I do with the replication factor? I think both keyspaces must have replication factor 1, but when must I modify it? Before decommission?</p> <p>Thanks a lot!</p>
2
failed uploading image // Object not found
<p>I have been trying to upload an image and has it shown after pressing submit button using PHP. it gave me the error below: </p> <p><a href="https://i.stack.imgur.com/KNnxp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KNnxp.png" alt="enter image description here"></a></p> <blockquote> <p>Object not found!</p> <p>The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.</p> <p>If you think this is a server error, please contact the webmaster.</p> <p>Error 404</p> <p>localhost Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.6.23</p> </blockquote> <p>Someone please help me to fix this. I have no idea where the problem is. Appreciate it! This is what I have been trying to do: <a href="https://i.stack.imgur.com/OMR1c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OMR1c.png" alt="enter image description here"></a> </p> <pre><code>echo &lt;&lt;&lt;_END &lt;html&gt;&lt;head&gt;&lt;title&gt;PHP from Upload&lt;/title&gt;&lt;/head&gt;&lt;body&gt; &lt;form method = 'POST' action='upload.php' enctype='multipart/form.data'&gt; Select a JPG, GIF, PNG or TIF File: &lt;input type='file' name='filename' size='10'&gt; &lt;input type='submit' value='Upload'&gt; &lt;/form&gt; _END; if ($_FILES){ $name = $_FILES['filename']['name']; switch($_FILES['filename']['name']){ case 'image/jpeg': $ext = 'jpg'; break; case 'image/gif': $ext = 'gif'; break; case 'image/png': $ext = 'png'; break; case 'image/tiff': $ext = 'tif'; break; default: $ext = ''; break; } if ($ext){ $n = "image.$ext"; move_uploaded_file($_FILES['filename']['tmp_name'], $n); echo "&lt;img src='$n'&gt;"; } else echo "'$name' is not an accepted image file"; } else echo "No image has been uploaded"; echo "&lt;/body&gt;&lt;/html&gt;"; </code></pre>
2
Vimeo embed showing white screen/missing progressbar
<p>I'm using Vimeo with webview in one of my apps, but in some devices it isn't working very well. On my xaiomi(API-19) it doesn't show the video progressbar and on my S4(API-21) the first time i watch the video it display correctly, but at the second time it shows a white screen, not only on the video i just watch but in all others Vimeos videos that i try to play. Someone knows what i'm doing wrong? or another way that works?. Here's my VimeoPlayer activity.</p> <pre><code>public class VimeoPlayer extends Activity { private HTML5WebView mWebView; private ModelVideo video; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mWebView = new HTML5WebView(this); video = getIntent().getParcelableExtra("video"); //Auto playing vimeo videos in Android webview mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setAllowFileAccess(true); mWebView.getSettings().setAppCacheEnabled(true); mWebView.getSettings().setDomStorageEnabled(true); mWebView.getSettings().setPluginState(PluginState.OFF); mWebView.getSettings().setAllowFileAccess(true); String html = "&lt;iframe src=\"https://player.vimeo.com/video/" + video.getVideoUrl() + "?title=0&amp;byline=0&amp;portrait=0&amp;color=000000\" width=\"" + mWebView.getWidth() + "\" height=\"" + mWebView.getHeight() + "\" frameborder=\"0\" webkitallowfullscreen=\"\" mozallowfullscreen=\"\" allowfullscreen=\"\"" + "style=\"margin-top:-8px;margin-bottom:-8px;margin-left:-8px;margin-right:-8px;padding:0;width:105%;height:100%;background-color:#000000;\"&gt;&lt;/iframe&gt;"; String mime = "text/html"; String encoding = "utf-8"; mWebView.loadDataWithBaseURL(null, html, mime, encoding, null); setContentView(mWebView.getLayout()); //Esconder a Status Bar View decorView = getWindow().getDecorView(); // Hide the status bar. int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); // Remember that you should never show the action bar if the // status bar is hidden, so hide that too if necessary. ActionBar actionBar = getActionBar(); if(actionBar!=null) { actionBar.hide(); } } @Override public void onPause() { super.onPause(); } @Override protected void onDestroy() { super.onDestroy(); mWebView.destroy(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) &amp;&amp; mWebView.canGoBack()) { mWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); } @Override public void onBackPressed() { super.onBackPressed(); mWebView.destroy(); finish(); } } </code></pre>
2
What's the Swift 3 enumerateContentsOfDirectoryAtPath Syntax? (Haneke)
<p>I'm converting the Haneke Cacheing framework to Swift 3 and I've run into a snag with enumerateContentsOfDirectoryAtPath.</p> <p>Here's the original syntax (<a href="https://github.com/Haneke/HanekeSwift/blob/feature/swift-3/Haneke/DiskCache.swift#L159" rel="nofollow">view on github</a>),</p> <pre><code>let fileManager = NSFileManager.defaultManager() let cachePath = self.path fileManager.enumerateContentsOfDirectoryAtPath(cachePath, orderedByProperty: NSURLContentModificationDateKey, ascending: true) { (URL : NSURL, _, inout stop : Bool) -&gt; Void in if let path = URL.path { self.removeFileAtPath(path) stop = self.size &lt;= self.capacity } } </code></pre> <p>I believe what I'm looking for is the following function which I found by looking at the FileManger definition, however I don't know how to make the conversion:</p> <pre><code>public func enumerator(atPath path: String) -&gt; FileManager.DirectoryEnumerator? </code></pre> <h2>Question</h2> <p>What's the Swift 3 equivalent of enumerateContentsOfDirectoryAtPath and how should I use it while converting the above example?</p>
2
Why do I get nothing but zero from the output of audiorecord?
<p>I want to use an AudioTrack to play a sound and I recorded it using AudioRecord at the same time. But I cant get anything except zero. Why?</p> <p>I have tried to read data from the <code>byte[]</code> buffer and all I get is zero. Here is my code:</p> <pre><code>import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.sql.Time; import java.util.Timer; import java.util.TimerTask; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; public class RecordThread implements Runnable { private static final int Encording = AudioFormat.ENCODING_PCM_16BIT; //Data size for each frame = 16 bytes private static final int Sample_rate = 8000; //Sample rate = 8000 HZ private static final int Channel = AudioFormat.CHANNEL_IN_MONO; //Set as single track public static final int Buffersize = AudioRecord.getMinBufferSize(Sample_rate, Channel, Encording); //Buffer size @Override public void run() { // TODO Auto-generated method stub AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,Sample_rate, Channel, Encording, Buffersize); while(MessageUsed.RecordPermit){ try { FileOutputStream ops = new FileOutputStream(TestoOFDMMain.file2); BufferedOutputStream bos = new BufferedOutputStream(ops); DataOutputStream dos = new DataOutputStream(bos); byte[] buffer = new byte[Buffersize]; audioRecord.startRecording(); //Start Recording int bufferReadResult = audioRecord.read(buffer, 0, buffer.length); //Read Array size MessageUsed.RecordStop = false; /*Write Data to file*/ for(int i=0;i&lt;bufferReadResult;i++){ dos.write(buffer[i]); System.out.println(buffer[i]); if(MessageUsed.ProcessPermit == true){ break; } } audioRecord.stop(); dos.close(); MessageUsed.RecordStop = true; Thread.sleep(300); MessageUsed.ProcessStart = true; Thread.sleep(900); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } </code></pre>
2
Embedded images in HTML email
<p>I have a text file (htmlText containing an HTML message to be sent out in a mass mailing. The text is marked up with my images using HTML code like</p> <pre><code>&lt;img src='cid:imgheader'/&gt; </code></pre> <p>I have followed example after example of how to use the LinkedResource in my VB code like</p> <pre><code>Dim imgHeader As String = "header.jpg" Dim lnkHeader As LinkedResource = New LinkedResource(imgHeader) lnkHeader.ContentId = "imgHeader" Dim av As AlternateView = AlternateView.CreateAlternateViewFromString(htmlText, Nothing, MediaTypeNames.Text.Html) av.LinkedResources.Add(lnkHeader) </code></pre> <p>and yet, the images are received as attachments and are not embedded in the email body as expected. What am I missing or doing wrong? My images are stored in the executable path of the program which is a console application.</p>
2
Getting the error of subprocess to the master when using rdd.pipe
<p>When using <code>rdd.pipe(command)</code>, the error of subprocess does not come back to the master. For instance, if one does:</p> <pre><code>sc.parallelize(Range(0, 10)).pipe("ls fileThatDontExist").collect </code></pre> <p>The stacktrace is then the following:</p> <pre><code>java.lang.Exception: Subprocess exited with status 1 at org.apache.spark.rdd.PipedRDD$$anon$1.hasNext(PipedRDD.scala:161) at scala.collection.Iterator$class.foreach(Iterator.scala:727) at org.apache.spark.rdd.PipedRDD$$anon$1.foreach(PipedRDD.scala:153) at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:48) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:103) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:47) at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:273) at org.apache.spark.rdd.PipedRDD$$anon$1.to(PipedRDD.scala:153) at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:265) at org.apache.spark.rdd.PipedRDD$$anon$1.toBuffer(PipedRDD.scala:153) at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:252) at org.apache.spark.rdd.PipedRDD$$anon$1.toArray(PipedRDD.scala:153) at org.apache.spark.rdd.RDD$$anonfun$collect$1$$anonfun$12.apply(RDD.scala:885) at org.apache.spark.rdd.RDD$$anonfun$collect$1$$anonfun$12.apply(RDD.scala:885) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1767) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1767) at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:63) at org.apache.spark.scheduler.Task.run(Task.scala:70) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:213) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Driver stacktrace: at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1273) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1264) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1263) at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59) at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47) at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1263) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:730) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:730) at scala.Option.foreach(Option.scala:236) at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:730) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1457) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1418) at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48) </code></pre> <p>No mention here of the error that happened in the command, one needs to search in the executor logs to find:</p> <pre><code>ls: fileThatDontExist: No such file or directory </code></pre> <p>Checking the code of PipedRDD, it appears that one could add more information when throwing the exception (like adding the content of proc.getErrorStream in the message):</p> <pre><code>val exitStatus = proc.waitFor() if (exitStatus != 0) { throw new Exception("Subprocess exited with status " + exitStatus) } </code></pre> <p>I have two questions regarding this. Is there a reason for not doing so? Also does anyone know a shortaround? </p> <p>For now I have encapsulated process execution so that when there is an error in the process, I return 0 and output the stderr of the process plus a marker. The RDD is then mapped and lines containing the marker throws an exception with the stderr.</p>
2
Firebase Analytics APP_OPEN on Android
<p>I made an Android app and I have integrated some tools of Firebase, but when I include the Firebase Analytics in the event APP_OPEN Android Studio shows that "I need out bundle", but in the docs of Firebase the method I should not send bundle. How resolve this problem? </p>
2
Updating SKNodes outside update() of scene
<p>I was quite surprised that the update method in the SKScene class isn't actually inherited from SKNode. To me, it seems logical for all SKNodes to be able to update themselves (for instance to remove itself from the scene when it's no longer on display, among other things). I think this would help in making the instances separate independent entities (no dependencies, no unexpected behavior) If there is other logic behind keeping the updates in the scenes only, please explain.</p> <p>So I'm wondering if it's worth using a timer (repeating with a 1/60 time interval) to add a custom update to my custom SKNodes (perhaps even an extension that will add this to all SKNodes). However, I imagine this will be quite memory intensive. So I would like to ask if there is some 'best practice' regarding this. Perhaps the timer would work if it fired at each frame rather forcing it to fire 60 times a second.</p>
2
How to use the Concurrency check attribute in Code first?
<p>I have been following the tutorial but I can't seem to make it work.</p> <p>I have my model:</p> <pre><code>public int id { get; set; } [Required] [Index] [Display(Name="First Name")] public string firstname { get; set; } [Required] [Display(Name="Last Name")] [ConcurrencyCheck] public string lastname { get; set; } [Required] [Display(Name="Address")] public string address { get; set; } </code></pre> <p>I also have everything working before I put the <code>ConcurrencyCheck</code> attribute.</p> <p>Here is the update snippet:</p> <pre><code>CarlCtx ctx = new CarlCtx(); ctx.Entry(entry).State = System.Data.Entity.EntityState.Modified; ctx.SaveChanges(); </code></pre> <p>But I get the exception right away even If I am the only user who is editing.</p> <p>What did I miss?</p>
2
Show total Sum of values of a Column of a DataTable
<p>I want to show sum of total Price of items. I am facing 2 issues:</p> <ul> <li>It's showing me wrong total of items price </li> <li>I want to add <code>.00</code> to the total price</li> </ul> <p>You can check issue in the <a href="http://i.stack.imgur.com/1mvxF.jpg" rel="nofollow">image</a> for a clear explanation.</p> <p>Here is my code:</p> <pre><code>tDisplay.Text = "Return/" + "Receipt No:" + Return_Form.setalueforText011; label1.Text = Return_Form.setalueforText011; OleDbConnection VCON = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Restaurant.accdb"); DataSet dsa = new DataSet(); DataTable dt = new DataTable(); dsa.Tables.Add(dt); OleDbDataAdapter da = new OleDbDataAdapter(); da = new OleDbDataAdapter("SELECT [Column1],[Column2],[Column3] from [Total] Where [Receipt No] = " + label1.Text + "", VCON); da.Fill(dt); //dataGridView1.DataSource = dt; for (int i = 0; i &lt; dt.Rows.Count; i++) { products.Add(new tblProduct() { productName = dt.Rows[i]["Column2"].ToString(),productPrice = Convert.ToDecimal(Math.Round(Convert.ToDecimal(dt.Rows[i]["Column1"].ToString())))}); label3.Text = dt.Rows[i]["Column3"].ToString(); textBox59.Text = "Rs: "+String.Format("{0:}", Total); tblProduct selected = (tblProduct)(listBox60.SelectedItem); Total += (decimal)selected.productPrice; } VCON.Close(); </code></pre>
2
Vertical Multi-level Navigation Menu in UWP App
<p>I m Working on UWP App this app contain some Products Categories and inside this Category create Another Product list and this is up to 3-level navigation.<br> <a href="http://i.stack.imgur.com/WuFOw.png" rel="nofollow">For Example</a></p>
2
Firebase custom token vs service account
<p>We have android app with local users list. The app has single dedicated user in Firebase (other users are managed locally), which should be used to access Realtime Database. UID would be used to apply security Rules and restrict access to specific data elements. I think we have two options: custom token or service account (with databaseAuthVariableOverride). </p> <p>I wonder what security issues we might get by using service account approach? Does it get full access? Maybe we could restrict that to minimal set of actions? </p> <p>Custom token approach might have problem with token expiration. Is there a way to significantly extend token validity? What could be the best way to generate custom token on android?</p>
2
VS Database Project Primary Key Name
<p>I have a database project in Visual Studio 2015. I would like to name the primary key but it seems to ignore any attempts. Naming default constraints though does work.</p> <pre><code>CREATE TABLE [dbo].[Stock] ( [Id] INT CONSTRAINT [PK_Stock_Id] NOT NULL PRIMARY KEY, [StockCode] NVARCHAR(6) NOT NULL, [CreatedDate] DATETIME2 CONSTRAINT [DF_Stock_CreatedDate] DEFAULT sysutcdatetime() NOT NULL ) GO </code></pre> <p>If you click on the primary key it even has a name property but it is readonly. I got it to create just the script rather than publish to SQL Server and it strips out the word constraint and name on the primary key.</p>
2
What's the minimum Api version for using FloatingActionButton in Android?
<p>I need to know what api version support the fab element in android.</p>
2
yii2 custom validation in rule not working
<p>How to implement custom validation in yii2?</p> <p>My code in model rules is </p> <pre><code>public function rules() { return [ [['product_price'], 'checkMaxPrice'] ]; } public function checkMaxPrice($attribute,$params) { if($this-&gt;product_price &gt; 1000) { $this-&gt;addError($attribute,'Price must be less than 1000'); } } </code></pre> <p>Anything else I have to do in view? </p>
2
Jenssegers / select('column') returns more columns than the one specified in the select
<p>I have the following issue with jenssegers query builder (I'm a new user):</p> <pre><code>print_r(DB::table($tablename)-&gt;where('_id',$_id)-&gt;select($table_structure_record['field'])-&gt;get()); </code></pre> <p>returns me more than one column, despite only one column is specified in the select statement:</p> <pre><code>Array ( [0] =&gt; Array ( [_id] =&gt; MongoDB\BSON\ObjectID Object ( [oid] =&gt; 5780b81d93f7fb0e00d0f252 ) [collection] =&gt; structure ) ) </code></pre> <p>My expected result would be only ([collection] => structure) , I don't understand why i also get "[_id] => MongoDB\BSON\ObjectID Object ( [oid] => 5780b81d93f7fb0e00d0f252 )"</p> <p>Can someone help me ? Despite many searches, it seems select statement is supposed to return ONLY the columns specified, not any other !</p>
2
Can't delete a row with SQLAlchemy / Flask-SQLAlchemy
<p>I can't seem to get this method to delete a row. It runs without error, but the row remains in the db (mysql). I have add and updates working using a similar approach.</p> <p>Basically, I'm creating a list of ids (ParentPage.id) and comparing those against a temp table (ParentPageTemp.id), with the intention of deleting rows in ParentPage which are not found in ParentPageTemp. Additional I have a relationship between ParentPage and Page where the row in Page should be deleted following the ParentPage delete. Admittedly my understanding of relationships in SQLAlchemy is novice at best.</p> <p>models.py</p> <pre><code>class ParentPage(Model): __tablename__ = 'parent_page' id = Column(Integer, primary_key=True) url = Column(String(255)) def __repr__(self): this_id = str(self.id) return this_id class Page(Model): __tablename__ = 'pages' id = Column(Integer, ForeignKey('parent_page.id'), primary_key=True) parent_id = Column(Integer, ForeignKey('parent_page.id')) type = Column(String(255)) default_code = Column(String(255)) name = Column(String(255)) header = Column(String(255)) title = Column(String(255)) keywords = Column(String(255)) description = Column((Text)) priority = Column(String(255)) list_price = Column((Float)) standard_price = Column((Float)) image_filename = Column((Text)) image_alt_text = Column(String(255)) pdf_filename = Column((Text)) lastupdate = Column(Date) page = relationship('ParentPage', foreign_keys=[id], backref='page') parent = relationship('ParentPage', foreign_keys=[parent_id], backref='children') def __repr__(self): return self.name </code></pre> <p>method in views.py</p> <pre><code>def delete_temp_not_in_test(): parent_test_ids = db.session.query(ParentPage.id).all() print "parent in test - %s" % (parent_test_ids) for item in parent_test_ids: q = db.session.query(ParentPageTemp).get(item) if q is None: print "ID doesnt exist - %s" % (item) db.session.query(Page).filter(Page.id==item).delete(synchronize_session='fetch') db.session.query(ParentPage).filter(ParentPage.id==item).delete(synchronize_session='fetch') db.session.commit() print "%s deleted from Temp" % (item) # return False else: print "ID is %s" % (q.id) # return True return </code></pre> <p>Thanks.</p>
2
react-native Navigator (navbar) Hiding View Under Navbar
<p>I'm having a hard time figuring out which props I need to change in the initial view below the Navbar. Or is there a prop for the navbar I need to change? Basically, the navbar is hiding the top portion of the underlying view. I'm attaching a screen cap here:</p> <p><a href="https://i.stack.imgur.com/leJZN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/leJZN.png" alt="enter image description here"></a></p> <p>Here is my code.</p> <p>Navigator code:</p> <pre><code>var routeMapper = { LeftButton: function(route, navigator, index, navState) { if(index &gt; 0) { return ( &lt;TouchableHighlight underlayColor="transparent" onPress={() =&gt; { if (index &gt; 0) { navigator.pop() } }}&gt; &lt;Text style={ styles.leftNavButtonText }&gt;Back&lt;/Text&gt; &lt;/TouchableHighlight&gt;) } else { return null } }, RightButton: function(route, navigator, index, navState) { return null; }, Title: function(route, navigator, index, navState) { return &lt;Text style={ styles.navbarTitle }&gt;EST4Life&lt;/Text&gt; } }; module.exports = React.createClass({ renderScene: function(route, navigator) { var Component = ROUTES[route.name]; // ROUTES['signin'] =&gt; Signin // return the component with props to the current route and the navigator instance return &lt;Component route={route} navigator={navigator} /&gt;; }, render: function() { // return an instance of Navigator return ( &lt;Navigator style={styles.container} initialRoute={{name: 'signin'}} renderScene={this.renderScene} configureScene={() =&gt; { return Navigator.SceneConfigs.FloatFromRight; }} navigationBar={&lt;Navigator.NavigationBar routeMapper={routeMapper} style={styles.navBarStyle} /&gt;} /&gt; ) } }); var styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', }, navBarStyle: { backgroundColor: 'gray', flex: 1, borderWidth: 1 }, navbarTitle: { color: 'white', }, rightNavButtonText: { color: 'white', }, leftNavButtonText: { color: 'white', }, }) </code></pre> <p>signin.js</p> <pre><code>module.exports = React.createClass({ render: function() { if (this.state.user == '') { // this.state.user = '' when signin is initiated return &lt;View style={styles.container}&gt;&lt;Text&gt;Loading...&lt;/Text&gt;&lt;/View&gt; } else if (this.state.user == null){ // this.state.user == null when user is not logged in return ( &lt;View style={styles.container}&gt; &lt;Text&gt;Sign In&lt;/Text&gt; &lt;Text style={styles.label}&gt;Username:&lt;/Text&gt; &lt;TextInput style={styles.input} value={this.state.username} onChangeText={(text) =&gt; this.setState({username: text})} /&gt; &lt;Text style={styles.label}&gt;Password:&lt;/Text&gt; &lt;TextInput secureTextEntry={true} style={styles.input} value={this.state.password} onChangeText={(text) =&gt; this.setState({password: text})} /&gt; &lt;Text style={styles.label}&gt;{this.state.errorMessage}&lt;/Text&gt; &lt;Button text={'Sign In'} onPress={this.onLoginPress} /&gt; &lt;Button text={'I need an account..'} onPress={this.onSignupPress} /&gt; &lt;/View&gt; ); // onPress={this.onPress} - pass in the onPress method below to TouchableHighlight } else { // clear view when user is logged in return &lt;View&gt;&lt;Text&gt;&lt;/Text&gt;&lt;/View&gt; } }, // end of render var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', borderWidth: 4, borderColor: 'green' }, input: { padding: 5, // space between text and inside of box height: 40, borderColor: 'gray', borderWidth: 1, borderRadius: 5, margin: 5, width: 200, alignSelf: 'center', }, label: { fontSize: 18 } }); </code></pre> <p>Thanks.</p> <p>Update: I figured out how to extract the heights involved with the navbar. Code for use where the component is created:</p> <pre><code>var NavBarHeight = navigator.props.navigationBar.props.navigationStyles.General.NavBarHeight var StatusBarHeight = navigator.props.navigationBar.props.navigationStyles.General.StatusBarHeight var TotalNavHeight = navigator.props.navigationBar.props.navigationStyles.General.TotalNavHeight </code></pre> <p>Code to use in any scene thereafter:</p> <pre><code>var NavBarHeight = this.props.navigator.props.navigationBar.props.navigationStyles.General.NavBarHeight var StatusBarHeight = this.props.navigator.props.navigationBar.props.navigationStyles.General.StatusBarHeight var TotalNavHeight = this.props.navigator.props.navigationBar.props.navigationStyles.General.TotalNavHeight </code></pre>
2
How does the blob: protocol work as <video> source?
<p>A friend of mine was trying to download a Twitter embedded video and found something like this in the HTML code:</p> <pre><code>&lt;video preload="auto" data-id="content" data-type="content" src="blob:https%3A//twitter.com/7897de6d-6eed-4905-9ed2-00ea3d2c99d5" class="visible paused" style="width: 100%; height: 100%;"&gt;&lt;/video&gt; </code></pre> <p>I'm as puzzled as he was when I tried to find out the <em>real</em> source of the video stream (either by inspecting the browser network console and hitting a proxy). As the video played, the bytes seem to come out of nowhere.</p> <p>How does the browser understand the blob "protocol"?</p>
2
Laravel Paypal API single payout
<p>I'm trying to integrate the Paypal API to my Laravel project to send payments to users emails automatically from my own Paypal account.</p> <p>The thing is that there are some "mass payments" packages but that's not what I need, I actually need to send a single payment to one user each time.</p> <p>Thanks in advance!</p>
2
Concatenating a vector of column names in R data.table
<p>I'm looking to add a column to a <code>data.table</code> which is a concatenation of several other columns, the names of which I've stored in a vector <code>cols</code>. Per <a href="https://stackoverflow.com/a/21682545/1840471">https://stackoverflow.com/a/21682545/1840471</a> I tried <code>do.call</code> + <code>paste</code> but couldn't get it working. Here's what I've tried:</p> <pre><code># Using mtcars as example, e.g. first record should be "110 21 6" dt &lt;- data.table(mtcars) cols &lt;- c("hp", "mpg", "cyl") # Works old-fashioned way dt[, slice.verify := paste(hp, mpg, cyl)] # Raw do.call+paste fails with message: # Error in do.call(paste, cols): second argument must be a list dt[, slice := do.call(paste, cols)] # Making cols a list makes the column "hpmpgcyl" for each row dt[, slice := do.call(paste, as.list(cols))] # Applying get fails with message: # Error in (function (x) : unused arguments ("mpg", "cyl") dt[, slice := do.call(function(x) paste(get(x)), as.list(cols))] </code></pre> <p>Help appreciated - thanks.</p> <p><em>Similar questions:</em></p> <ul> <li><p><a href="https://stackoverflow.com/questions/21682462/concatenate-columns-and-add-them-to-beginning-of-data-frame">Concatenate columns and add them to beginning of Data Frame</a> (operates on <code>data.frames</code> using <code>cbind</code> and <code>do.call</code> - this was very slow on my <code>data.table</code>)</p></li> <li><p><a href="https://stackoverflow.com/questions/6308933/r-concatenate-row-wise-across-specific-columns-of-dataframe">R - concatenate row-wise across specific columns of dataframe</a> (doesn't deal with columns as names or large number of columns)</p></li> <li><p><a href="https://stackoverflow.com/questions/15007979/accessing-columns-in-data-table-using-a-character-vector-of-column-names">Accessing columns in data.table using a character vector of column names</a> (considers aggregation using column names)</p></li> </ul>
2
How to not offer a task to specific worker on Twilio
<p>I am new in Twilio and i have been facing an issue while designing outbound dialer currently preview dialing. If a worker rejects a task than the same task should not be offered to that worker again. How do i handle this case?</p>
2
ElasticBeanstalk nodejs.log can't find module 'hogan.js'
<p>I have a simple node.js app that is using <code>"hogan": "^1.0.2"</code> (from <code>packages.json</code> under <code>"dependencies"</code>).</p> <p>It has been failing to deploy, and looking in the logs, I am seeing (multiple times):</p> <p><code> Error: Cannot find module 'hogan.js' at Function.Module._resolveFilename (module.js:325:15) at Function.Module._load (module.js:276:25) at Module.require (module.js:353:17) at require (internal/module.js:12:17) </code></p> <p>I'm fairly new to node.js on EB, and have just been following <a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_nodejs_express.html" rel="nofollow">http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_nodejs_express.html</a> with a pre-existing Express app.</p> <p>Assuming EB runs <code>npm install</code> for me (is that a safe assumption?), what might the issue be?</p>
2