input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
node-fetch receives empty body <p>I'm writing unit-tests for a simple NodeJS application and for some reason I cannot retrieve response body. It gets proper response code (either 200 for successful requests or 422 for invalid ones) but body appears to be empty. Also, when I'm making exactly the same request with <stron... | <p>You need to try <code>response.json()</code> instead of <code>response.ok</code> which will return the response in a proper way in your case.</p>
<p>Hope this helps!</p>
|
VueJS data() not working <p>I am trying to make a VueJS app but I am failing even with the simplest examples.
I am using Laravel 5.3 with pre-built support for VueJS (version 1, I tried version 2 as well).</p>
<p>Here is my Example.vue component</p>
<pre><code><template>
<div class="profile">
... | <p>Call the component inside your template</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Vue.component('example', {
template: `<div class="profile">{{ name }}</... |
Global variables code confusion <p>I am having trouble getting data input from one class to another and I cant seem to get the global function to work. The part i need help with is in the last function but it only works if you have the whole code.</p>
<pre><code>import tkinter as tk
import os
self = tk
TITLE_FONT = (... | <p>If you want to use global variables, you need to do this:</p>
<pre><code>var1 = <some value>
var2 = <some other value>
s1 = <yet another value here>
# then create your classes
class Whatever(tk.whatever_you_want):
def __init__(self, arg1, arg2, whatever_arg):
global var1 #whis tells... |
PHP array_search not working (returns empty string) <p>I'm trying to check if a filename of an image contains "cover". Somehow this stopped working for me (Pretty sure it worked already). I copied the part of my function not working. </p>
<pre><code>$name=array("_IMG8555.jpg", "_IMG7769.jpg", "_IMG8458.jpg", "Cover.jp... | <p>The array_search() function search an array for a value and returns the key</p>
<pre><code>array_search(key_value,array)
</code></pre>
<p>Loop your $cov array and get one key at a time and check with $name array</p>
<pre><code>foreach($cov as $i => $cov_s){
if(in_array($cov_s, $name)){
return $name[array_se... |
shopify I need to check if current page is a collection page and not a single product page <p>I am trying to check if my current page is a collection page not a single product page in some collection.</p>
<p>I mean for example if someone goes to collection page of shoes then I can check using collection.handle == 'Sho... | <p>Use this simple way with <a href="https://help.shopify.com/themes/liquid/objects/template" rel="nofollow"><code>template</code></a>: </p>
<pre><code>{% if template contains 'collection' %}
Do something
{% endif %}
</code></pre>
|
Can't launch service with net.tcp binding error 10049 <p>I have a problem with launching a WCF service using net.tcp endpoints. I'm getting an 10049 error.</p>
<p>My <code>app.config</code>:</p>
<pre><code><system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehaviour0"
... | <p>Try to replace lines</p>
<pre><code>net.tcp://78.26.210.203:50050/reg
</code></pre>
<p>with </p>
<pre><code>net.tcp://localhost:50050/reg
</code></pre>
<p>And the same for <code>/auth</code> endpoint.</p>
|
Change table Information <p>I have three tables:</p>
<p>Table 1: (Consumer)</p>
<pre><code>UserName | FirstName | LastName
'Magika12' 'Ronald' 'Ludwig'
</code></pre>
<p>Table 2: (ConsumerLocation)</p>
<pre><code>UserName | LocationID
'Magika12' 13234
</code></pre>
<p>Table 3: (Location)</p>
<pre><code>Lo... | <p>You missed condition of <code>join</code> statement. Should be like this:</p>
<pre><code>UPDATE
Location L1
INNER JOIN ConsumerLocation c on c.LocationID=L1.LocationID -- miseed on
SET
L1.StreetNumber = 124,
L1.StreetName = 'Braelands Crescent',
L1.Suburb = 'Albion' ,
L1.City = 'Melbourne'... |
How modules know each other <p>I can plot data from a CSV file with the following code:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('test0.csv',delimiter='; ', engine='python')
df.plot(x='Column1', y='Column3')
plt.show()
</code></pre>
<p>But I don't understand one thing. How <... | <p>Matplotlib has two "interfaces": a <a href="http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html" rel="nofollow">Matlab-style interface</a> and an <a href="http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut2.html" rel="nofollow">object-oriented interface</a>. </p>
<p>Plotting with the Matlab-style i... |
How To Run a specific Application on Android Devices <p>I just want to learn how can i run my application on Android devices? <br>
I mean,it has to run automatically on startup and nothing will be allowed except the application.<br>
I just want to do something like this. (See the video) <a href="https://www.youtube.com... | <p>Use this link for Kiosk Application
<a href="http://www.andreas-schrade.de/2015/02/16/android-tutorial-how-to-create-a-kiosk-mode-in-android/" rel="nofollow">http://www.andreas-schrade.de/2015/02/16/android-tutorial-how-to-create-a-kiosk-mode-in-android/</a></p>
|
solr 6.2.1 uniqueField not work <p>i install solr 6.2.1 and in schema define a uniqueField:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!-- Solr managed schema - automatically generated - DO NOT EDIT -->
<schema name="ps_product" version="1.5">
<fieldType name="int" class="solr.TrieIn... | <p>Since Solr 4 and to support SolrCloud the <a href="http://wiki.apache.org/solr/UniqueKey#UUID_techniques" rel="nofollow">uniqueKey</a> field can no longer be populated using <code>default=...</code> you should remove it from the feld definition in schema.xml :</p>
<p><code><field name="id_product" type="uuid" in... |
Workaround for Zoom in Graph overview? <p>I am currently working on a medium size graph in gephi (5k nodes, 25k edges);</p>
<p>Whenever I click on "Center on Graph" button, the Zoom slider stops working. If the file is saved in this situation, this error stays even after reopening Gephi. </p>
<p>Closing this graph fi... | <p>After doing some tests, I realized that an easy way to fix the problem is using the mouse wheel.</p>
<p>It changes the zoom level, and also fix the zoom slider.</p>
|
Websphere 8.5. won't start up after Java 7 SDK update <p>We have a Websphere 8.5 with Fix Pack 5 config, first we did use Java SDK 7.1.2.10. I removed this and installed Java SDK 7.1.3.40 but now I won't start the DMGR or nodes. I also doesn't start when I switch too Java SDK 6.</p>
<p>This is the error we get:</p>
<... | <p>Since there is no fixpack 5 for WebSphere Application Server traditional 8.5, I assume you're talking about 8.5.5 fixpack 5 or 8.5.5.5. According to <a href="http://www-01.ibm.com/support/docview.wss?uid=swg27005002" rel="nofollow">http://www-01.ibm.com/support/docview.wss?uid=swg27005002</a>, 8.5.5.5 is shipped wi... |
How to pass/make an object/variable accessible inside a callback function which is called by a third party library? <p>How to make <code>globalObject</code> accessible by <code>callbackFunction</code>?</p>
<p>I am using a third party library <code>library.h</code> which has a method <code>libraryFunction</code>. The o... | <p>If the library really takes a function pointer (not a generalized Callable like std::function) and does not offer the ability to pass a context or user pointer to your callback, you have to make your global object global (with all its drawbacks):</p>
<pre><code>#include <stdio.h>
#include "library.h"
static ... |
Collatz Structure Loop <p>I am trying to create a Collatz structure that asks the user how many times they would like to run it. Then it loops the code incrementing each time by 3 (n = n + 3). While the code partially works, it continues to repeat the previous process that is finished, e.g. with an input of 5 and runni... | <p>It looks to me like you aren't terminating the child process once it completes, you're just letting it continue the parent's main loop spawning more processes. Also, you were running a process and waiting for it which buys you nothing over letting your parent process just do the calculations -- instead spawn all th... |
Device build fails after upgrading to Xcode 8 <p>Since upgrading to Xcode 8 I cannot run any app on my iPhone. The build fails with error:</p>
<blockquote>
<p>error: Task failed with exit 0 signal 11</p>
</blockquote>
<p>I can run the apps on the simulators, just not on a device.
The full error message:</p>
<block... | <p>Use automatically manage signing:</p>
<p>Go to Target --> General --> Signing, check the Automatically manage siging.</p>
|
get the data associate with cell in Selected event <p>I am doing a form generator app to be developed in jquery/javascript.
I am using a html table an in order the cell to be selectable I am using jquery 'selectable' api. I have attached some metadata to the cells while initializing the cells and now I want to access ... | <p>You can get the <code>data-element</code> attribute of the selected cell with:</p>
<pre><code>$(ui.selected).data("element")
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-j... |
How to sum all elements in a tuple <p>In Swift, i.e. a tuple <code>let tp = (2,5,8)</code>.</p>
<p>What's the simplest and smartest way to sum it up, other than traditionaly as below?</p>
<p><code>let sum = tp.0 + tp.1 + tp.2</code></p>
| <p>Your approach is the most straightforward. An alternative is harder to read, but it works, too:</p>
<pre><code>let s = Mirror(reflecting: x).children.map {$1 as! Int}.reduce(0,+)
</code></pre>
<p><code>Mirror(reflecting: x).children</code> obtains a sequence of name-value pairs representing the original tuple. Eac... |
ReactiveCocoa, Module compiled with Swift 2.3 cannot be imported in Swift 3.0 issue. How to fix? <p>I have 2 Xcodes in my Mac(7.3.1 & 8.1). I want to work with ReactiveCocoa so I installed it via Cocoapods and later with Carthage. And when I import later in my ViewController <code>import ReactiveCocoa</code> I get ... | <p>Referring to the latest <a href="https://github.com/ReactiveCocoa/ReactiveCocoa" rel="nofollow">documentation</a> (github):</p>
<blockquote>
<p>"This documents the RAC 5 which targets Swift 3.0.x ..."</p>
</blockquote>
<p>I assume that should not install 4.x version. try to "pod 'ReactiveCocoa'" -for installing... |
Return count of records in SQL <p>I have one table like
â</p>
<pre><code>âSQL> select * from CRICKET_DETAILS;
TEAM1 TEAM2 WINNER
-------------------- -------------------- --------------------
INDIA PAKISTAN INDIA
INDIA SRILANKA ... | <p>I would go with <code>group by</code> and <code>union all</code>:</p>
<pre><code>select team, count(*), sum(won), sum(lost)
from ((select team1 as team,
(case when winner = team1 then 1 else 0 end) as won,
(case when winner = team1 then 0 else 1 end) as lost
from cricket_details c... |
How to read 2 different dataframes from single CSV file in R? <p>Suppose we have 2 dataframes like this in single CSV file as:</p>
<pre><code>Name C1 C2 C3 C4
aa 1 2 3 4
bb 3 4 6 5
cc 10 2 5 6
TT 44 2 2 6
#
Name C1 C2 C3 C4
aa 1 2 3 4
bb 3 4 6 5
cc 10 2 5 6
TT 44 2 ... | <p>Here's an example</p>
<pre><code>writeLines(
con = tf <- tempfile(fileext = ".csv"),
text = "Name C1 C2 C3 C4
aa 1 2 3 4
bb 3 4 6 5
cc 10 2 5 6
TT 44 2 2 6
#
Name C1 C2 C3 C4
aa 1 2 3 4
bb 3 4 6 5
cc 10 2 5 6
TT 44 2 3 6")
txt <- readLines(tf)
sep <- grep("^#", txt)[1]
df1 <- read.table(text = txt[1:(... |
Dagger 2 : error while getting a multiple instances of same object with @Named <p>How can i get multiple instances of same return type like cursor </p>
<p>for example :-</p>
<pre><code>Module
@CursorScope
public class CursorModule {
@Provides
Cursor provideSongCursor(
@Named("Song") Musician mus... | <p>when you want to provide multiple variable of one type you must use <code>@Named</code> annotation like below:</p>
<pre><code>Module
@CursorScope
public class CursorModule {
@Provides
@Named("songCursor")
Cursor provideSongCursor(
@Named("Song") Musician musician) {
return musician.getApplicationContext... |
C++ output string without '\n' or endl will output '#' in the end of string <p>On ubuntu16.04, I use g++ to compile such code:</p>
<pre><code>#include <iostream>
int main()
{
std::cout << "Hello World!";
return 0;
}
</code></pre>
<p>if the string does not end with '\n' or use 'std::endl' at the l... | <p>It doesn't, it's your bash prompt.</p>
<p>You can reproduce your problem with <code>echo</code>:</p>
<pre class="lang-bash prettyprint-override"><code># echo "Hello, World!"
Hello, World!
# echo -n "Hello, World!"
Hello, World!#
</code></pre>
|
Exception handling in code layers in java <p>I have two layers in my project say A & B. Layer A functions throw set of exceptions Ae1, Ae2, Ae3. Layer B functions throw exceptions Be1, Be2,Be3, Be4. Layer B functions are called from different functions in Layer A. </p>
<p>A function in layer A can throws more than... | <p>Since Java 7 you can do this:</p>
<pre><code> try{
function1InLayerB();
} catch(Be1 | Be2){
throw new Ae3;
} catch(Be4){
throw new Ae1;
}
</code></pre>
<p>Thus you avoid repetition when the common exception happens in catch blocks.</p>
<p>For Java 6 and less:</p>
<pre>... |
Energy drink scrape in python <p>I want to scrape the energy drink in india by ml</p>
| <p>If you have the IMDB id's use the MovieMeter API vs scraping:</p>
<pre><code>library(moviemeter) # devtools::install_github("hrbrmstr/moviemeter")
library(purrr)
imdb_ids <- c("tt1107846", "tt0282552", "tt0048199")
map_df(imdb_ids, function(x) {
mm <- mm_get_movie_info(x)
mm <- map(mm, ~. %||% NA) #... |
How to add < in TextInput. To show message like < Back <p>how can i insert < in TextInput. I want to show message like < Back.</p>
<p>I tried entering the < directly but it gives compile time error.</p>
<p>thanks in advance.</p>
| <p>You can wrap the text with brackets like that:</p>
<pre><code><Text>{'< Back'}</Text>
</code></pre>
|
Two Words in one String with space <p>I am trying to read inputs from file. I have line like this:
"Peter Brown Ashley Granger". There are two empty strings, name1 and name2. I want to get Peter Brown as name1 and Ashley Granger as name2. How can i do that ? </p>
| <p>Read the two parts, then put them together.</p>
<p>Something along these lines:</p>
<pre><code>std::string full_name;
std::string part1;
std::string part2;
if (stream >> part1 >> part2)
{
full_name = part1 + " " + part2;
}
</code></pre>
|
(Android + Firebase) Automatically sending push notifications on child added <p>So I'm trying to make a group chat for an Android app using Firebase. What I want to do is send automatic notifications to users whenever a child is added to the realtime database (i.e when someone else sends a message to the group chat I w... | <p>I believe this is not yet implemented on Firebase. I think you can ask them directly <a href="https://firebase.google.com/support/contact/bugs-features/" rel="nofollow">here</a>. </p>
|
Laravel CsrfToken expires on refresh after switching servers <p>I know my issue is not because of Laravel but most likely the php configuration (sessions), but I am not sure what to check. I was running this particular project on a <code>homestead</code> and it was fine. Now after I submit a form (it's a steps controll... | <p>Do you send a csrf token with the form you submit? If not: how did you build up your form, with FormBuilder or Html?</p>
<p><strong>FormBuilder</strong></p>
<p>In the formbuilder the CSRF token is already posted so it's not needed to send it.</p>
<p><strong>Html</strong></p>
<pre><code><form method="POST" act... |
Spark container failed. Shall I trust the results I got? <p>I have a quite long Spark job only consisting of a map operation.
I tried to launch it several times with different number of partitions, executors, and the maximum amount of memory I could give (16G + 2G of overhead).
During my last attempt few executors were... | <p>I think output will be correct because you have _SUCCESS file and also if some of you executor dies because of out of memory spark is fault tolerant so the work load will be transfer to the other executor.</p>
|
Typescript debug with line number <p>Opening up the console in a browser shows the javascript line number of a function call or error message.</p>
<p>But I am using TypeScript which is being compiled to Javascript.</p>
<p>Is there a way I can get the line numbers for TypeScript?</p>
<p>I am using VSCode as my editor... | <p>There are source maps, but the simple thing to do is to navigate to the source, provided that for development it's not being uglified and rollified and minified, in that case you need source maps. </p>
<p>Otherwise simply using the generated JavaScript file usually points to what the issue might be in the source co... |
Mac beeps when I type end parantheses in commented block of Python <p>Why, when I type an end parantheses in a commented out area in IDLE, does mac sound the error beep, and how can I stop it?</p>
| <p>Various programs, including IDLE, sometimes ask the computer to 'beep' when the user does something that the program considers an error. In general, to not hear a beep, you can 1) stop doing whatever provokes the beep, 2) turn your speaker down or off, or 3) plug in earphones and not wear them while editing.</p>
|
Unable to pass values to controller from jquery function <p>My Codeigniter view needs to pass <code>textbox</code> values to another function in the calling <code>controller</code> as follows. But when i click the mouse unable to pass values to controller from jquery function. Nothing happen in click event.</p>
<p><st... | <p>You are using ajax so first disable default form submission</p>
<pre><code>$("#send").click(function(e) {
e.prevenntDefault(); //default form submit
e.stopPropagation();
var postUrl = '<?php echo base_url(); ?>' + 'main/display';
name = $("#textbox").val();
$.post(postUrl, {name :name },fu... |
@Input with promise Angular2 <p>I have the parent component like this:</p>
<pre><code>import { Component } from '@angular/core';
import { UrlService } from '../../services/url.service';
@Component({
selector: 'wrapPost',
templateUrl: './app/html/wrapPost.component.html',
})
export class WrapPost {
dataPos... | <p>What about </p>
<pre><code><navigation></navigation>
<posts [dataPost]="dataPost | async"></posts>
<loading class="noteCommonAlign"></loading>
<pagination [dataPost]="dataPost | async"></pagination>
</code></pre>
|
C: main() returning an array always equals to 56 <p>I wonder what happens when I play with the return value of the <code>main</code> function.</p>
<p>I found that if I return an array variable from <code>main</code> (which is supposed to be the exit status) and print the exit status in shell, the output is always 56. ... | <p>Your program returns a pointer. It's not an "array" as you put it in the question. Because the name of an array evaluates to the address of its first item (which is the same as address of the array itself).</p>
<p>In C, the value returned from the <code>main</code> function is interpreted as the <a href="https://en... |
Convert phpMyAdmin exported database to older version. utf8mb4 issues <p>I want to move my MySQL database to an older version server (5.7 to 5.1).<br>
I get errors because it is created using <code>utf8mb4</code> .<br>
If i manually change <code>utf8mb4</code> to <code>utf8</code> the data become unreadable because of ... | <p>It seems I've figured out a solution.<br>
Use at export <code>mysql40</code> compatibility mode, replace <code>utf8mb4</code> with <code>utf8</code> and change the character set of tables from phpmyadmin to <code>utf8_unicode_ci</code>.<br>
Hope this will save some time from a fellow in future.</p>
|
How to select data from db using angular variable in php <p>I want to write select query in php to get data from database using variable from front-end. In other words I need to do something like this:
SELECT email FROM users WHERE token = '$token'
What I currently have, I have code which posts my variables to back... | <p>first thing is try to var_dump($_POST), or try to var_dump($data) on your test.php</p>
|
How to construct array of objects inside $.each(? <p>I have little experience with array of objects so please bare with me.
My current code pushes the key into normal array but i want to push both key and value in to array of object. I appreciate if an expert show me how this can be done.Thanks</p>
<p>Javascript to cr... | <p>If you just replace </p>
<pre><code>MyArray.push(key);
</code></pre>
<p>with </p>
<pre><code>var o = {};
o[key] = value;
MyArray.push(o);
</code></pre>
<p>It would do that, but you seem to want to iterate over each <code>dict</code>, and then get the value of each <code>key</code> inside the parent <code>dict</... |
Angular2 - Display image <p>I created a Angular2 app that allows the user to upload images. I want to implement a preview option. However, when i try to imperilment it the image doesn't show up. How do i achieve this feature? </p>
<p>UploadComponent.ts</p>
<pre><code>import * as ng from '@angular/core';
//import { UP... | <p>The way you try it, you don't get the image URL with <code>fileInput.target.files[0]</code>, but an object.</p>
<p>To get an image URL, you can use <code>FileReader</code> (<a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader" rel="nofollow">documentation here</a>)</p>
<pre><code>onFileChange(fileI... |
VideoJS Swf Remove Right Click Menu <p>i want disabling context menu , i never worked with actionscript , after some search i find this code for disabling context menu :</p>
<pre><code>stage.addEventListener(MouseEvent.RIGHT_CLICK, function(e:MouseEvent):void {});
stage.addEventListener(MouseEvent.CONTEXT_MENU, functi... | <blockquote>
<p><em>"I find this code for disabling context menu... I want know how can apply it in <code>VideoJS.as</code>"</em>.</p>
</blockquote>
<p>Open <a href="https://github.com/videojs/video-js-swf/blob/master/src/VideoJS.as" rel="nofollow"><strong><code>VideoJS.as</code></strong></a>... Find the following ... |
Robolectric different threads in Android Studio vs. Gradle tests <p>why are thread names different when I start a Robolectric test from Android Studio vs. the Gradle build?</p>
<p>e.g. consider this simple test:</p>
<pre><code>@RunWith(RobolectricTestRunner.class)
public class RobolectricRxThreadTest {
@Test
... | <p>I just reproduced the issue, but I wonder why do you need this test?</p>
<p>If you really want to check main thread then the correct way would be:</p>
<pre><code> assertThat(Thread.currentThread()).isEqualTo(Looper.getMainLooper().getThread());
</code></pre>
<p>And this test pass from AS and console both runs.</p... |
chrome extension native message not received in c# app <p>I am trying to communicate between chrome extension and c# app using native messaging. I have refered the link
<a href="https://developer.chrome.com/extensions/nativeMessaging" rel="nofollow">nativeMessaging</a></p>
<p>In my extension there are 2 menu buttons,... | <p>I am able to communicate now. What I changed is</p>
<ol>
<li>Created windows form app as native app, previously it was console app. Don't know why but extension could not communicate with console app.
<ol start="2">
<li>Instead of running .bat from json run direct native app.</li>
</ol></li>
</ol>
|
database "db/development.sqlite3" does not exist - how to fix? <p>a friend deployed my application on Heroku, and it works fine there. But I can not open my application on local server. Can anyone help? </p>
<p>When going on localhost i get the following error message: </p>
<p>ActiveRecord::NoDatabaseError
FATAL: dat... | <p>Update your <code>database.yml</code></p>
<pre><code>default: &default
adapter: postgresql
encoding: utf8
development:
<<: *default
database: your_app_development
username: your_usernmae
password: your_password
</code></pre>
|
Why is a switch case statement unable to work with properties of an Enum? <p>I am writing a simple game in which I use an Enum, <code>CommandManager</code>, to store information about the possible commands and what each one does. The main purposes of this Enum is to be able to print out a menu of available commands, as... | <blockquote>
<p>Am I right in thinking that properties of Enums simply cannot be used in switch statements? </p>
</blockquote>
<p>You are.</p>
<blockquote>
<p>If this is the case, why?</p>
</blockquote>
<p>Because the "labels" for a switch statement need to be <em>compile time</em> constants, and the properties ... |
How to ignore folder in GitHub correctly? <p>In my <code>.gitignore</code> file I added a path to folder I don't want to see in GitHub website:</p>
<pre><code>Results/.ipynb_checkpoints/
</code></pre>
<p>Then I push this changes:</p>
<pre><code>git commit -a -m "add ignore"
git push origin master
</code></pre>
<p>B... | <p>You need to remove the folder now that it is in the .gitignore. You can do this by deleting the folder locally, adding changes, commit it and then push it. If you need the folder in your local repository you can then recover it by making a backup, before deleting it. </p>
<p>If you however do not want to remove the... |
how to check in a pandas DataFrame entry exists by (index, column) <p>I have searched and searched but I can't find how to test whether a pandas data frame entry exists by (index, column).</p>
<p>for example:</p>
<pre><code>import pandas
df = pandas.DataFrame()
df.ix['apple', 'banana'] = 0.1
df.ix['apple', 'orange']... | <p>You can check for the existence in index and columns:</p>
<pre><code>('kiwi' in df.index) and ('apple' in df.columns)
</code></pre>
<p>Or you can use a try/except block:</p>
<pre><code>try:
df.ix['kiwi', 'apple'] += some_value
except KeyError:
df.ix['kiwi', 'apple'] = some_value
</code></pre>
<p>Note tha... |
delete an array element in MATLAB <p>In MATLAB, we can delete an object by</p>
<pre><code>o = obj();
delete o;
</code></pre>
<p>Can we explicitly delete an object in an array?</p>
<pre><code>arr = {obj(), obj(), obj()};
delete arr{1}; % ???
</code></pre>
<p>Also, does MATLAB release the memory if we call delete exp... | <p>First off, this line</p>
<pre><code>delete o;
</code></pre>
<p>does not do what you think it does. In <em>command syntax</em>, o is interpreted as a string, and this will delete a file named "o" in your current working directory.</p>
<p>If you want to delete the object <code>o</code> then you need to use <em>func... |
flashdata codeigniter with array <p>I have problem with array on flashdata codeigniter to send alert, if without framework this code work correcly, I modified this to codeigniter, but it does not work.</p>
<p>Controller Code:</p>
<pre><code> function reply(){
$id = $this->input->post('id');
$err = a... | <p>you could set array to flashdata session using the simple way</p>
<pre><code>$array_msg = array('first'=>'<p>msg 1</p>','second'=>'<p>msg2</p>');
</code></pre>
<p>then pass it to session</p>
<pre><code>$this->session->set_flashdata('msg',$array_msg);
</code></pre>
<p>then acce... |
Tomcat runs in Eclipse but can't do a GET request <p>I created just a dynamic web project in Eclipse and when I run the the helloworld webapp then I see the index.html page with no problems screenshot:
<a href="http://i.stack.imgur.com/2tYQb.png" rel="nofollow"><img src="http://i.stack.imgur.com/2tYQb.png" alt="enter i... | <p>Change the line of code has annotation <code>@WebServlet</code> become to:</p>
<pre><code>@WebServlet(name = "HelloServlet", urlPatterns = "/HelloServlet")
</code></pre>
<p>You will be happy.</p>
<p>To avoid exception (When application context is <code>/</code>), you should check <code>request.getContextPath()</c... |
Modify/flatten result from sql one to many query with multiple joins <p>Consider the following simplified schema example -</p>
<pre><code>sys_systems
id name
---------------------
1 Inventory
sys_shadow_data
id primary_key_value sys_schema_id field_value
-------------------------------------------------... | <p>Your query amounts to pivoting the joined tables on the <code>field_name</code> column from the <code>sys_schemas</code> table to generate new columns for each value in that column. You can <code>GROUP BY</code> the inventory ID and name, then use <code>MAX</code> to collapse the two records into one:</p>
<pre><co... |
To find distance between two letters <p>In this question,it is required to find the distance between two letters
for eg. Between A and E,the letters are B,C,D.So,distance between the letters is number of letters+1 ie,4 here.But I'm not getting the output for this code </p>
<pre><code> import java.util.*;
publ... | <p>You have extra nextLine method calls. Modified your code to make it working.</p>
<pre><code>import java.util.Scanner;
public class LetterDistance {
public static void main(String[] args) {
String s1, s2;
Scanner input = new Scanner(System.in);
s1 = input.nextLine();
s2 = input... |
Separate package names for iOS and Android <p>I currently have a native app published to the App Store and Google Play and both have different package names. I was wanting to know if there is there a way to tell NativeScript to use a one package name for iOS and a different one for Android? Thank you.</p>
| <p>Yep, you can absolutely do that. For iOS, include a <code>CFBundleIdentifier</code> flag in your <code>app/App_Resources/iOS/Info.plist</code> file.</p>
<pre><code><key>CFBundleIdentifier</key>
<string>com.mycompany.myapp</string>
</code></pre>
<p>And for Android, update the <code>android.d... |
MYSQL / Spring Hibernate: Connection has already been closed <p>So, I want to do 32 write operations under one @Transactional. I have set maxActive connections as "100", maxIdle as "50" (which I believe are quite high), maxTimeout is set to 150000 and removeAbandonedTimeout = 3000</p>
<p>Here's the tomcat configuratio... | <p>The setting you used has removeAbandonedTimeout set to 3 sec. Looking for the documentation for <strong>org.apache.tomcat.jdbc.pool.DataSourceFactory</strong> which you are using at <a href="https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html" rel="nofollow">https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.htm... |
STM32F4 PWM and interrupt with the same timer <p>I have a STM32F407x. Is it possible to have a PWM Signal on a Pin and at the same time getting a timer interrupt if the UPPER value is reached? I tried the following code, but I only get once an interrupt (count stays at 1 forever if I use the debugger), but the PWM Sign... | <p>If you're trying to count pulses or stop at a certain pulse this post may help</p>
<p><a href="https://my.st.com/public/STe2ecommunities/mcu/Lists/cortex_mx_stm32/Flat.aspx?RootFolder=%2Fpublic%2FSTe2ecommunities%2Fmcu%2FLists%2Fcortex_mx_stm32%2FStop%20PWM%20output%20after%20N%20steps&FolderCTID=0x012002007709... |
Datagrid context menu only for single select <p>I have a datagrid with context menu. How prevent context menu showing for multiple selection? I tried to add attached property but got an error <strong>The attachable property 'ContextMenuVisibilityMode' was not found in type 'ProcessIntasnceActivitiesView'</strong></p>
... | <p>Handle <code>ContextMenuOpening</code> event of <code>DataGrid</code>.</p>
<pre><code>private void DataGrid_ContextMenuOpening_1(object sender, ContextMenuEventArgs e)
{
e.Handled = (sender as DataGrid).SelectedItems.Count > 1;
}
</code></pre>
<p>You can put this logic into an <code>AttachedProp... |
importing ViewPagerIndicator in android stidio <p>I want to use ViewPagerIndicator in my app. So I need its library. I find these 2 links for downloading, <a href="https://github.com/JakeWharton/ViewPagerIndicator" rel="nofollow">Link1</a> and <a href="http://viewpagerindicator.com/" rel="nofollow">Link2</a>.</p>
<p>B... | <p>You can use this dependency (it's an analog):</p>
<pre><code>compile 'fr.avianey.com.viewpagerindicator:library:2.4.1.1@aar'
</code></pre>
|
failed to set up pod network: Unhandled Exception killed plugin <p>I'm trying to play with kubernetes 1.4 install with rkt containers on CoreOS beta (1185.1.0).</p>
<p>In general I have two CoreOS pc machines at home that are configured with etcd2 tls certificates.</p>
<p>I patched the coreos-kubernetes automated gen... | <p>The "Unhandled Exception Killed plugin" error message is being generated by the Calico CNI plugin. From my experience that means it is unlikely to be something wrong with the <code>calico-node.service</code> causing that error.</p>
<p>As such it is <em>probably</em> something subtly wrong with you CNI network conf... |
Python While Loop <p>Write function lastfirst() that takes one argument a list of strings of the format â and returns a list consisting two lists: </p>
<p>(a) A list of all the ï¬rst names </p>
<p>(b) A list of all the last names </p>
<pre><code>>>> lastfirst(['Gerber, Len', 'Fox, Kate', 'Dunn, Bob'])
... | <p>With the while loop you need a counter or iterator since the for loop is not creating the iterator for you.</p>
<pre><code># http://stackoverflow.com/questions/39934280/python-while-loop
# uses an iterator effectively making it a for loop
def lastFirst_iterator(nameList):
nameListIter = iter(nameList)
fir... |
Ways to do inter-frame video compression in AVFoundation <p>I've created a process to generate video "slideshows" from collections of photographs and images in an application that I'm building. The process is functioning correctly, but creates unnecessarily large files given that any photographs included in the video ... | <p>It looks like you're </p>
<ol>
<li>appending a bunch of redundant frames to your video, </li>
<li>labouring under a misapprehension: that video files must have a constant framerate that is high, e.g. 30fps.</li>
</ol>
<p>If, for example, you're showing a slideshow of 3 images over a duration of 15 seconds, then y... |
Navigation between page <p>I'm writing a small WPF app with only 3 pages (for now). I'm using DataTemplate and ContentControl in the main window to display and switch between my pages. (See code sample below). It's working but I have a few concerns:</p>
<ol>
<li><p>The DataTemplate use parameterless constructor only. ... | <p>It looks like my problem has been very well explained in this <a href="http://stackoverflow.com/questions/5462040/what-is-a-viewmodellocator-and-what-are-its-pros-cons-compared-to-datatemplates">post</a>.</p>
<p>In short, I need to implement a ViewModelLocator pattern in order to fix all my concerns.</p>
|
gawk and grep using same pattern but need different treatement for escape sequence <p>I have a bash shell script (named <code>testawk</code> to replace a line containing a pattern (1st arg) with one or more than one line (2nd arg) and operates on the filename given in 3rd arg. The shell script is given below: </p>
<pr... | <p>This should do what I think you are asking for:</p>
<pre><code>if awk -v nm2="$2" -v nm1="$1" 'index($0,nm1){f=1; $0=nm2} 1; END{exit !f}' "$3" > "${3}.bak"
then
mv "${3}.bak" "$3"
# do stuff with modified file "$3"
else
rm -f "${3}.bak"
# do stuff with unmodified file "$3"
fi
</code></pre>
<p>N... |
Calculation in 1 line VBS <p>How can I make this Calculator work if the user enters 1+1?
It only works if I enter 1 + 1 ;C
The calculation must be in 1 line.</p>
<pre><code>x = inputbox("Calculation", "Calculator", "1+1")
y = Split(x)
if not isnumeric (y(0)) then
wscript.quit
end if
if not isnumeric (y(2)) then
ws... | <p>Try next code snippet (commented for explanation):</p>
<pre><code>Dim ii, sOperator, strExpr, y
strExpr = inputbox("Calculation", "Calculator", "1+1")
' insert spaces around all operators
For Each sOperator in Array("+","-","*","/","%")
strExpr = Trim( Replace( strExpr, sOperator, Space(1) & sOperator &... |
NoClassDefFoundError. Why??? How can I fix it? <p>I wrote my classloader:</p>
<pre><code>package ru.sberbank.school.homework8;
import ru.sberbank.school.homework8.plugin.Plugin;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class PluginManager extends ClassLoader {
private ... | <p>You get this error because you don't provide the correct FQN of your class, indeed in your <code>load</code> method, you try to find the class corresponding to <code>pluginName + "." + pluginClassName</code> that will be in your case <code>plugin.PluginImpl</code> but the package name of your class <code>PluginImpl<... |
Spring Boot Response Entity doesn't return JSON <p>When i return my POJO from RestController it's transforms in JSON object.
But when i try to return <code>new ResponseEntity<>("success", HttpStatus.CREATED);</code>
controller returns plain-text. What's wrong?</p>
<p>My RestController:</p>
<pre><code> @Reque... | <p><code>"success"</code> as a String cannot be cast to JSON format. Hence, spring controller returns plain/text.Generally, for any object to be cast as JSON, it must be in the format of a key value pair, so all POJOs can be converted to corresponding key-value pairs where <code>key</code> is the property name and <cod... |
Inequality in Mysql with count() <p>I have the following structure : </p>
<pre><code>Table Author :
idAuthor,
Name
+----------+-------+
| idAuthor | Name |
+----------+-------+
| 1 | Renee |
| 2 | John |
| 3 | Bob |
| 4 | Bryan |
+----------+-------+
Table Publication:
idPublication,
... | <p>When you use aggregation funcion you can filter with a proper operator named HAVING </p>
<p>Having worok on the result of the query (then pn the aggrgated result like count() ) instead of where that work on the original value of the tables rows</p>
<pre><code>SELECT author.name, COUNT(name)
FROM author INNER JOI... |
Using if statement to deal cards <p>I am trying to deal an x amount of cards to a player depending on how many they already have in their hand (max of 5). But to insure that you don't get dealt the same card twice, or dealt a card that has already been played I've used an if Statement.</p>
<pre><code>Card[] hand = new... | <p>Your <code>for</code> loop is always executed exactly five times, no matter how often you encounter a <code>null</code> within the loop's body. You can verify this by manipulating the size of <code>deck</code> to something <code>< 5</code>. If your method were working correct, it should get caught in an endless l... |
read file line by line including multiple newline characters <p>I am trying to read a file of unknown size line by line including single or multiple newline characters.
for example if my sample.txt file looks like this</p>
<pre><code>abc cd er dj
text
more text
zxc cnvx
</code></pre>
<p>I want my strings to l... | <p>If the lines are just short and there aren't many of them, you could use <code>realloc</code> to reallocate memory as needed. Or you can use smaller (or larger) chunks and reallocate. It's a little more wasteful but hopefully it should average out in the end.</p>
<p>If you want to use just one allocation, then find... |
How to handle special characters like : and , in .htaccess rules? <p>How i can get <strong>a</strong> and <strong>b</strong> values from urls like this:<br></p>
<pre><code>http://127.0.0.1:8080/a:4522,b:846
</code></pre>
<p>I add this code to .htaccess for redirect all links to index.php but not working when use <cod... | <p>For <code>http://127.0.0.1:8080/a:4522,b:846</code> the request URI equals to <code>/a:4522,b:846</code>. And the <code>.htaccess</code> directives put the request URI into <code>path</code> GET parameter. So you can simply parse <code>$_GET['path']</code> in PHP:</p>
<pre><code><?php
$vars = [];
if ($path = iss... |
sql : find the lowest amount of loan at each branch <p>what does mean by this question ? I am confused . Does it say to find the lowest amount or the branch names who have the lowest amount . Help me to figure this out .</p>
<p>My_query(finding the lowest amount) : </p>
<pre><code>select min(total_amount)
from (sele... | <p>I think the question is asking for the smallest loan made at each branch. In this case you can use the following query:</p>
<pre><code>SELECT branch_name,
MIN(amount) as smallest_loan
FROM loan
GROUP BY branch_name
</code></pre>
|
Firebase Retrieve Data - Could not cast value <p>First, I have checked these answers that do not help me :
<a href="https://stackoverflow.com/questions/30151782/swift-json-error-could-not-cast-value-of-type-nsarraym-0x507b58-to-nsdic">Swift JSON error, Could not cast value of type '__NSArrayM' (0x507b58) to ... | <p>I took your code and shrunk it down a bit for testing, and it's working. (note Firebase 2.x on OS X and Swift 3 but the code is similar)</p>
<p>Firebase structure:</p>
<pre><code> "what-am" : {
"results" : [ {
"code" : "738/B738",
"data" : "Boeing",
"engines" : "Rolls"
}, {
"code" ... |
Swift 3 Core Data "Entity" error: `Use of undeclared type` <p><code>Use of undeclared type 'Transcription'</code></p>
<p>I'm following this simple tutorial of Core Data in Swift 3 (<a href="https://learnappdevelopment.com/uncategorized/how-to-use-core-data-in-ios-10-swift-3/" rel="nofollow">https://learnappdevelopment... | <p>Highlight the Data Model, go to Editor -> Create NSManagedObject Subclass...</p>
<p>This solved the error</p>
|
merge two lists of dictionaries in python? <p>I have two lists of dictionaries:</p>
<pre><code>old = [{'a':'1','b':'2'},{'a':'2','b':'3'},{'a':'3','b':'4'},{'a':'4','b':'5'}]
new = [{'a':'1','b':'100'},{'a':'2','b':'100'},{'a':'5','b':'6'}]
</code></pre>
<p>How can I merge two lists of dictionaries to get:</p>
<pre>... | <p>If 'a' is the real key here and b is the value, imo it would be easier to convert the list of dicts into one dict, process the merge and then convert it back. This way you can use the standard functions.</p>
<p>Convert into one dict where a is the key:</p>
<pre><code>def intoRealDict(listOfDicts):
values = []
... |
Change structure of object in JavaScript <p>I have some data</p>
<pre><code>arr = {
'a': ['1', '2', '3'],
'b': ['2', '3', '4'],
'c': ['3', '5', '6'],
}
</code></pre>
<p>How can I change this to</p>
<pre><code>newArr = {
'1': ['a'],
'2': ['a', 'b'],
'3': ['a', 'b', 'c'],
'4': ['b'],
'5': ['c'],
'6':... | <p>Just change one line</p>
<pre><code>newData[key].forEach(value => {
</code></pre>
<p>to</p>
<pre><code>oldData[key].forEach(value => {
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang... |
spring security - how to provide a list of intercepting URL's <p>In my spring project having a bunch of users and User Levels. so that need to provide a list of intercepting url's and its access control. currently it is written in spring security xml file. how can i make it simple to do?</p>
<p>any suggestions will be... | <p>May be if you want to put them in application properties, then use WebSecurityConfigurerAdapter</p>
<p>in <strong>application.properties</strong></p>
<pre><code>url1 = /admin
url2 = /reservation/**
</code></pre>
<p>===</p>
<pre><code>@Configuration
@EnableWebSecurity
@PropertySource("classpath:application.prope... |
jquery add event to cells into a board <p>How can I add an event to cells inside a board?
I have a grid of 9x9 and I want to add an event to them, for example, this is part of my grid in HTML:</p>
<pre><code><div class="container">
<div class="dad-board">
<div class="dad-row">
<d... | <p>Two things:</p>
<p>In <code>$('#dad-board > dad-cell')</code> the class name should be <code>.dad-cell</code>.</p>
<p><code>.dad-cell</code> are <code>div</code> and as such them don't have a <code>focusout</code> event. I think you meant <code>$('#dad-board > .dad-cell input')</code>.</p>
<p>In order to ma... |
Use of deleted copy constructor in the singleton <p>I've implemented the singleton pattern like <a href="http://stackoverflow.com/questions/270947/can-any-one-provide-me-a-sample-of-singleton-in-c/271104#271104">this</a>, there is my code:</p>
<p><strong>header file:</strong></p>
<pre><code>class Settings_manager{
pu... | <p>Consider what you're trying to do here:</p>
<pre><code>Settings_manager set = Settings_manager::get_instance();
</code></pre>
<p>You have your singleton, <code>get_instance()</code>, and you're trying to copy it? That would kind of defeat the purpose of singleton if you could just... create two of them right?</p>
... |
Dagger 2: Providing dependencies in Application Module vs injecting them <p>I was trying to add Dagger 2 to my android app.
As far as I understand, Dagger will construct my object(which I am trying to inject) as long as its' dependencies are provided(in a Module) or they are injected using some form of injection(const... | <p>Both are the same. Constructor injection basically eliminates the need to write a provider method. As a rule of thumb, I mostly use it for classes with a no-args constructor for easy injection, like Util classes. </p>
|
Yii2 GridView how to display column only when some filter is active <p>I have a Yii2 GridView with implemented sortable option (I used <a href="https://github.com/kotchuprik/yii2-sortable-widgets" rel="nofollow">kotchuprik extension</a>) which add one column with drag'n'drop ability. The problem is that I need to be ab... | <p>You could use the visible property of the column </p>
<p>Yii\grid\DataColumn has visible property.
This attrribute accepts boolean values,
but you can dynamically using an expression that boolean value. eg:</p>
<pre><code> use Yii;
...
'columns' => [
['class' => 'yii\grid\S... |
Function.prototype does not show all in-built properties and methods in console <p>This <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype" rel="nofollow">MDN article</a> on <code>Function.prototype</code> objects lists native properties and methods however when I ... | <p>This is simply how the browser decides to "show" you the object, because reasons.</p>
<p>In Chrome you can do <code>dir(Function.prototype)</code> and it will list all methods and properties of the object. Firefox may have something similar.</p>
<p>UPDATE: In Firefox you can simply right click on what it shows you... |
Mine Tweets between two dates in Python <p>I would like to mine tweets for two keywords for a specific period of time. I currently have the code below, but how do I add so it only mine tweets between two dates? (10/03/2016 - 10/07/2016) Thank you!</p>
<pre><code>#Import the necessary methods from tweepy library
from t... | <p>You can't. Have a look at <a href="http://stackoverflow.com/questions/26205102/making-very-specific-time-requests-to-the-second-on-twitter-api-using-python">this question</a>, that is the closest you can get.</p>
<p>The Twitter API does not allow to search by time. Trivially, what you can do is fetching tweets and ... |
How to use JGit to get list of changes in files? <p>Using JGit, I want to get a list of changes in files of a commits as is possible with <code>git log --full-history -p -1 <hash-id></code>.</p>
<p>Is this possible? If so, how do you do it?</p>
<p>I know how to get each commit, and look at the commit message: <... | <p>JGit has a very simple <code>diff</code> command that would write textual diff of the changes between two commits to an output stream.</p>
<p>For example:</p>
<pre class="lang-java prettyprint-override"><code>OutputStream outputStream = ...
List<DiffEntry> diffEntries = git.diff().setOutputStream( outputStre... |
ContentCachingResponseWrapper Produces Empty Response <p>I'm trying to implement filter for logging requests and responses in <code>Spring MVC</code> application.
I use the following code:</p>
<pre><code>@Component
public class LoggingFilter extends OncePerRequestFilter {
private static final Logger LOGGER = Logg... | <p>After couple of houurs of struggling, I've finally found the solution.</p>
<p>In short, <code>ContentCachingResponseWrapper.copyBodyToResponse()</code> should be called in the end of the filter method.</p>
<p><code>ContentCachingResponseWrapper</code> caches the response body by reading it from response output str... |
PDO fetch returns only first row <p><strong>UPDATE 2:</strong>
I kindly asked to unmark this question as duplicate as it is not a duplicate of the other question, which after some research I discovered the problem and provided an effective answer, which the person that marked my question as duplicate didn't provide sta... | <p>Add a while loop,</p>
<pre><code>while($row= $sth->fetch( PDO::FETCH_ASSOC )){
echo $row['your_field_name'];
}
</code></pre>
<p>Or you can use <code>fetchAll</code></p>
<pre><code>$row= $sth->fetchAll();
print_r($row);
</code></pre>
|
C++ problems in vector usage <p>Let's say I input values between 0-109 several times. I have a vector that counts how many times a value in a specific range(0-9, 10-19,...100-109) has occurred. </p>
<p>For instance, my vector initially: </p>
<p>0 0 0 0 0 0 0 0 0 0 0</p>
<p>I give 15, 16, 88, 95, 94, 5 as input.Vecto... | <p>This is not want you expect:</p>
<pre><code>for(decltype(vec.size()) i:vec)
{
cout<<vec[i];
}
</code></pre>
<p>A range based for gives you element values, not element indices.</p>
<p>You likely want:</p>
<pre><code>for(const auto& e : vec)
{
cout<<e;
}
</code></pre>
|
Laravel: Can't access Eloquent relationship <p>I've made Post and User models and defined a one to many relationship between the two like so:</p>
<p><strong>User.php</strong></p>
<pre><code><?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
... | <p>As far as I can see, the <code>User</code> relation in the Post model is causing the exception. So, when you call:</p>
<pre><code>{{ $blog_post->user->name }}
</code></pre>
<p>it can't find the user associated with that post. I am guessing that the foreign key for <code>User</code> table is not the same as ... |
openssl_private_encrypt and "error:0E06D06C...NCONF_get_string:no value" <p>I can generate all keys fine, when I go to encrypt the file I get an error thrown at me: <code>error:0E06D06C:configuration file routines:NCONF_get_string:no value</code> but googling and checking stackoverflow only shows people with problems g... | <p>There was an error in my fopen dir somehow and it just broke. It is all good and fixed now, thanks.</p>
|
Qt Error while building first project[Windows] <p>I installed Qt Creator 4.1 Based on Qt 5.7.0 from <a href="https://www.qt.io/" rel="nofollow">https://www.qt.io/</a>.</p>
<p>I tried to build a Qt Widgets Application, but I got the following error in the Console output:</p>
<pre><code>Error while building/deploying p... | <p>You should install visual studio 2015 or vs c++ 2015 compiler so you can use vs compiler 2015 with Qt or use Qt with MinGW compiler</p>
|
Binding object into callback using arrow function <p>I'm new to javascript and ES6. How do I bind the <code>websocket</code> object into the callback I supply to <code>subscribe</code>? It feels wrong/wierd to me that I am accessing the <code>websocket</code> object from "global" scope like this. </p>
<pre><code>const... | <p>You will likely want to use a <a href="https://en.wikipedia.org/wiki/Closure_(computer_programming)" rel="nofollow">closure</a>:</p>
<pre><code>let webSocket = new WebSocket(url);
let takesWebSocket = socket => {
return () => {
// do stuff with the websocket
};
};
let subscribeCallback = takesWebSoc... |
UIFieldBehaviour for snapping dynamic view to top, bottom or middle of screen <p>I'm using a draggable view which is the width and height of the screen and can be moved up or down on the screen depending on the pan gesture. </p>
<p>When the pan gesture has ended I want it to snap to three different y positions, top, ... | <p>It was easier than I thought.
I'm using the new UIViewPropertyAnimator and when pan .ended I just check whether the targets y-position should snap to the top, bottom or middle by comparing it to the height of the UIScreen.</p>
<pre><code> animator!.addAnimations({
print(target.frame.origin.y)
... |
AV Capture Contents of a *View* to a Movie <p>I know how to use AVFoundation to capture the contents of a <em>screen</em> to a movie file, but I'd like to instead capture the contents of an NSView instead. My app does some things in a view and currently to generate a movie file I have to record the whole screen (croppe... | <p>I've had some success with a pure CALayer tree using a CARenderer into an old-style OpenGL context into a CVOpenGLTextureCache / AVAssetWriter, then also displaying it to a regular GL view or layer for display.</p>
<p>There are some quirks in the old renderer, however, so you might have to tweak things a bit to mak... |
How to read sets of pairs from a list of integers? <p>The idea being the program would read the 4 integers submitted and would have one result if there were 2 sets of pairs and another result if otherwise. </p>
<p>For example, <code>(3, 5, 3, 5)</code> and <code>(3, 3, 3, 3)</code> would have one effect, but <code>(2,... | <p>How about:</p>
<pre><code>from collections import Counter
def has_two_pair(array):
two_most_common = Counter(array).most_common(2)
counts = [count for _, count in two_most_common if count > 1]
length = len(counts)
return length > 0 and all([(length > 1 and count > 1) or count > 3 for... |
moment.js uses the month as day instead the day <p>I'm using currently moment.js (moment-with-locales.js - v.2.14.1) in my project. I want to remove the time of my datetime string to get only the date. But if I use the <code>.format()</code> method of moment.js I got an incorrect date.</p>
<p>I want to format this dat... | <p>It depends on your locale. <code>en-US</code> locate means moment will parse by "month day year". So, you need to parse with the pattern as well:</p>
<pre><code>var date = moment('08.10.2016 11:00','DD.MM.YYYY HH:mm').format('DD.MM.YYYY')
</code></pre>
|
moved all models to Models folder, have now can't use attach() <p>I've decided to move all models inclusing User to Models folder and everything works except for one thing. I have a this trait</p>
<pre><code>trait Favoritable{
public function favorites()
{
return $this->belongsToMany(Album::class, '... | <p>Wanted to comment but:
Sorry that this is an answer but can't comment before I have 50 reps':</p>
<p>Can you please provide the User class? Including the uses of other classes/traits.</p>
|
Image loading from url still not fast enough using a background queue <p>I started a background queue to load the image first, and then update the UIImageView's image in the main queue.</p>
<pre><code> int i = 0;
for (UIImageView *imageView in self.featuredPhotoImageViewCollection) {
dispatc... | <p>U are misunderstanding the use of background queue. In your code, iOS will start to execute your background code while leaving the main queue not doing anything until it is finished the background code and then update your image view in the main queue. </p>
<p>Therefore, no matter u use what queue in the background... |
Is it good practice to save separate server and ui files in R Shiny? <p>There are at least two different ways of storing and deploying a Shiny app. </p>
<p>The first is to save <code>server.R</code> and a <code>ui.R</code> in <code>dir</code>files and run the app from the directory via <code>runApp(appDir = dir)</code... | <p>According to the tutorial video from RStudio's website (the makers of Shiny), it makes no difference technically.</p>
<p><a href="https://www.rstudio.com/resources/webinars/how-to-start-with-shiny-part-1/" rel="nofollow">https://www.rstudio.com/resources/webinars/how-to-start-with-shiny-part-1/</a></p>
|
Check browser cookie in AngularJS <p>I set cookie by <code>hapi-auth-cookie</code>. Can i check in AngularJS is cookie exists? </p>
<h2>data.js</h2>
<pre><code>server.register(Cookie, function(err) {
if(err) {
console.error(err);
throw err;
}
server.auth.strategy('session', 'cookie', {
password: 'f... | <p>You can access like this if you are using <a href="https://docs.angularjs.org/api/ngCookies/service/$cookies" rel="nofollow"><code>Angularjs 1.4</code></a> and above</p>
<pre><code>angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a co... |
How to create new string in C++ by two other ones? <p>I want to create <code>string</code> <code>"hello1world</code> by this two strings:</p>
<pre><code>string s1 = "hello"
string s2 = "world"
</code></pre>
<p>I do this:</p>
<pre><code>string my_str;
sprintf(my_str, "%s1%s", s1, s2);
</code></pre>
<p>But I have an... | <p>Please don't use <code>sprintf</code>. It only supports <code>char[]</code> strings, i.e. C strings. So that's why it doesn't compile when you pass <code>std::string</code>.</p>
<p>With <code>std::string</code>, a simple <code>+</code> is all you need:</p>
<pre><code>string my_str = s1 + s2;
</code></pre>
|
Swift - Firebase function signInWithEmail don't execute in the first call <pre><code>@IBAction func loginEmailButton(sender: AnyObject) {
FIRAuth.auth()?.signInWithEmail(email.text!, password: password.text!, completion: { (user, error) in
if error != nil {
if let errCode = FIRAuthEr... | <p>Its asynchronous issue. <strong><code>signInWithEmail</code></strong> makes an asynchronous call to the server, meaning this call will be loaded in a different network thread, which takes some time to complete, but since your <code>performSegueWithIdentifier</code> is put outside the completionBlock so it get's exec... |
Accuracy of clock() function in C <p>I have some code that tries to determine the execution time of a code block.</p>
<pre><code>#include <time.h>
#include <stdio.h>
int main()
{
clock_t start_t, end_t, total_t;
int i;
start_t = clock(); //clock start
printf("Starting of the program, start_t ... | <p>The unit of time used by the <code>clock</code> function is arbitrary. On most platforms, it is unrelated to the processor speed. It's more commonly related to the frequency of an external timer interrupt â which may be configured in software â or to a historical value that's been kept for compatibility through... |
Android: Cast SDK v3 CastOptionsProvider not detected in release build <p>I've correctly declared CastOptiponsProvider manifest.xml</p>
<pre><code> <meta-data
android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
android:value="org.lao.yao.kd.cast.CastOptionsProvide... | <p>I've run into this issue before with Proguard and external libraries (especially Google's stuff). I used the following in the <code>proguard-rules.pro</code> file:</p>
<pre><code>-keep class org.lao.yao.kd.cast.CastOptionsProvider { *; }
</code></pre>
<p>Also your CastIntentReceiver.</p>
<pre><code>-keep class or... |
Angular 2 Chart.js and NG2-Charts Not Binding Data Objects After Updates To Project <p>I have been working on a project in Angular-2 using the starter project found <a href="https://github.com/mrholek/CoreUI-Free-Bootstrap-Admin-Template/tree/master/Angular2_CLI_Full_Project" rel="nofollow">here</a>, </p>
<p>The proje... | <p>There is no longer the selector <code>base-chart</code> valid.</p>
<p>Per ng2-charts <a href="https://github.com/valor-software/ng2-charts/blob/development/CHANGELOG.md#breaking-changes" rel="nofollow">changelog</a></p>
<blockquote>
<p>base-chart component became baseChart directive so you need to convert</p>
</... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.