title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
QT add Label to certain position | <p>I'm new to QT and I want to know how to add a label on a certain position by code. I create a new application and I have these code automatically:</p>
<pre><code>#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
</code></pre>
<p>I want to add a label to a certain position, for example, its geometry is (10, 10, 30, 80). How do I do this by code? Someone can help me?</p> | 0 |
How to Fix "Variable Lengths Differ" Error in r When Doing a Linear Regression | <p>I'm trying to make a for loop that loops through my data frame and runs a linear regression of all columns against <code>AcquisitionTime</code> which is a double. All columns are of the same length. Eventually I want to just use one of the apply functions instead of the for loop to do this but I am really new at r and the apply functions don't make sense to me. </p>
<pre><code>##pdf("ROIs_vs_AcquisitionTime_lm.pdf")
x = 0
for (i in names(raw_data)){
if(x > 9){
fit <- lm(i ~ AcquisitionTimes, data = raw_data)
##print(ggplotRegression(fit))
}
x <- x + 1
}
##dev.off()
</code></pre>
<p>When I run this code I get this error:</p>
<pre><code>Error in model.frame.default(formula = i ~ AcquisitionTimes, data = raw_data,:
variable lengths differ (found for 'AcquisitionTimes')
</code></pre>
<p>What is causing this error? I checked to see if I had any other data frames named raw_data, but I did not. I even cleared the objects in R to see if that would help. Everywhere I read says that this is either because the variable <code>AcquisitionTimes</code> does not exist in the data frame or because there are identical variable names somewhere in my data. So far I haven't found any.</p> | 0 |
Is it possible to use Dependency Injection with xUnit? | <p>I have a test class with a constructor that needs an IService.</p>
<pre class="lang-c# prettyprint-override"><code>public class ConsumerTests
{
private readonly IService _service;
public ConsumerTests(IService servie)
{
_service = service;
}
[Fact]
public void Should_()
{
//use _service
}
}
</code></pre>
<p>I want to <strong>plugin my DI container of choice</strong> to build the <strong>test class</strong>.</p>
<p>Is this possible with <strong>xUnit</strong>?</p> | 0 |
Invert 0 and 1 in a binary array | <p>Is there a function in Numpy to invert 0 and 1 in a binary array?
If</p>
<pre><code>a = np.array([0, 1, 0, 1, 1])
</code></pre>
<p>I would like to get:</p>
<pre><code>b = [1, 0, 1, 0, 0]
</code></pre>
<p>I use:</p>
<pre><code>b[a==0] = 1
b[a==1] = 0
</code></pre>
<p>but maybe it already exist something in Numpy to do this.</p> | 0 |
break row from specific td to next line | <p>I have a table in which <code><td></code> are coming dynamically and some <code><td></code> will come with specific class on which the row should break and other <code><td></code> should start from next line.</p>
<p>As the <code><td></code> are coming dynamically i can't create another <code><tr></code> i want to break it with css.</p>
<p>I have seen other examples on stackoverflow but they are showing breaking all the <code><td></code> to next line but i want to break from specific <code><td></code> and all then other <code><td></code> in continuation from this <code><td></code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>td.break {
display:block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tr>
<td>hdv</td>
<td>hdv</td>
<td class="break">hdv</td>
<td>hdv</td>
<td>hdv</td>
<td>hdv</td>
<td>hdv</td>
<td>hdv</td>
<td>hdv</td>
<td class="break">hdv</td>
<td>hdv</td>
<td>hdv</td>
<td>hdv</td>
<td>hdv</td>
<td>hdv</td>
<td>hdv</td>
<td>hdv</td>
<td>hdv</td>
</tr>
</table></code></pre>
</div>
</div>
</p>
<p>I tried using <code>display:block</code> but its not working if appying on single <code><td></code>.</p> | 0 |
Bootstrap/flexbox card: move image to left/right side on desktop | <p>I'm trying to build following card layout using Bootstrap 4 with flexbox enabled. Picture is taken from my current implementation and it works like expected.</p>
<p><a href="https://i.stack.imgur.com/huXvo.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/huXvo.jpg" alt="Current mobile layout"></a></p>
<p>HTML structure is following:</p>
<pre><code><section>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="card">
<div class="card-block">
<h4 class="card-title">Curabitur gravida vestibulum imperdiet.</h4>
<p class="card-text">Cras convallis ut turpis vitae facilisis. Morbi eu augue vel quam efficitur rhoncus vitae eget lectus. Cras augue ligula, aliquam ut enim ut, feugiat imperdiet sem. Integer sed mi quis nisl eleifend interdum.</p>
<p class="card-text">Cras convallis ut turpis vitae facilisis. Morbi eu augue vel quam efficitur rhoncus vitae eget lectus. Cras augue ligula, aliquam ut enim ut, feugiat imperdiet sem.</p>
<a href="#" class="btn btn-primary">Read More</a>
</div>
</div>
</div>
<div class="col-md-6">
<img class="card-img-bottom" src="img1.jpg" alt="" title="">
</div>
</div>
</div>
</section>
</code></pre>
<p>Now when I scale to larger screen, I got following output (which is expected with Bootstrap but not wanted one):</p>
<p><a href="https://i.stack.imgur.com/GGfLx.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/GGfLx.jpg" alt="enter image description here"></a></p>
<p>What I would like to see instead is:</p>
<p><a href="https://i.stack.imgur.com/75aE7.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/75aE7.jpg" alt="enter image description here"></a></p>
<p>So my question is, how I can properly implement this kind of layout? I'm using flex-box, so Bootstrap columns (col-*) are always same height which is exactly what I want. But I should remove the paddings between two columns, then make both columns content always to cover 100% of parent height, and finally make sure that picture maintains it's aspect ratio, so it should be cropped from the center like I have in example.</p>
<p>I've Googled and tried many different solutions but all of them seems to be overly complex or "hacky" solutions. So I'm wondering is it true that there is no easy way to implement this kind of layout...?</p>
<p>Note: solution doesn't have to be Bootstrap related, general solution for this kind of problem is even better.</p> | 0 |
JSON object to Datatable in C# | <p>I've the following c# Class</p>
<pre><code>public class Output
{
public string name { get; set; }
public string[] results { get; set; }
}
</code></pre>
<p>Which results in below output after execution</p>
<pre><code>[
{
"name": "Field1",
"results": [
"One",
"Two",
"Three"
]
},
{
"name": "Field2",
"results": [
"One",
"Two",
"Three",
"Four"
]
}
]
</code></pre>
<p>Is there any utility or library which can convert my JSON into DataTable. I checked the <a href="https://stackoverflow.com/questions/7641004/how-to-convert-json-into-datatable">JSON.net example</a> but that require the JSON must be in below format to convert that into table</p>
<pre><code>string json = @"[{"Field1" : "One", "Field2": "One"}
{"Field1" : "Two", "Field2": "Two"}
{"Field1" : "Three", "Field2": "Three"}
{"Field1" : "", "Field2": "Four"}];
var table = JsonConvert.DeserializeObject<DataTable>(json);
</code></pre>
<p>Also, Any clue if my JSON can be converted in the format needs for JsonConvert.DeserializeObject</p>
<p>It's not duplicate, the question marked in duplicate discusses the best way instead the complex JSON format example i provided here.</p>
<p><strong>Expected Output</strong></p>
<pre><code>Field1, Field2
One, One
Two, Two
Three, Three
null,Four
</code></pre> | 0 |
Is it possible to prevent cookies to be sent in every HTTP request? | <p>I recently found (here: <a href="https://stackoverflow.com/questions/1336126/does-every-web-request-send-the-browser-cookies">Does every web request send the browser cookies?</a>) that every HTTP request contains the cookies related to a domain every time a request is made to that same domain.</p>
<p>Given this, what happens when the request is not sent through a browser but from Node.js, for example? Is it possible that no information is sent in the request?
Is it also possible to prevent it to be sent in the browser requests?</p> | 0 |
How to get syslog file in Redhat | <p>I have installed collectd on my Red Hat Enterprise Linux 7.2 server.</p>
<p>I have also installed it on ubuntu 14.04 server.</p>
<p>In ubuntu when I run the service collectd and face any error , I can easily go to <code>/var/log/syslog</code> to get the error message and reason.</p>
<p>But when I get error message on my Red Hat server like this :</p>
<p><a href="https://i.stack.imgur.com/BEAkH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BEAkH.png" alt="enter image description here" /></a></p>
<p>and I go to <code>/var/log</code> I did not get the file syslog.</p>
<p>As I don't have much/no experience with Red Hat , can some body tell me where to find syslog file in Red Hat server in order to trouble shoot my errors.</p>
<p>Thank you.</p> | 0 |
Angular2 version RC.6 "directives" inside @Component Error | <p>I am using Angular2 and have downloaded package.json from the official website. When I am trying to use "directives" inside @Component decorator I am getting this error. </p>
<p>I have attached my code ERROR:</p>
<pre><code>[ts]
Argument of type '{ selector: string; template: string; directives: string;
}' is not assignable to parameter of type 'ComponentMetadataType'.
Object literal may only specific known properties, and 'directives' does not
exist in type 'ComponentMetadataType'.
(property) directives: string
</code></pre>
<p>This is my code:</p>
<pre><code>import { Component } from '@angular/core';
import { PeopleListComponent } from './people-list/people-list.component';
@Component({
selector: 'my-app',
template: '<h1>{{ title }}</h1>',
directives: '' //ERROR //NOT ABLE TO RECOGNIZE
})
export class AppComponent {
title = "My title";
}
</code></pre>
<p>Here is my package.json:</p>
<pre><code> {
"name": "angular2-quickstart",
"version": "1.0.0",
"scripts": {
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
"lite": "lite-server",
"postinstall": "typings install",
"tsc": "tsc",
"tsc:w": "tsc -w",
"typings": "typings"
},
"license": "ISC",
"dependencies": {
"@angular/common": "2.0.0-rc.6",
"@angular/compiler": "2.0.0-rc.6",
"@angular/compiler-cli": "0.6.0",
"@angular/core": "2.0.0-rc.6",
"@angular/forms": "2.0.0-rc.6",
"@angular/http": "2.0.0-rc.6",
"@angular/platform-browser": "2.0.0-rc.6",
"@angular/platform-browser-dynamic": "2.0.0-rc.6",
"@angular/router": "3.0.0-rc.2",
"@angular/upgrade": "2.0.0-rc.6",
"core-js": "^2.4.1",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.11",
"systemjs": "0.19.27",
"zone.js": "^0.6.17",
"angular2-in-memory-web-api": "0.0.18",
"bootstrap": "^3.3.6"
},
"devDependencies": {
"concurrently": "^2.2.0",
"lite-server": "^2.2.2",
"typescript": "^1.8.10",
"typings":"^1.3.2"
}
}
</code></pre> | 0 |
How to add rank column? | <p>I would like to select records and determine rank number for each similar data.</p>
<p>My data is as follows.</p>
<pre><code>MEMBER ID | LOAN AMOUNT
1 | 2,000.00
2 | 1,000.00
3 | 4,000.00
4 | 1,000.00
</code></pre>
<p>The result I wanted is shown below. </p>
<pre><code>RANK|MEMBER ID|LOAN AMOUNT
1 |3 |4,000.00
2 |1 |2,000.00
3 |2 |1,000.00
3 |4 |1,000.00
</code></pre>
<p>RANK is a new column. I am using MS SQL server 2008 and created a view table as shown below but it does not resulting to what is wanted.</p>
<pre><code> select rank=count(*), s1.MemberID, s1.Loan_Amount
from (select MemberID, Loan_Amount from vwPrintTop20Borrowers) s1
group by s1.MemberID, s1.LOAN_AMOUNT
order by rank, s1.Loan_amount DESC
</code></pre>
<p>Please help. Thanks! :)</p> | 0 |
Is it possible to download a websites entire code, HTML, CSS and JavaScript files? | <p>Is it possible to fully download a website or view all of its code? Like for example I know you can view page source in a browser but is there a way to download all of a websites code like HTML, CSS and JavaScript then run it on my own server or change it up and run that?</p> | 0 |
How to change the color of the status bar in Android? | <p>I would like to change the color of highlighted bar in Android Studio:</p>
<p><a href="https://i.stack.imgur.com/0jfDq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0jfDq.png" alt="enter image description here"></a></p>
<p>How can i do it?</p> | 0 |
Git clone leads to deleted & untracked files | <p>I am new to Git.</p>
<p>I just installed Git (2.9.3) for Windows (10), then I opened git-bash and did a <code>git clone <remoteURL></code>. A new folder is created with the whole copy of the remote repository, which is good. But then I run a <code>git status</code> and I get a ton of <code>deleted</code> files (I suppose all the files that just got copied) ready <code>to be committed</code>, and the three main folders under the repository folder are <code>untracked</code>. The <code>deleted</code> files actually exist on my drive though!</p>
<p>I am pretty sure my git status should be clean instead. What is happening?</p>
<p><a href="https://stackoverflow.com/questions/10361322/git-status-for-cloned-repository-shows-file-deleted">This</a> about deleted files didn't help (I didn't use <code>checkout</code>), neither did <a href="https://stackoverflow.com/questions/19569805/git-clone-followed-by-status-shows-untracked-files">this</a> about untracked files (I'm not using Mac OS).</p> | 0 |
How to make the server backend of a mobile app? | <p>I am an Android developer and I want to make an app which shows users on a map and performs tasks based on their location. </p>
<p>The whole model of the app has to run in the server. I need an API which:</p>
<ul>
<li>Receives user location</li>
<li>Performs calculations based on the location of the users</li>
<li>Sends response to specific users with the results</li>
</ul>
<p>The problem is that I have 0 experience in doing server side programming. </p>
<p>Can you please suggest me a way of making the server?</p>
<p>I checked the <em>Google Colud Platform</em> and <a href="https://www.youtube.com/watch?v=v5u_Owtbfew&feature=player_embedded" rel="noreferrer">this</a> video. The video addresses the connection between the app and the server, but what I really need is coding the model and deploying it on the cloud.</p>
<p>What is the way for me to build the API for such an app, as a developer with no server side programming experience?</p>
<p>Can you suggest me a tutorial which goes trough the process of building a cloud backend for a mobile app?</p> | 0 |
Adding files to standard images using docker-compose | <p>I'm unsure if something obvious escapes me or if it's just not possible but I'm trying to compose an entire application stack with images from docker hub. </p>
<p>One of them is mysql and it supports adding custom configuration files through volumes and to run .sql-files from a mounted directory. </p>
<p>But, I have these files on the machine where I'm running docker-compose, not on the host. Is there no way to specify files from the local machine to copy into the container before it runs it entrypoint/cmd? Do I really have to create local images of everything just for this case?</p> | 0 |
How to capture packets for single docker container | <p>There have many container running on the host. And I want to capture packets for the one container of these. Is there any way to do this?</p> | 0 |
How to get current camera position from view matrix? | <p>I've implemented a simple arc-ball camera and it works well - when I use the mouse, I update the View matrix with roll, pitch and yawn.</p>
<p>However, in order to properly calculate specular reflection, I need current camera position in world space which is not updated per-se when applying rotation.</p>
<p>Do you guys know how can retrieve current position from the View matrix? Or is there another way to update this?</p> | 0 |
Euclidean Distance Matrix Using Pandas | <p>I have a .csv file that contains city, latitude and longitude data in the below format:</p>
<pre><code>CITY|LATITUDE|LONGITUDE
A|40.745392|-73.978364
B|42.562786|-114.460503
C|37.227928|-77.401924
D|41.245708|-75.881241
E|41.308273|-72.927887
</code></pre>
<p>I need to create a distance matrix in the below format (please ignore the dummy values):</p>
<pre><code> A B C D E
A 0.000000 6.000000 5.744563 6.082763 5.656854
B 6.000000 0.000000 6.082763 5.385165 5.477226
C 1.744563 6.082763 0.000000 6.000000 5.385165
D 6.082763 5.385165 6.000000 0.000000 5.385165
E 5.656854 5.477226 5.385165 5.385165 0.000000
</code></pre>
<p>I have loaded the data into a pandas dataframe and have created a cross join as below:</p>
<pre><code>import pandas as pd
df_A = pd.read_csv('lat_lon.csv', delimiter='|', encoding="utf-8-sig")
df_B = df_A
df_A['key'] = 1
df_B['key'] = 1
df_C = pd.merge(df_A, df_B, on='key')
</code></pre>
<ul>
<li>Can you please help me create the above matrix structure?</li>
<li>Also, is it possible to avoid step involving cross join?</li>
</ul> | 0 |
How do you force SQL Server to release memory? | <blockquote>
<p>What's a good way of checking how much (actual) memory is currently
being used vs. how much is SQL Server allocated to itself?</p>
</blockquote>
<p>I've been resorting to <strong>memory_utilization_percentage</strong> but that doesn't seem to change after running the following to release memory.</p>
<pre><code>SELECT [Memory_usedby_Sqlserver_MB] = ( physical_memory_in_use_kb / 1024 ) ,
[Memory_utilization_percentage] = memory_utilization_percentage
FROM sys.dm_os_process_memory;
DBCC FREESYSTEMCACHE ('ALL')
DBCC FREESESSIONCACHE
DBCC FREEPROCCACHE
SELECT [Memory_usedby_Sqlserver_MB] = ( physical_memory_in_use_kb / 1024 ) ,
[Memory_utilization_percentage] = memory_utilization_percentage
FROM sys.dm_os_process_memory;
</code></pre>
<p>A solution is to drop <strong>max server memory</strong> for the SQL Server and increase it again to force SQL Server to release unused but allocated memory. However an issue with this approach is that we cannot be sure how far to reduce <strong>max server memory</strong>, hence run the risk of killing SQL Server. This is why it's important to understand how much SQL Server is 'actually' using before reducing the value for <strong>max server memory</strong>.</p> | 0 |
na.fill in Spark DataFrame Scala | <p>I am using Spark/Scala and I want to fill the nulls in my DataFrame with default values based on the type of the columns.</p>
<p>i.e String Columns -> "string", Numeric Columns -> 111, Boolean Columns -> False etc.</p>
<p>Currently the DF.na.functions API provides na.fill<br>
<code>fill(valueMap: Map[String, Any])</code> like </p>
<pre><code>df.na.fill(Map(
"A" -> "unknown",
"B" -> 1.0
))
</code></pre>
<p>This requires knowing the column names and also the type of the columns.</p>
<p>OR</p>
<pre><code>fill(value: String, cols: Seq[String])
</code></pre>
<p>This is only String/Double types, not even Boolean.</p>
<p>Is there a smart way to do this?</p> | 0 |
Run bash script after login | <p>I have a bash script with a series of whiptail menus that allows a user to setup their new system, which is Ubuntu server, with no GUI, just CLI (it's going to be a Virtual Machine image).</p>
<p>I'm already forcing a root login by editing <code>/etc/default/grub</code> and <code>/etc/init/tty1.conf</code>, so the user is dropped directly into the root command prompt. From there the user has to type in <code>./whiptail.sh</code> to start the script and get the whiptail prompts to further setup their host.</p>
<p>Now, I'd like for my script to be what appears up after the the login occurs instead of the user being dropped to the command prompt. How can I do this?</p> | 0 |
How to read webapi responses with HttpClient in C# | <p>I have developed a small webapi which has a few actions and returns my custom class called <code>Response</code>.</p>
<p>The <code>Response</code> class</p>
<pre><code>public class Response
{
bool IsSuccess=false;
string Message;
object ResponseData;
public Response(bool status, string message, object data)
{
IsSuccess = status;
Message = message;
ResponseData = data;
}
}
</code></pre>
<p>My webapi with actions</p>
<pre><code>[RoutePrefix("api/customer")]
public class CustomerController : ApiController
{
static readonly ICustomerRepository repository = new CustomerRepository();
[HttpGet, Route("GetAll")]
public Response GetAllCustomers()
{
return new Response(true, "SUCCESS", repository.GetAll());
}
[HttpGet, Route("GetByID/{customerID}")]
public Response GetCustomer(string customerID)
{
Customer customer = repository.Get(customerID);
if (customer == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return new Response(true, "SUCCESS", customer);
//return Request.CreateResponse(HttpStatusCode.OK, response);
}
[HttpGet, Route("GetByCountryName/{country}")]
public IEnumerable<Customer> GetCustomersByCountry(string country)
{
return repository.GetAll().Where(
c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase));
}
}
</code></pre>
<p>Now where I am stuck is that I do not know how to read the response data returned from the webapi actions and extract json from my response class. After getting json how could I <code>deserialize</code> that json to the customer class.</p>
<p>This is the way I am calling my webapi function:</p>
<pre><code>private void btnLoad_Click(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8010/");
// Add an Accept header for JSON format.
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// List all Names.
HttpResponseMessage response = client.GetAsync("api/customer/GetAll").Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Request Message Information:- \n\n" + response.RequestMessage + "\n");
Console.WriteLine("Response Message Header \n\n" + response.Content.Headers + "\n");
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
Console.ReadLine();
}
</code></pre>
<h5>Questions</h5>
<ol>
<li><p>How to get the response class the webapi returns at the client side</p>
</li>
<li><p>How could I extract json from the response class</p>
</li>
<li><p>How to deserialize the json to the customer class at client side</p>
</li>
</ol>
<hr />
<p>I use this code but still getting an error.</p>
<pre><code> var baseAddress = "http://localhost:8010/api/customer/GetAll";
using (var client = new HttpClient())
{
using (var response = client.GetAsync(baseAddress).Result)
{
if (response.IsSuccessStatusCode)
{
var customerJsonString = await response.Content.ReadAsStringAsync();
var cust = JsonConvert.DeserializeObject<Response>(customerJsonString);
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
}
}
</code></pre>
<p>The error is:</p>
<blockquote>
<p>An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code</p>
<p>Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'WebAPIClient.Response[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.</p>
</blockquote>
<p>Why is the response causing this error?</p> | 0 |
Angular 2 - Directives declared yet still have errors | <p>In <code>RootModule</code>:</p>
<pre><code>@NgModule({
imports: [
ModuleA
],
declarations: [
ScrollToWhen
],
bootstrap: [BootComponent],
})
class RootModule {}
</code></pre>
<p>In one of the component template inside Module A, I use <code>ScrollToWhen</code>, but I got error: <code>Can't bind to 'scrollToWhen' since it isn't a known property of 'div'</code>.</p>
<p>Why?</p>
<p><a href="https://i.stack.imgur.com/ti8cb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ti8cb.png" alt=""></a></p>
<p><code>Error: Unexpected directive 'HbClass' imported by the module 'Module'</code></p> | 0 |
How to read data in Python dataframe without concatenating? | <p>I want to read the file f (file size:85GB) in chunks to a dataframe. Following code is suggested.</p>
<pre><code>chunksize = 5
TextFileReader = pd.read_csv(f, chunksize=chunksize)
</code></pre>
<p>However, this code gives me TextFileReader, not dataframe. Also, I don't want to concatenate these chunks to convert TextFileReader to dataframe because of the memory limit. Please advise.</p> | 0 |
Python/Tkinter - Identify object on click | <p>I am trying to create a program that changes the object colour on click from white to black or from white to black depending of the previous colour. I would want the program change the colour only if the object is a rectangle. How can I make the this happen?</p>
<p>Here is my code:</p>
<pre><code>import tkinter as tk
root = tk.Tk()
cv = tk.Canvas(root, height=800, width=800)
cv.pack()
def onclick(event):
item = cv.find_closest(event.x, event.y)
current_color = cv.itemcget(item, 'fill')
if current_color == 'black':
cv.itemconfig(item, fill='white')
else:
cv.itemconfig(item, fill='black')
cv.bind('<Button-1>', onclick)
cv.create_line(50, 50, 60, 60, width=2)
cv. create_rectangle(80, 80, 100, 100)
root.mainloop()
</code></pre>
<p>In this code the program changes the fill colour for any object. I would want it to change it only for rectangles.</p>
<p>Thanks for the help.</p> | 0 |
componentWillUnmount() not being called when refreshing the current page | <p>I've been having this problem where my code in the <code>componentDidMount()</code> method wasn't firing properly when refreshing the current page (and subsequently, the component). However, it works perfectly fine just navigating and routing through my website by clicking links. Refresh the current page? Not a chance.</p>
<p>I found out that the problem is that <code>componentWillUnmount()</code> doesn't trigger when I refresh the page and triggers fine clicking links and navigating my website/app.</p>
<p>The triggering of the <code>componentWillUnmount()</code> is crucial for my app, since the data that I load and process in the <code>componentDidMount()</code> method is very important in displaying information to users.</p>
<p>I need the <code>componentWillUnmount()</code> to be called when refreshing the page because in my <code>componentWillMount()</code> function (which needs to re-render after every refresh) I do some simple filtering and store that variable in a state value, which needs to be present in the <code>logos</code> state variable in order for the rest of the component to work. This does not change or receive new values at any time during the component's life cycle.</p>
<pre><code>componentWillMount(){
if(dataReady.get(true)){
let logos = this.props.questions[0].data.logos.length > 0 ? this.props.questions[0].data.logos.filter((item) => {
if(item.logo === true && item.location !== ""){
return item;
}
}) : [];
this.setState({logos: logos});
}
};
</code></pre>
<p><strong>Cliffs:</strong></p>
<ul>
<li>I do DB filtering in <code>componentWillMount()</code>method</li>
<li>Need it to be present in the component after refresh</li>
<li>But I have a problem where the <code>componentWillUnmount()</code> doesn't trigger when the page is refreshed</li>
<li>Need help</li>
<li>Please</li>
</ul> | 0 |
WKWebView does load resources from local document folder | <p>In my Swift iOS app, I want to download some dynamic HTML pages from a remote server, save them in the document directory, and display those pages from document directory.</p>
<p>I was using this to load the page:</p>
<pre><code>var appWebView:WKWebView?
...
appWebView!.loadRequest(NSURLRequest(URL: NSURL(fileURLWithPath: htmlPath)))
</code></pre>
<p>Everything works on the simulator, but when I moved to real phones, it just showed a blank page. I then connected to the app using Safari, and found it complained with "Failed to load resource".</p>
<p>I then tried to first read the content of the page at <code>htmlPath</code>, then use </p>
<pre><code>appWebView!.loadHTMLString()
</code></pre>
<p>to load the page. It works when the HTML page is simple. But if the HTML references something else, i.e. a JavaScript file also in the document directory (with an absolute path like <code><script src="file:////var/mobile/Containers/Data/Application/762035C9-2BF2-4CDD-B5B1-574A0E2B0728/Documents/xxxxx.js"></code>), it will fail to load.</p>
<p>Does anyone know why this happens, and how to resolve the issue?</p>
<p>More info:</p>
<ul>
<li>XCode version: 7.3.1</li>
<li>Deployment Target: 8.1 (I tried to use 9.3 too, but that didn't help.)</li>
</ul> | 0 |
Endless Scrolling RecyclerView is not working when items in list are minimum then screen size | <p>I have successfully implemented the Endless Scrolling using Recycler view. I am using <a href="https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews-and-RecyclerView" rel="noreferrer">this</a> code and this works perfectly but except with the following case </p>
<p><strong>Case 1:</strong> When the list has 2 items which are lesser then the screen size so its looks like the OnLoadMore calls again as it finds itself arriving to the end of the list </p>
<p><strong>What I am doing:</strong> I am getting the list from 1 fragment and then send this list to the other fragment and in that fragment there is a RecyclerView with the onScroll listner here it is as follows : </p>
<pre><code>recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount) {
// do something...
currentVisiblePosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
pageNumber = pageNumber + 1;
CallingMyApi();
}
});
</code></pre>
<p><strong>Confusions:</strong> </p>
<ul>
<li>My RecyclerView add on scroll listener run first time when the fragments gets initialized. where as there is no scrolling performed. </li>
<li>if there are lesser items let say 2 it runs always on fragment initiallized , in case of many items OnLoadMore methos does not runs. </li>
</ul>
<p>So i can guess that it is problem due to the less items in the list view How to control that please help me ?? </p>
<p><strong>Update 1: My Fragment Code</strong></p>
<pre><code>@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mAdapter = new EnrollmentSearchAdapter(getActivity(), parentList);
rvSearchEnrollments.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount) {
// do something...
if(parentList!=null && parentList.size()>3) { // just checking my own that 3 items should not be minimum to screen size , where as here it should be more flexible solution
currentVisiblePosition = ((LinearLayoutManager) rvSearchEnrollments.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
pageNumber = pageNumber + 1;
SearchSundaySchoolParentsCouples searchSundaySchoolParentsCouples = new SearchSundaySchoolParentsCouples(keyword, 20, pageNumber, getActivity());
searchSundaySchoolParentsCouples.execute();
}
}
});
rvSearchEnrollments.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));
rvSearchEnrollments.setAdapter(mAdapter);
}
</code></pre> | 0 |
Typescript overload arrow functions | <p>So we can do:</p>
<pre><code>export function myMethod (param: number) :number
export function myMethod (param: string) :string
export function myMethod (param: string | number): string | number {
if (typeof param === 'string') {
return param.toUpperCase()
} else {
return param + 1
}
}
</code></pre>
<p>Can I declare and implement it with arrow function?</p>
<pre><code>export var myMethodArror = (param: string): string
export var myMethodArror = (param: number): number
export var myMethodArror = (param: string | number): string | number => {
..
}
</code></pre>
<p>I am aware of that it is not possible to duplicate the variables declaration, but my question is: is it possible to make function overload using arrow notation?</p> | 0 |
Could not execute statement; SQL [n/a]; constraint [null]; | <p>I am getting this error while delete a row from a particular schema:</p>
<pre><code>Hibernate: select journal0_.id as id1_2_0_, journal0_.content as content2_2_0_, journal0_.filename as filename3_2_0_, journal0_.subject as subject4_2_0_, journal0_.tags as tags5_2_0_, journal0_.user_id as user_id6_2_0_, journal0_.version as version7_2_0_ from journal journal0_ where journal0_.id=?
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into subscription (journal_id, user_id, version, id) values (?, ?, ?, ?)
2016-09-03 01:08:01.581 WARN 13462 --- [nio-8080-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 23505, SQLState: 23505
2016-09-03 01:08:01.581 ERROR 13462 --- [nio-8080-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : Unique index or primary key violation: "UK_9XFQUT5UKXNSBX8NL2LR23TC5_INDEX_9 ON PUBLIC.SUBSCRIPTION(USER_ID, JOURNAL_ID) VALUES (9, 2, 10)"; SQL statement:
insert into subscription (journal_id, user_id, version, id) values (?, ?, ?, ?) [23505-191]
2016-09-03 01:08:01.598 INFO 13462 --- [nio-8080-exec-9] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2016-09-03 01:08:01.632 ERROR 13462 --- [nio-8080-exec-9] c.j.exceptions.ErrorController : Exception during execution of SpringSecurity application
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
</code></pre>
<p>Even though the delete method with proper arguments is called still it's running the insert query which is causing data violation issue.</p>
<p>Here is the model:</p>
<pre><code>@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames={"userId", "journalId"})})
public class Subscription {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Version
private Integer version;
private Integer userId;
private Integer journalId;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return this.id;
}
public void setVersion(Integer version) {
this.version = version;
}
public Integer getVersion() {
return this.version;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getUserId() {
return this.userId;
}
public void setJournalId(Integer journalId) {
this.journalId = journalId;
}
public Integer getJournalId() {
return this.journalId;
}
}
</code></pre>
<p>This is where the delete method is called:</p>
<pre><code>@Override
public void unsubscribeJournalForSubscriber(Journal journal, Account subscriber) {
Subscription subscription = new Subscription();
subscription.setJournalId(journal.getId());
subscription.setUserId(subscriber.getId());
this.subscriptionRepository.delete(subscription);
}
</code></pre> | 0 |
Adding Firebase to android Studio fails to resolve | <p>I am trying to add Firebase references to my android app but facing the following problem:</p>
<blockquote>
<p>Failed to resolve :com.google.firebase:firebase-core:9.0.0</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/J7jwL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J7jwL.png" alt="screenshot here"></a></p> | 0 |
How to create vCard using javascript? | <p>I found an <a href="https://github.com/enesser/vCards-js" rel="noreferrer">extension</a> to resolve my problem. But when i clone it to local, it doesn't have any example. </p>
<p>I am confused about how to use it. I try some method, but it not work for me.
Please show me how to use it or any extension to solve my problem?</p> | 0 |
Simplest example for streaming audio with Alexa | <p>I'm trying to get the new streaming audio API going. Is the following response valid? I'm getting a "there was a problem with the skill" error when I test it on my device. </p>
<p>Here is the code for my AWS-lambda function:</p>
<pre><code>def lambda_handler(event, context):
return {
"response": {
"directives": [
{
"type": "AudioPlayer.Play",
"playBehavior": "REPLACE_ALL",
"audioItem": {
"stream": {
"token": "12345",
"url": "http://emit-media-production.s3.amazonaws.com/pbs/the-afterglow/2016/08/24/1700/201608241700_the-afterglow_64.m4a",
"offsetInMilliseconds": 0
}
}
}
],
"shouldEndSession": True
}
}
</code></pre> | 0 |
Best practice for Swift methods that can return or error | <p>I’m practicing Swift and have a scenario (and a method) where the result could either be successful or a failure.</p>
<p>It’s a security service class. I have a method where I can authenticate with an email address and password, and want to either return a <code>User</code> instance if the credentials are correct, or throw some form of <code>false</code> value.</p>
<p>I’m a bit confused as my understanding of Swift methods is you need to specify a return type, so I have:</p>
<pre class="lang-swift prettyprint-override"><code>class SecurityService {
static func loginWith(email: String, password: String) -> User {
// Body
}
}
</code></pre>
<p>I’ve seen in Go and Node.js methods that return a “double” value where the first represents any errors, and the second is the “success” response. I also know that Swift doesn’t have things like errors or exceptions (but that may have changed since as I was learning an early version of Swift).</p>
<p>What would be the appropriate thing to do in this scenario?</p> | 0 |
Hash string with SHA512 in Swift | <p>Anyone knows how to reproduce PHP hashing method hash(‘SHA512’, $value, true) in swift ? I tried to use CommonCrypto C library with this code :</p>
<pre><code>extension String {
func digest(length:Int32, gen:(data: UnsafePointer<Void>, len: CC_LONG, md: UnsafeMutablePointer<UInt8>) -> UnsafeMutablePointer<UInt8>) -> String {
var cStr = [UInt8](self.utf8)
var result = [UInt8](count:Int(length), repeatedValue:0)
gen(data: &cStr, len: CC_LONG(cStr.count), md: &result)
let output = NSMutableString(capacity:Int(length))
for r in result {
output.appendFormat("%02x", r)
}
return String(output)
}
}
</code></pre>
<p>and used it like this :</p>
<pre><code>var digest = salted.digest(CC_SHA512_DIGEST_LENGTH, gen: {(data, len, md) in CC_SHA512(data,len,md)})
</code></pre>
<p>But I don't get the right output</p>
<p><strong>EDIT :</strong></p>
<p>I have some PHP code :</p>
<pre><code>echo base64_encode(hash('sha512', '8yOrBmkd', true)); // output: rlltLWeWaQCrfNTYMa0CcIs0mfLoHGAynrd+d8H65+rGAzHS/BSWsumwSmcxF9aAG9TIzXx+HOjArPyLL3herg==
</code></pre>
<p>And I want my swift code to output the same. The Base64 encoding is ok :</p>
<pre><code>let utf8str = input.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let base64Encoded = utf8str!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print("Encoded: \(base64Encoded)")
</code></pre>
<p>But the hashing part return an output the same value as this PHP code :</p>
<pre><code>echo base64_encode(hash('sha512', '8yOrBmkd', false)); // output: YWU1OTZkMmQ2Nzk2NjkwMGFiN2NkNGQ4MzFhZDAyNzA4YjM0OTlmMmU4MWM2MDMyOWViNzdlNzdjMWZhZTdlYWM2MDMzMWQyZmMxNDk2YjJlOWIwNGE2NzMxMTdkNjgwMWJkNGM4Y2Q3YzdlMWNlOGMwYWNmYzhiMmY3ODVlYWU=
</code></pre> | 0 |
In python, append dictionary value with each element in array | <p>Hi and thank you so much for your help!</p>
<p>I am sure this is a dumb question but I am trying to append a dictionary value with the elements within an array. Right now I can only get it to load the entire array of elements as one entry instead of separate values. Sorry if I am not explaining this well. Here is an example:</p>
<pre><code>Array = [4,5,6]
dictionary {'index'} = [1,2,3]
</code></pre>
<p>Here is what I am doing and it's wrong</p>
<pre><code>dictionary['index'].append(array)
</code></pre>
<p>It's wrong because if I inquiry how many elements are in dictionary ['index'][1] it returns 1 instead of 3. Look here:</p>
<pre><code>print range(len(dictionary['index'][0]))
</code></pre>
<p>The answer is 3, thats 1 2 and 3. however!</p>
<pre><code>print range(len(dictionary['index'][1]))
</code></pre>
<p>The answer is 1, [4,5,6]. I must be loading the array in incorrectly. Does anyone know what I am doing wrong? Thanks!</p> | 0 |
Reading text from image | <p>Any suggestions on converting these images to text? I'm using pytesseract and it's working wonderfully in most cases except this. Ideally I'd read these numbers exactly. Worst case I can just try to use PIL to determine if the number to the left of the '/' is a zero. Start from the left and find the first white pixel, then </p>
<p><a href="https://i.stack.imgur.com/kIrvO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kIrvO.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/iCqkW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iCqkW.png" alt="enter image description here"></a></p>
<pre><code>from PIL import Image
from pytesseract import image_to_string
myText = image_to_string(Image.open("tmp/test.jpg"),config='-psm 10')
myText = image_to_string(Image.open("tmp/test.jpg"))
</code></pre>
<p>The slash in the middle causes issues here. I've also tried using PIL's '.paste' to add lots of extra black around the image. There might be a few other PIL tricks I could try, but i'd rather not go that route unless I have to. </p>
<p>I tried using config='-psm 10' but my 8's were coming through as ":" sometimes, and random characters other times. And my 0's were coming through as nothing. </p>
<p>Reference to: <a href="https://stackoverflow.com/questions/31643216/pytesseract-dont-work-with-one-digit-image">pytesseract don't work with one digit image</a> for the -psm 10</p>
<p><strong>_____________EDIT_______________</strong>
Additional samples:</p>
<p><a href="https://i.stack.imgur.com/RCKPc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RCKPc.jpg" alt="enter image description here"></a>
1BJ2I]</p>
<p><a href="https://i.stack.imgur.com/wlFJJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wlFJJ.jpg" alt="enter image description here"></a>
DIS</p>
<p><a href="https://i.stack.imgur.com/4eGlZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4eGlZ.jpg" alt="enter image description here"></a>
10.I'10</p>
<p><a href="https://i.stack.imgur.com/0JqEW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0JqEW.jpg" alt="enter image description here"></a>
20.I20</p>
<p>So I'm doing some voodoo conversions that seem to be working for now. But looks very error prone:</p>
<pre><code>def ConvertPPTextToReadableNumbers(text):
text = RemoveNonASCIICharacters(text)
text = text.replace("I]", "0")
text = text.replace("|]", "0")
text = text.replace("l]", "0")
text = text.replace("B", "8")
text = text.replace("D", "0")
text = text.replace("S", "5")
text = text.replace(".I'", "/")
text = text.replace(".I", "/")
text = text.replace("I'", "/")
text = text.replace("J", "/")
return text
</code></pre>
<p>Ultimately generates:</p>
<pre><code>ConvertPPTextToReadableNumbers return text = 18/20
ConvertPPTextToReadableNumbers return text = 0/5
ConvertPPTextToReadableNumbers return text = 10/10
ConvertPPTextToReadableNumbers return text = 20/20
</code></pre> | 0 |
Ruby date format validation | <p>How I can verify that the date '2016-01-01' is in the right format (%Y-%m-%d).</p>
<p>For example I want to get <code>true</code> or <code>false</code> if the date is in the right format.</p>
<p>pseudo code:</p>
<pre><code>if ('2016-01-01' == (%Y-%m-%d))
puts date is valid
else
puts date is not valid
end
</code></pre>
<p>Please help,</p>
<p>Thanks!</p> | 0 |
Adding legends to multiple line plots with ggplot | <p>I'm trying to add a legend to a plot that I've created using ggplot. I load the data in from two csv files, each of which has two columns of 8 rows (not including the header). </p>
<p>I construct a data frame from each file which include a cumulative total, so the dataframe has three columns of data (<code>bv</code>, <code>bin_count</code> and <code>bin_cumulative</code>), 8 rows in each column and every value is an integer.</p>
<p>The two data sets are then plotted as follows. The display is fine but I can't figure out how to add a legend to the resulting plot as it seems the ggplot object itself should have a data source but I'm not sure how to build one where there are multiple columns with the same name.</p>
<pre><code>library(ggplot2)
i2d <- data.frame(bv=c(0,1,2,3,4,5,6,7), bin_count=c(0,0,0,2,1,2,2,3), bin_cumulative=cumsum(c(0,0,0,2,1,2,2,3)))
i1d <- data.frame(bv=c(0,1,2,3,4,5,6,7), bin_count=c(0,1,1,2,3,2,0,1), bin_cumulative=cumsum(c(0,1,1,2,3,2,0,1)))
c_data_plot <- ggplot() +
geom_line(data = i1d, aes(x=i1d$bv, y=i1d$bin_cumulative), size=2, color="turquoise") +
geom_point(data = i1d, aes(x=i1d$bv, y=i1d$bin_cumulative), color="royalblue1", size=3) +
geom_line(data = i2d, aes(x=i2d$bv, y=i2d$bin_cumulative), size=2, color="tan1") +
geom_point(data = i2d, aes(x=i2d$bv, y=i2d$bin_cumulative), color="royalblue3", size=3) +
scale_x_continuous(name="Brightness", breaks=seq(0,8,1)) +
scale_y_continuous(name="Count", breaks=seq(0,12,1)) +
ggtitle("Combine plot of BV cumulative counts")
c_data_plot
</code></pre>
<p>I'm fairly new to R and would much appreciate any help.</p>
<p>Per comments, I've edited the code to reproduce the dataset after it's loaded into the dataframes. </p>
<p>Regarding producing a single data frames, I'd welcome advice on how to achieve that - I'm still struggling with how data frames work.</p> | 0 |
Export GIT LOG into an Excel file | <p>I have looked into the forum, but with no luck.</p>
<p>Requirement :</p>
<p>Run GIT LOG (format) command and write the results into an Excel File . </p>
<p>I have seen examples wherein with GIT Log command, data can be written into a CSV, but formatting is double the effort.</p>
<p>Any utility or approach would be helpful.</p>
<p>Thanks
Milind</p> | 0 |
Accessibility: sr-only or aria-label | <p><a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute" rel="noreferrer">From MDN</a>:</p>
<blockquote>
<p>In the example below, a button is styled to look like a typical "close" button, with an X in the middle. Since there is nothing indicating that the purpose of the button is to close the dialog, the aria-label attribute is used to provide the label to any assistive technologies.</p>
<pre><code><button aria-label="Close" onclick="myDialog.close()">X</button>
</code></pre>
</blockquote>
<p>According to the Bootstrap Documentation:</p>
<blockquote>
<p>Hide an element to all devices except screen readers with .sr-only</p>
</blockquote>
<p>So I guess I could also write:</p>
<pre><code><button onclick="myDialog.close()"><span class="sr-only">Close</span>X</button>
</code></pre>
<p>In a Bootstrap project, how can I choose which one to prefer?</p> | 0 |
Node.js MySQL model designing | <p>I'm developing a node.js application using MySQL database but i'm stuck with making models on the node.js side of my application. I've used mongoose before to produce schemas and use models to do database functions but i couldn't find such support for MySQL. Can anyone suggest a proper way to isolate my database functions in node.js like i could do with mongoose. here's my app.js and users model i'm using right now. </p>
<p>app file: </p>
<pre><code>var express= require("express");
var bodyParser = require("body-parser");
var mysql = require("mysql");
var UserModel= require("./models/User.js")
var app=express();
var sql = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database: "dricm"
});
sql.connect(function (err) {
if(err){
console.log("error");
}else{
console.log("connected");
}
});
app.set("views", "./views");
app.use(express.static("node_modules/bootstrap/dist"));
app.use(express.static("public"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.get('/', function (req, res) {
res.render("signup.jade");
});
app.post('/signup', function (req, res) {
var obj= {
username: req.body.username,
password: req.body.password
};
UserModel.createUser(obj);
res.redirect("/");
});
app.listen(3000, function () {
console.log("server running at 3000");
});
</code></pre>
<p>User(probable model)</p>
<pre><code>var mysql= require("mysql");
var bcrypt = require("bcryptjs");
var sql = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database: "dricm"
});
sql.connect(function (err) {
if(err){
console.log("error");
}else{
console.log("connected");
}
});
var User= {
}
User.createUser = function createUser(newUser) {
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(newUser.password,salt, function (err, hash) {
newUser.password = hash;
var query = sql.query("INSERT INTO USERS set ?", newUser, function (err, res) {
console.log(query);
if(err) {
console.log("error");
}
else{
console.log(res.insertId);
}
});
});
});
}
module.exports= User;
</code></pre> | 0 |
How the new range-based for loop in C++17 helps Ranges TS? | <p>The committee changed the range-based for loop from:</p>
<ul>
<li><p>C++11:</p>
<pre><code>{
auto && __range = range_expression ;
for (auto __begin = begin_expr, __end = end_expr;
__begin != __end; ++__begin) {
range_declaration = *__begin;
loop_statement
}
}
</code></pre></li>
<li><p>to C++17 : </p>
<pre><code>{
auto && __range = range_expression ;
auto __begin = begin_expr ;
auto __end = end_expr ;
for ( ; __begin != __end; ++__begin) {
range_declaration = *__begin;
loop_statement
}
}
</code></pre></li>
</ul>
<p>And people said that this will make implementing Ranges TS easier. Can you give me some examples? </p> | 0 |
Android Studio: Buildtools 24.0.1 requires Java 1.8 or above. | <p>I'm trying to setup an Android dev environment on Mac. </p>
<p>My starting point is Java 1.7 I believe. So I installed android studio and opened the project I'd like to build. And it says:</p>
<pre><code>Error:Buildtools 24.0.1 requires Java 1.8 or above. Current JDK version is 1.7.
</code></pre>
<p>So I went and download Java 1.8 u101 and installed that. No luck. Then I removed Android Studio and re-installed it and re-installed the SDK and still no luck.</p>
<p>My Java Control Pannel says: Java 8 update 101.
Output of <code>/usr/bin/java</code>:</p>
<pre><code>java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)
</code></pre>
<p>Output of <code>/usr/bin/javac</code></p>
<pre><code>javac 1.8.0_101
</code></pre>
<p>What have I done wrong?</p> | 0 |
Could not initialize SDL(No available video device), qemu-system, Windows Subsystem for Linux | <p>I'm learning how to write a basic OS kernel with <a href="https://intermezzos.github.io" rel="nofollow noreferrer">intermezzos.github.io</a></p>
<p>I'm running in Windows Subsystem for Linux on Windows 10 v1607.</p>
<p>I'm at the point where I want to run my <code>.iso</code> with <code>qemu-systems-x86_64 -cdrom os.iso</code>.</p>
<p>Previously I was able to run the command and QEMU would run a window, which was running into another problem, posted here: <a href="https://stackoverflow.com/questions/39232676/qemu-no-bootable-device-windows-subsystem-for-linux">QEMU, No bootable device, Windows Subsystem for Linux</a></p>
<p>Now when running the command, I receive the following error: <code>Could not initialize SDL(No available video device) - exiting</code></p>
<p>When I ran into this problem before I installed <code>Xming</code>, ran it, and then QEMU successfully ran. But now, when I try to run Xming it no longer solves the problem.</p>
<p>I even tried installing <code>xorg</code> and running <code>startx</code> on WSL but that starts another issue: <code>xf86OpenConsole: Cannot open /dev/tty0 (No such file or directory)</code></p>
<p>I really don't know what I'm doing and I have so many questions.</p>
<p>I'm under the impression that for QEMU to successfully run, it needs to be able to find a video driver. Is that the purpose of X11?</p> | 0 |
Heroku - No web process running | <p>I made a twitter bot using tweepy in Python and tried deploying it using Heroku. The Bot just tweets after certain intervals. After deploying it, the Python program just doesn't run and Heroku log shows the following error : </p>
<pre><code>at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=fathomless-island-25537.herokuapp.com request_id=0aa76d12-31e6-4940-85ec-a8476af4f82f fwd="182.64.210.145" dyno= connect= service= status=503 bytes=
</code></pre>
<p>After looking through some similar problems where a django app has to be deployed, I tried:</p>
<pre><code>heroku ps:scale web=1
</code></pre>
<p>and got:</p>
<pre><code>Scaling dynos... !
! Couldn't find that formation.
</code></pre>
<p>Does it mean that the program failed to establish a web process or is there something else related to dynos ? Or if I have to include some code related to dynos in my program ? I don't know which part of this whole process has a problem. Apologies if it's too basic.</p> | 0 |
MongoDB unwind multiple arrays | <p>I have the following documents:</p>
<pre><code>{
"dates": [
1399518702000,
1399126333000,
1399209192000,
1399027545000
],
"dress_number": "4",
"name": "J. Evans",
"numbers": [
"5982",
"5983",
"5984",
"5985"
]
}
</code></pre>
<p>Is it possible unwind data from multiple arrays and get only paired elements from arrays:</p>
<pre><code>{
"dates": "1399518702000",
"numbers": "5982"
},
{
"dates": "1399126333000",
"numbers": "5983"
},
{
"dates": "1399209192000",
"numbers": "5984"
},
{
"dates": "1399027545000",
"numbers": "5985"
}
</code></pre> | 0 |
how to open gallery to select multiple image? | <p>I want to open gallery with multiple image selection functionality and i am using following code.</p>
<pre><code> Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);
</code></pre>
<p>It opens gallery app but doesn't let me choose multiple images.</p> | 0 |
how to change the black color to Red with opencv python | <p>how can you make it in python? I faced a problem with this line</p>
<pre><code>img_rgb.Set(mask,cv2.Scalar(0,0,255))
</code></pre>
<p>and here is the code :</p>
<pre><code>import numpy as np
import imutils
import cv2
img_rgb = cv2.imread('figi.jpg')
Conv_hsv_Gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(Conv_hsv_Gray, 0, 255,cv2.THRESH_BINARY_INV |cv2.THRESH_OTSU)
img_rgb.Set(mask,cv2.Scalar(0,0,255))
cv2.imshow("imgOriginal", img_rgb) # show windows
cv2.imshow("output", res) # show windows
cv2.imshow("mask", mask) # show windows
cv2.waitKey(0)
</code></pre> | 0 |
Class App\Http\Controllers\homeController does not exist | <p>i'm using laravel 5 , in rutes.php i have this code :</p>
<pre><code>Route::get('about',"homeController@about");
</code></pre>
<p>and in App\Http\Controllers\ i have file homeController.php that contains :</p>
<pre><code><?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller as BaseController;
class homeController extends BaseController{
public function about(){
return view::make('about');
}
}
</code></pre>
<p>but it throws this error : Class App\Http\Controllers\homeController does not exist .
how can i fix it ? </p>
<p>here is structure of the project and controllers :
<a href="https://i.stack.imgur.com/qVQ4M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qVQ4M.png" alt="enter image description here"></a></p> | 0 |
Adding wsdl web reference in asp .Net Core project | <p>I've got web service <a href="http://www.mcommunicator.ru/m2m/m2m_api.asmx?WSDL" rel="noreferrer">http://www.mcommunicator.ru/m2m/m2m_api.asmx?WSDL</a>
And I've got a problem with connecting to it from Visual Studio 2015
in my Web API project</p>
<p>There is no "Add web reference" anymore
I've tried to add is with:
References-> Add connected Service -> WCF Service - Preview
It finds 1 web service by my address, but I get an error when click finish.
I guess it's not a WCF service, that's why I get an error.
But I don't see any other ways to add it. Please, help me.</p> | 0 |
How do I make my android app appear in Ultra Power Saving Mode | <p>Some samsung devices have an Ultra Power Saving Mode which turns off wifi, turns the screen grayscale and limits usage to a few basic apps.</p>
<p>It however does allow you to add some apps which can then be used. These apps include Facebook and WhatsApp. How do I make my app appear in this list? What changes do I have to make to the app so that it may appear on this list? Or is this list based on a white list maintained by Samsung?</p> | 0 |
Remove whitespaces in string with Scala | <p>I want to remove the whitespaces in a string. </p>
<pre><code>Input: "le ngoc ky quang"
Output: "lengockyquang"
</code></pre>
<p>I tried the <code>replace</code> and <code>replaceAll</code> methods but that did't work.</p> | 0 |
Does an Application Load Balancer support WebSockets? | <p>I have an Elastic Beanstalk application which was initially configured to use a Classic Load Balancer. I found that this caused errors when connecting via WebSocket. Because of this, I configured the application to use an Application Load Balancer instead, because I was told that ALBs support WebSockets. However, it seems that they do not: I get exactly the same error when attempting to connect to my ALB via WebSocket.</p>
<p>Do ALBs actually support WebSocket? The AWS documentation is contradictory on this. <a href="http://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html" rel="noreferrer">This page</a> says it only supports HTTP and HTTPS. There are no guides to setting up an ALB to support WebSocket.</p> | 0 |
ReactJS - Call One Component Method From Another Component | <p>I have two components. I want to call a method of the first component from the second component. How can I do it?</p>
<p>Here is my code.</p>
<p><strong>First Component</strong></p>
<pre><code>class Header extends React.Component{
constructor(){
super();
}
checkClick(e, notyId){
alert(notyId);
}
}
export default Header;
</code></pre>
<p><strong>Second Component</strong></p>
<pre><code>class PopupOver extends React.Component{
constructor(){
super();
// here i need to call Header class function check click....
// How to call Header.checkClick() from this class
}
render(){
return (
<div className="displayinline col-md-12 ">
Hello
</div>
);
}
}
export default PopupOver;
</code></pre> | 0 |
Is there an Autoincrement in BigQuery? | <p>Is there something like an AUTO_INCREMENT, SERIAL, IDENTITY or sequence in BigQuery ?</p>
<p>I'm aware of ROW_NUMBER <a href="https://cloud.google.com/bigquery/query-reference#row-number" rel="noreferrer">https://cloud.google.com/bigquery/query-reference#row-number</a><br>
But I want to persist a generated unique ID for every row in my table.</p> | 0 |
C# Generic Interface and Factory Pattern | <p>I am trying to create a Generic interface where the parameter type of one of the methods is defined by the generic</p>
<p><strong>EDIT</strong></p>
<p>I've changed the question slightly after realising I have probably confused matters by specifying a type parameter in the Factory creation method. What I have is two types of API calls that I need to make to a 3rd party API. The first retrieves a record from the API using an Id that is an int. The second also retrieves a record from the API but the Id is a string (guid). I have a class for each record type (ClientEntity and InvoiceEntity) that both implement a Generic Interface where I pass in the Id type</p>
<p>This is the Interface in which I declare a Method with an id Parameter</p>
<pre><code>public interface IGeneric<TId>
{
void ProcessEntity(TId id);
}
</code></pre>
<p>I implement the interface in a couple of classes, one sets the id to be an int, the other a string.</p>
<pre><code>public class ClientEntity: IGeneric<int> // Record with Id that is an int
{
public void ProcessEntity(int id)
{
Console.WriteLine(id);
// call 3rd party API with int Id
}
}
public class InvoiceEntity: IGeneric<string> // Record with Id that is a string (guid)
{
public void ProcessEntity(string id)
{
Console.WriteLine(id);
// call 3rd party API with string Id
}
}
</code></pre>
<p>What I would like to know is how do I use this within a factory pattern?</p>
<pre><code>public static class GenericFactory
{
public static IGeneric<WhatGoesHere> CreateGeneric(string recordType)
{
if (recordType == "Client")
{
return new ClientEntity();
}
if (type == "Invoice")
{
return new InvoiceEntity();
}
return null;
}
}
</code></pre>
<p>The objective is to use the factory to instantiate the correct class so that I can call the ProcessEntity method</p>
<p><strong>EDIT</strong></p>
<p>I don't want to have to pass in the Generic type to the factory method because the class that is created by the factory should handle that. When I create the object, I don't know what Id type is required, I want the factory to handle that</p>
<p>e.g. </p>
<pre><code> var myGeneric = GenericFactory.CreateGeneric("Client");
myGeneric.ProcessEntity("guid")
</code></pre>
<p>or</p>
<pre><code> var myGeneric = GenericFactory.CreateGeneric("Invoice");
myGeneric.ProcessEntity(1234)
</code></pre>
<p>I hope that makes sense</p> | 0 |
python decorate function call | <p>I recently learned about decorators and wondered if it's possible to use them not in a function definition but in a function call, as some kind of general wrapper.</p>
<p>The reason for that is, that I want to call functions from a module through a user-defined interface that does repeatable things to a function and I don't want to implement a wrapper for every single function.</p>
<p>In principle I would like to have something like</p>
<pre><code>def a(num):
return num
@double
a(2)
</code></pre>
<p>returning 4 without the need of having access to the implementation of <code>a</code>.
Or would in this case a global wrapper like</p>
<pre><code>def mutiply(factor,function,*args,**kwargs):
return factor*function(*args,*kwargs)
</code></pre>
<p>be the better choice?</p> | 0 |
How to add SHA-1 to android application | <p>I'm trying to create a dynamic link in Firebase, when I'm selecting the android app, it shows an error saying "Add SHA-1 to this android app", I've already added a credential, but I'm not sure how exactly do I "add SHA-1 to the app"</p>
<p>How is this done?</p> | 0 |
document.getElementById().value not working | <p>I would like to auto calculate a price + commission (12%) and automatically input the result. For example: 100$ + 12% commission = 112$. Problem is here my result is 10012.</p>
<p>Where did I write wrong my code:</p>
<pre><code><input type="value" class="form-control" id="input">
<input type="value" id="output" onkeyup="calc();"/>
<input id="finalprice" onkeyup="calc();"/>
<script>
function calc() {
var a = document.getElementById("input").value;
var b = (12/100) ;
var c = b * 100;
var e = a + c;
var f = a + e;
document.getElementById("output").value = c;
document.getElementById("finalprice").value = f;
}
</script>
</code></pre> | 0 |
vcruntime140.dll vs vcruntime140d.dll | <p>What are the difference between these two dlls <strong>vcruntime140.dll</strong> and <strong>vcruntime140d.dll</strong>? Why do we need them? Are they both part of the Microsoft Visual C++ 2015 Redistributable?</p>
<p>Have googled for quite some time, but couldn't find anything that I can understand.</p>
<p>Some background: I have a C# program that works on a Windows 10 machine but doesn't work on Windows Vista, and looks like it is because there is no vcruntime140d.dll on my Windows Vista machine.</p> | 0 |
Vertical alignment of canvas text | <p>I am working on a canvas based app, and I have some problems with the vertical alignment of my texts. I am using floating point coordinates, which I think are the cause of the problem. I am not sure though, and am nonetheless looking for a solution. Anyway, the code I use for displaying the letter 'O' in a square, for instance, is:</p>
<pre><code>context.fillRect(0, 0, 21.864951768488744, 21.864951768488744);
context.textBaseline = 'middle';
context.textAlign = alignLeft ? 'left' : 'center';
context.fillText('O', 10.932475884244372, 10.932475884244372);
</code></pre>
<p>The result on the canvas is that the 'O' is centered horizontally, but placed about 1 - 2 pixels above the center.</p>
<p>Does anyone have any thoughts on this?</p> | 0 |
How can I use urllib.request.urlretrieve with python 2.7 | <p>I am trying to get images dowloaded from image-net.org so that I can create a haar cascade classifier. I am following this tutorial <a href="https://www.youtube.com/watch?v=z_6fPS5tDNU&list=PLQVvvaa0QuDdttJXlLtAJxJetJcqmqlQq&index=18" rel="noreferrer">https://www.youtube.com/watch?v=z_6fPS5tDNU&list=PLQVvvaa0QuDdttJXlLtAJxJetJcqmqlQq&index=18</a> but I am using python 2.7 instead of python 3. So in the tutorial he has the line:</p>
<pre><code>urllib.request.urlretrieve(img, pathToImage)
</code></pre>
<p>Instead of <code>import urllib.request</code> I did this <code>import urllib2</code> So I tried this but it isn't vaild</p>
<pre><code>urllib2.urlretrieve(i, "Negatives/"+str(num)+".jpg")
</code></pre>
<p>Thank you in Advance!</p> | 0 |
Curl PUT Request With JWT Authorization Header | <p>I am still getting a hang of using curl for testing API request from the terminal. I have a particular issue with formatting because the API request I am attempting requires a JWT Token to be passed with every call.
The request I am attempting to pass is PUT request and my question is where to place the header for the JWT token authorization.
I have tried the following format and I get a error Could not resolve host: —H curl: (6) Could not resolve host: Authorization:</p>
<pre><code>curl -X PUT -H "Authorization: JWT <token here>" -d "field=value" "https://url/update_record/<id>/"
</code></pre>
<p>Any ideas?</p>
<p>The call being accessed has the following permissions</p>
<pre><code>class Item_Update_APIView(UpdateAPIView):
authentication_classes = [SessionAuthentication, BasicAuthentication, JSONWebTokenAuthentication]
permission_classes = [IsAuthenticated]
serializer_class = ItemSerializer
def get_queryset(self):
id = self.kwargs['id']
return Item.objects.filter(id__exact=id)
</code></pre>
<p>serializer:</p>
<pre><code>class ItemSerializer(ModelSerializer):
class Meta:
model = Item
fields = [
'id',
'booleanField',
]
</code></pre> | 0 |
Angular 2 @ViewChild returns undefined | <p>I've looked at several related posts and documentation, but still can't seem to get expected behavior from @ViewChild. </p>
<p>Ultimately, I'm trying to set the scroll position of a div. This element isn't a component, but a normal div in my HTML. </p>
<p>To accomplish this, I'm trying to use @ViewChild to get the DOM element I need, and set its scroll value. (As an aside, if you know a better way to accomplish this without @ViewChild (or jQuery), answers will be very much appreciated!)</p>
<p>At the moment, @ViewChild only returns undefined. Going through some dummy checks:
- I am accessing my element in AfterViewInit
- I do not have any other directives like *ngIf or *ngFor on this element.</p>
<p>Here's the controller:</p>
<pre><code>import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'portfolio-page',
templateUrl: './portfolio-page.component.html',
styleUrls: ['./portfolio-page.component.scss']
})
export class PortfolioPageComponent implements AfterViewInit{
@ViewChild('gallery-container') galleryContainer: ElementRef;
ngAfterViewInit(){
console.log('My element: ' + this.galleryContainer);
}
}
</code></pre>
<p>And the template:</p>
<pre><code><div id='gallery-container' class='gallery-image-container'>
<div class='gallery-padding'></div>
<img class='gallery-image' src='{{ coverPhotoVm }}' />
<img class='gallery-image' src='{{ imagepath }}' *ngFor='let imagepath of imagesVm' />
</div>
</code></pre>
<p>My output is simple: My element: undefined.</p>
<p>As you can see, I'm currently trying to access the element by ID, but have tried class name as well. Could anyone provide more detail about what the ViewChild selector query is expecting?</p>
<p>I've also seen examples where a hash '#' is used as the selector idendifier that @ViewChild uses -- -- but this causes a template parse error for me with #gallery-container.</p>
<p>I can't think of anything else that could possible be wrong here. All help is appreciated, thanks!</p>
<p>Full code available here: <a href="https://github.com/aconfee/KimbyArting/tree/master/client/KimbyArting/components/portfolio-page" rel="noreferrer">https://github.com/aconfee/KimbyArting/tree/master/client/KimbyArting/components/portfolio-page</a></p> | 0 |
Handling AutoLayout constraint animation differences in iOS 10? | <p>I've noticed that in iOS 10 Beta 5 (about to try Beta 6), AutoLayout constraint animation behaves a bit differently.</p>
<p>For example, this approach does not work the same as it did in previous iOS releases:</p>
<pre><code>[view addConstraints:@[constraints...]];
[view setNeedsUpdateConstraints];
[view layoutIfNeeded];
[UIView animateWithDuration:...
{
/* adjust constraint here... */
[view layoutIfNeeded]; // Only the adjusted constraints since previous layoutIfNeeded() call should animate change with duration.
} completion:{ ... }];
</code></pre>
<p>... In my testing, the constraints initially added with <code>addConstraints()</code> will <strong>also</strong> animate in iOS 10 with the UIView <code>animateWithDuration()</code> block... which is causing some funky/undesirable behavior so far.</p>
<p>For example, setting the left/right constraints in the array (but the vertical constraints in the block) <strong>causes the entire view to animate onto the screen diagonally</strong> with this approach... which is totally incorrect.</p>
<p>Does anyone know how to do this correctly for both iOS 9 (and below), as well as 10?</p> | 0 |
Calculate age from BirthDate | <p>I have DatePicker Dialog, When I select date at that time I want to calculate age it's working but when I select date of current year at that time it showing the -1 age instead of 0 then how can solve this? Please help me to solve it.
My code is below:</p>
<pre><code>public int getAge(int year, int month, int day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, noofyears;
y = cal.get(Calendar.YEAR);// current year ,
m = cal.get(Calendar.MONTH);// current month
d = cal.get(Calendar.DAY_OF_MONTH);// current day
cal.set(year, month, day);// here ur date
noofyears = (int) (y - cal.get(Calendar.YEAR));
LOGD("Age......", String.valueOf(noofyears));
if ((m < cal.get(Calendar.MONTH)) || ((m == cal.get(Calendar.MONTH)) && (d < cal.get(Calendar.DAY_OF_MONTH)))) {
--noofyears;
}
LOGD("Age......", String.valueOf(noofyears));
if (noofyears != 0) {
ageCount = noofyears;
} else {
ageCount = 0;
}
if (noofyears < 0)
throw new IllegalArgumentException("age < 0");
return noofyears;
}
</code></pre> | 0 |
Efficiently finding the closest coordinate pair from a set in Python | <p><strong>The Problem</strong></p>
<p>Imagine I am stood in an airport. Given a geographic coordinate pair, how can one efficiently determine which airport I am stood in?</p>
<p><strong>Inputs</strong></p>
<ul>
<li>A coordinate pair <code>(x,y)</code> representing the location I am stood at.</li>
<li>A set of coordinate pairs <code>[(a1,b1), (a2,b2)...]</code> where each coordinate pair represents one airport.</li>
</ul>
<p><strong>Desired Output</strong></p>
<p>A coordinate pair <code>(a,b)</code> from the set of airport coordinate pairs representing the closest airport to the point <code>(x,y)</code>.</p>
<p><strong>Inefficient Solution</strong></p>
<p>Here is my inefficient attempt at solving this problem. It is clearly linear in the length of the set of airports.</p>
<pre><code>shortest_distance = None
shortest_distance_coordinates = None
point = (50.776435, -0.146834)
for airport in airports:
distance = compute_distance(point, airport)
if distance < shortest_distance or shortest_distance is None:
shortest_distance = distance
shortest_distance_coordinates = airport
</code></pre>
<p><strong>The Question</strong></p>
<p>How can this solution be improved? This might involve some way of pre-filtering the list of airports based on the coordinates of the location we are currently stood at, or sorting them in a certain order beforehand.</p> | 0 |
date_format is not a recognized built-in-function name in sql | <p>I want my date is to be displayed as follows:</p>
<pre><code>Monday , 1 April 2013
</code></pre>
<p>But in SQL-Server shows...</p>
<blockquote>
<p>Date_format function is not a recognized built in function</p>
</blockquote> | 0 |
Spring Batch - Pass all data between reader processor and writer | <p>I'm curious how one would manage to pass all available data from the reader down through the pipeline. </p>
<p>e.g. I want the reader to pull all the data in and pass the entire result set down to the processor and the writer. The result set is small, I'm not worried about resources. I thought I had implemented this properly by having all of the components (reader, writer, processor) receive and return a collection of the processed item.</p>
<p>While the results of the process appears to be fine, what I am seeing is that the job is reading everything in, passing it down through the pipeline and then it returns to the reader, reads everything and passes it down and so on.</p>
<p>I've considered creating an extra step to read all the data in and pass it down to a subsequent step, but I'm curious if I can do this and how</p>
<p>The job looks like</p>
<pre><code>@Bean
Job job() throws Exception {
return jobs.get("job").start(step1()).build()
}
@Bean
protected Step step1() throws Exception {
return steps.get("step1").chunk(10)
.reader(reader()
.processor(processor()
.writer(writer()).build()
</code></pre>
<p>//....</p>
<p>The reader, processor and writer accept and return a List, e.g.</p>
<pre><code>class DomainItemProcessor implements ItemProcessor<List<Domain>, List<Domain>>{
</code></pre> | 0 |
How do I get the length of a String in Swift3 on macOS | <p>How do I get the length of a <code>String</code> in 'Swift3' on macOS?</p>
<p>This used to work in Swift2:</p>
<pre><code>if purchaseDateString.length == 0 {
purchaseDateString = "n/a"
}
</code></pre>
<p>What is Swift3 equivalent for finding String's length.</p>
<p>UPDATE</p>
<p>There are answers to this question as Martin points out. The referred question has 30 answers. However, as far as I can tell, none of them relate specifically to Swift3. I could be wrong..</p> | 0 |
Remove accents from a dataframe column in R | <p>I got a data.table base.
I got a term column in this data.table</p>
<pre><code>class(base$term)
[1] character
length(base$term)
[1] 27486
</code></pre>
<p>I'm able to remove accents from a string.
I'm able to remove accents from a vector of string.</p>
<pre><code>iconv("Millésime",to="ASCII//TRANSLIT")
[1] "Millesime"
iconv(c("Millésime","boulangère"),to="ASCII//TRANSLIT")
[1] "Millesime" "boulangere"
</code></pre>
<p>But for some reason, it does not work when I apply the very same function on my term column</p>
<pre><code>base$terme[2]
[1] "Millésime"
iconv(base$terme[2],to="ASCII//TRANSLIT")
[1] "MillACsime"
</code></pre>
<p>Does anybody know what is going on here?</p> | 0 |
how to navigate from one component to another component without carrying any parameters(id) in angularjs2? | <p>In my appcomponent it consists of two button login and signup which directs to corresponding components.
In my signupcomponent when the user enters all the text field and clicks the submit button all the text field should disappear and content in my confcomponent show be displayed.(I want to navigate from signupcomponent to confcomponent)</p>
<p>app.component.ts</p>
<pre><code>import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
@Component({
selector: 'my-app',
template: `
<div class="ui buttons">
<button class="ui button"routerLink="/login"routerLinkActive="active">Login</button>
<div class="or"></div>
<button routerLink="/signUp"routerLinkActive="active">SignUp</button>
</div>
<div class="ui form margin-top">
<router-outlet></router-outlet>
</div>
`,
directives: [ROUTER_DIRECTIVES]
})
export class AppComponent { }
</code></pre>
<p>app.routes.ts</p>
<pre><code>import { provideRouter, RouterConfig } from '@angular/router';
import { signUpComponent } from './signUp.component';
import { loginComponent } from './login.component';
import { confComponent } from './conf.component';
const routes: RouterConfig = [
{ path: 'signUp', component: signUpComponent },
{ path: 'login', component: loginComponent },
{ path: 'conf', component: confComponent }
];
export const appRouterProviders = [
provideRouter(routes)
];
</code></pre>
<p>signup.component.ts</p>
<pre><code>import { Component } from '@angular/core';
@Component({
template: `
<h5 class="ui header">Admin detail</h5>
<form>
<div class="field">
<input type="text" placeholder="Company Name">
</div>
<div class="field">
<input type="text" placeholder="Admin Name">
</div>
<div class="field">
<input type="email" placeholder="Admin's Email-id">
</div>
<div class="field">
<input type="password" placeholder="Admin's Password">
</div>
<div class="field">
<input type="password" placeholder="Re-enter Password">
</div>
<div class="ui warning message">
<div class="header">Authentication failed!</div>
<p>Please check your Email-id and Password</p>
</div>
<div class="ui animated button" tabindex="0">
<div class="visible content" routerLink="/conf" routerLinkActive="active">
Submit and Proceed
</div>
<div class="hidden content">
<i class="fa fa-arrow-right" aria-hidden="true"></i>
</div>
</div>
</form>
`
})
export class signUpComponent { }
</code></pre> | 0 |
How to install PHP 7 extension "memcache" on Windows | <p>I'm having huge problems installing memcached extension for php.</p>
<p>Currently using:</p>
<p>OS: Windows 10 x64<br>
PHP: 7.0.1 via <strong>XAMPP</strong><br>
Apache: 2.4.18 (Win32)<br></p>
<p>I have successfully installed memcached in <code>C:/memcached</code> the service is running.</p>
<p>But the problem starts when trying to add the memcache php extension. I've tried numerous versions of <code>php_memcache.dll</code> and non seem to be working. <br><em>I did include the extension in php.ini</em> <code>extension=php_memcache.dll</code></p>
<p>When i run <code>php -m</code> memcache is not listed and at the top i recieve the error:<br></p>
<blockquote>
<p>PHP Startup: Unable to load dynamic library 'C:\xampp\php\ext\php_memcache.dll' <br>- The specified module could not be found.</p>
</blockquote>
<p>And when I try running a test.php for memcache initialization i recive the <code>Class not found exception</code></p>
<p>This is a huge problem, because I need it for running selenium tests.</p> | 0 |
Firebase - iOS Swift: FIRAuth.auth().signOut() not signing out current user | <p>I'm building an app using Firebase with an initial <code>SignInViewController</code> that loads a sign in page for users to authenticate with email which triggers the following methods:</p>
<pre><code>@IBAction func didTapSignIn(sender: AnyObject) {
let email = emailField.text
let password = passwordField.text
FIRAuth.auth()?.signInWithEmail(email!, password: password!) { (user, error) in
if let error = error {
print(error.localizedDescription)
return
}
self.signedIn(user!)
}
}
func signedIn(user: FIRUser?) {
AppState.sharedInstance.displayName = user?.displayName ?? user?.email
AppState.sharedInstance.signedIn = true
NSNotificationCenter.defaultCenter().postNotificationName(Constants.NotificationKeys.SignedIn, object: nil, userInfo: nil)
performSegueWithIdentifier(Constants.Segues.SignInToHome, sender: nil)
}
</code></pre>
<p>The <code>SignInViewController</code> also checks if there is a cached current user when the app launches and, if so, signs that user in:</p>
<pre><code>override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
//Synchronously gets the cached current user, or null if there is none.
if let user = FirebaseConfigManager.sharedInstance.currentUser {
self.signedIn(user)
}
}
</code></pre>
<p>Once the user is signed in, the app segues to a <code>HomeScreenViewController</code> which displays a "Sign Out" button at the top left of the navigation bar. When a user taps the "Sign Out" button, that user is supposed to get signed out and the app should segue back to the <code>SignInViewController</code> with the following method:</p>
<pre><code>@IBAction func didTapSignOut(sender: UIBarButtonItem) {
print("sign out button tapped")
let firebaseAuth = FIRAuth.auth()
do {
try firebaseAuth?.signOut()
AppState.sharedInstance.signedIn = false
dismissViewControllerAnimated(true, completion: nil)
} catch let signOutError as NSError {
print ("Error signing out: \(signOutError)")
} catch {
print("Unknown error.")
}
}
</code></pre>
<p>When I tap the "Sign out" button, the <code>didTapSignOut</code> method gets called and gets executed.
However, after the <code>try firebaseAuth?.signOut()</code> line of code gets executed, the current user should be <code>nil</code>. But when I print out the current user in the Xcode console, the current user is still logged in:</p>
<pre><code>po FIRAuth.auth()?.currentUser
▿ Optional<FIRUser>
- Some : <FIRUser: 0x7fde43540f50>
</code></pre>
<p>Since the current user doesn't get signed out after <code>firebaseAuth?.signOut()</code> gets called, once the app segues back to the <code>SignInViewController</code> the app still thinks there is a cached current user so that user gets signed in again.</p>
<p>Could this be a Keychain issue?</p>
<p>Does it have to do with <code>NSNotificationCenter.defaultCenter().postNotificationName</code> being called?</p>
<p>My code comes directly from the Google Firebase Swift Codelab so I'm not sure why it's not working:
<a href="https://codelabs.developers.google.com/codelabs/firebase-ios-swift/#4" rel="noreferrer">https://codelabs.developers.google.com/codelabs/firebase-ios-swift/#4</a></p> | 0 |
How to make svg animation with Animated in react-native | <p>ReactNative:</p>
<pre><code><ScrollView style={styles.container}>
<Svg
height="100"
width="100">
<Circle
cx="50"
cy="50"
r="50"
stroke="blue"
strokeWidth="2.5"
fill="green"/>
</Svg>
</ScrollView>
</code></pre>
<p>I want to make Circle scale with Animated.Value. I have tried this :</p>
<pre><code> let AnimatedScrollView = Animated.createAnimatedComponent(ScrollView);
let AnimatedCircle = Animated.createAnimatedComponent(Circle);
<ScrollView style={styles.container}>
<Svg
height="100"
width="100">
<AnimatedCircle
cx="50"
cy="50"
r={this.state.animator}
stroke="blue"
strokeWidth="2.5"
fill="green"/>
</Svg>
</ScrollView>
</code></pre>
<p>Then flash back with no error.</p>
<p>How can I do?</p>
<hr>
<p><strong>update 2016.8.24</strong></p>
<p>I found a new way instead of requestAnimationFrame :</p>
<p>constructor: </p>
<pre><code>this.state = {
animator: new Animated.Value(0),
radius: 1,
};
this.state.animator.addListener((p) => {
this.setState({
radius: p.value,
});
});
</code></pre>
<p>render: </p>
<pre><code><Circle
cx="50"
cy="50"
r={this.state.radius}
stroke="blue"
strokeWidth="2.5"
fill="green"/>
</code></pre>
<p>But here <a href="http://facebook.github.io/react-native/docs/animated.html" rel="noreferrer">the guides</a> gives advice using it sparingly since it might have performance implications in the future.</p>
<p>so what's the best way ?</p> | 0 |
Javascript !undefined gives true? | <p>When I try to alert a negation of variable having <code>undefined</code> value , I get the output as true?</p>
<pre><code>alert(undefined);
alert(!undefined);
</code></pre>
<p>The first alert gives <code>undefined</code> and second alert gives <code>true</code>.
Is this the expected behavior. If so then why ?Am I missing some concept/theory about <code>undefined</code> in Javascript?</p> | 0 |
Mocking method calls using power mockito - org.powermock.api.mockito.ClassNotPreparedException | <p>I have an image loader class and i need to test some static methods in it. Since Mockito does not support static methods i switched to Power Mockito. But the static method i am testing has a method call </p>
<pre><code> Base64.encodeToString(byteArray, Base64.DEFAULT);
</code></pre>
<p>To mock this i am using <strong>mockStatic</strong> method as below with @PrepareForTest annotation.</p>
<pre><code> PowerMockito.mockStatic(Base64.class);
</code></pre>
<p>But Android studio is returning me still returning me an error as below.</p>
<blockquote>
<p>org.powermock.api.mockito.ClassNotPreparedException: The class
android.util.Base64 not prepared for test. To prepare this class, add
class to the '@PrepareForTest' annotation.</p>
</blockquote>
<p>Below is my complete code.</p>
<p>Code to be tested:</p>
<pre><code>import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.widget.ImageView;
public static String convertBitmapToBase64(Bitmap imageBitmap, boolean withCompression) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 120, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
</code></pre>
<p>Test class code</p>
<pre><code>import android.graphics.Bitmap;
import android.util.Base64;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.testng.annotations.Test;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Base64.class})
public class ImageLoaderTest {
@Test
public void testConvertBitmap(){
byte[] array = new byte[20];
PowerMockito.mockStatic(Base64.class);
PowerMockito.when(Base64.encodeToString(array, Base64.DEFAULT)).thenReturn("asdfghjkl");
Bitmap mockedBitmap= PowerMockito.mock(Bitmap.class);
String output = ImageLoaderUtils.convertBitmapToBase64(mockedBitmap);
assert (!output.isEmpty());
}
</code></pre>
<p>}</p>
<p>Gradle dependencies</p>
<pre><code>testCompile 'junit:junit:4.12'
testCompile 'org.powermock:powermock:1.6.5'
testCompile 'org.powermock:powermock-module-junit4:1.6.5'
testCompile 'org.powermock:powermock-api-mockito:1.6.5'
</code></pre> | 0 |
Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response | <p>I am trying to make a DELETE ajax request but I can't seem to make it work. When I make it using POSTMAN it works. Here's my code:</p>
<p>This is my request, made with jQuery's .ajax() method:</p>
<pre><code>$.ajax({
url: imageUrl,
type: 'DELETE',
crossDomain: true
});
</code></pre>
<p>On the server, a different app built with node.js + express, I have:</p>
<pre><code>app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
</code></pre>
<hr>
<p>And finally, these are my Request, Request Headers and Response Headers:</p>
<p><strong>Request</strong></p>
<pre><code>Request URL:http://original/request/url
Request Method:OPTIONS
Status Code:200 OK
Remote Address:75.126.137.93:80
</code></pre>
<p><strong>Request Headers</strong></p>
<pre><code>Accept:*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4,es;q=0.2,gl;q=0.2
Access-Control-Request-Headers:
Access-Control-Request-Method:DELETE
Connection:keep-alive
Host:fs.bvodola.webfactional.com
Origin:http://localhost:3000
Referer:http://localhost:3000/landing/admin/add-page
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
</code></pre>
<p><strong>Response Headers</strong></p>
<pre><code>Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Origin:*
Allow:GET,HEAD,DELETE
Connection:keep-alive
Content-Length:15
Content-Type:text/html; charset=utf-8
Date:Sat, 03 Sep 2016 23:34:17 GMT
ETag:W/"f-W+bYAIA7Bs2GwQecFLp1SA"
Server:nginx
X-Powered-By:Express
</code></pre>
<p>And in the <strong>Console</strong> i get the following:</p>
<p><em>XMLHttpRequest cannot load <a href="http://original/request/url" rel="nofollow noreferrer">http://original/request/url</a>. Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response.</em></p>
<p><strong>How can I solve this?</strong>
On some StackOverflow questions I read that Access-Control-Allow-Headers must the same as Access-Control-Request-Headers. But when I try to set it on the jQuery request, I get the following on the console:</p>
<p><em>Refused to set unsafe header "Access-Control-Request-Headers"</em></p>
<p>Any ideas of what might be wrong? Thanks!</p>
<hr>
<p>I have looked at the following StackOverflow questions but couldn't find the answer:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/28990565/delete-is-not-allowed-by-access-control-allow-methods#">DELETE is not allowed by Access-Control-Allow-Methods</a></li>
<li><a href="https://stackoverflow.com/questions/36374247/always-got-method-delete-is-not-allowed-by-access-control-allow-methods-in-prefl">Always got Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response</a></li>
<li><a href="https://stackoverflow.com/questions/25630585/access-control-allow-origin-in-preflight-response-doesnt-enable-cross-domain-ac">Access-Control-Allow-Origin in preflight response doesn't enable cross-domain access</a></li>
<li><a href="https://stackoverflow.com/questions/25727306/request-header-field-access-control-allow-headers-is-not-allowed-by-access-contr">Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers</a></li>
</ul> | 0 |
how to screen capture in wpf? | <p>I want to simple screen short on click.</p>
<p>I create a simple project from c# windows form.</p>
<p>But I can not on wpf.</p>
<p>Here is windows form code:</p>
<pre><code>using System.Drawing;
using System.Windows.Forms;
private void short_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
System.Windows.Forms.SendKeys.Send("{PRTSC}");
Image img = Clipboard.GetImage();
pictureBox1.Image = img;
img.Save("D:\\myimg.jpg"); //Its save only one picture
}
</code></pre>
<p>But it save only one picture .</p>
<p><strong>Question for wpf:</strong></p>
<p><strong>1:</strong> How can I capture screen on click?</p>
<p><strong>2:</strong> How can I save multiple picture at a time?</p>
<p><strong>Note:</strong></p>
<p>Just simple</p>
<p>Please help me anybody</p>
<p>Please</p> | 0 |
Have withLatestFrom wait until all sources have produced one value | <p>I'm making use of the <code>withLatestFrom</code> operator in RxJS in the normal way:</p>
<pre><code>var combined = source1.withLatestFrom(source2, source3);
</code></pre>
<p>...to actively collect the most recent emission from <code>source2</code> and <code>source3</code> and to emit all three value only when <code>source1</code> emits.</p>
<p>But I cannot guarantee that <code>source2</code> or <code>source3</code> will have produced values <em>before</em> <code>source1</code> produces a value. Instead I need to wait until all three sources produce at least one value each before letting <code>withLatestFrom</code> do its thing.</p>
<p>The contract needs to be: if <code>source1</code> emits then <code>combined</code> will <strong>always</strong> eventually emit when the other sources finally produce. If <code>source1</code> emits multiple times while waiting for the other sources we can use the latest value and discard the previous values. <strong>Edit:</strong> as a marble diagram:</p>
<pre><code>--1------------2---- (source)
----a-----b--------- (other1)
------x-----y------- (other2)
------1ax------2by--
--1------------2---- (source)
------a---b--------- (other1)
--x---------y------- (other2)
------1ax------2by--
------1--------2---- (source)
----a-----b--------- (other1)
--x---------y------- (other2)
------1ax------2by--
</code></pre>
<p>I can make a custom operator for this, but I want to make sure I'm not missing an obvious way to do this using the vanilla operators. It feels almost like I want <code>combineLatest</code> for the initial emit and then to <em>switch</em> to <code>withLatestFrom</code> from then on but I haven't been able to figure out how to do that.</p>
<p><strong>Edit:</strong> Full code example from final solution:</p>
<pre><code>var Dispatcher = new Rx.Subject();
var source1 = Dispatcher.filter(x => x === 'foo');
var source2 = Dispatcher.filter(x => x === 'bar');
var source3 = Dispatcher.filter(x => x === 'baz');
var combined = source1.publish(function(s1) {
return source2.publish(function(s2) {
return source3.publish(function(s3) {
var cL = s1.combineLatest(s2, s3).take(1).do(() => console.log('cL'));
var wLF = s1.skip(1).withLatestFrom(s2, s3).do(() => console.log('wLF'));
return Rx.Observable.merge(cL, wLF);
});
});
});
var sub1 = combined.subscribe(x => console.log('x', x));
// These can arrive in any order
// and we can get multiple values from any one.
Dispatcher.onNext('foo');
Dispatcher.onNext('bar');
Dispatcher.onNext('foo');
Dispatcher.onNext('baz');
// combineLatest triggers once we have all values.
// cL
// x ["foo", "bar", "baz"]
// withLatestFrom takes over from there.
Dispatcher.onNext('foo');
Dispatcher.onNext('bar');
Dispatcher.onNext('foo');
// wLF
// x ["foo", "bar", "baz"]
// wLF
// x ["foo", "bar", "baz"]
</code></pre> | 0 |
Replacement of Elvis Operator of Angular2 in Typescript | <p>Is there any operator in the typescript which is used similer to <code>Elvis Operator</code> of angular2, i mean to say
let supppose i have to get key from object like this:</p>
<pre><code>this.myForm.name.first_name
</code></pre>
<p>and in case first_name does't exist so it will throw error <code>first_name of undefined</code>,</p>
<p>yes i can handel this error using <code>Ternary operator</code> of typescript like this</p>
<pre><code>this.myForm.name ? this.myForm.name.first_name : ''
</code></pre>
<p>but sometimes keys are getting too long,</p>
<p>so is there any operator like <code>Elvis Operator</code> of angular2 in the typescript so that i can use like this</p>
<pre><code>this.myForm?.name?.first_name
</code></pre> | 0 |
How does Python return multiple values from a function? | <p>I have written the following code:</p>
<pre><code>class FigureOut:
def setName(self, name):
fullname = name.split()
self.first_name = fullname[0]
self.last_name = fullname[1]
def getName(self):
return self.first_name, self.last_name
f = FigureOut()
f.setName("Allen Solly")
name = f.getName()
print (name)
</code></pre>
<p>I get the following <strong>Output:</strong></p>
<pre><code>('Allen', 'Solly')
</code></pre>
<p>Whenever multiple values are returned from a function in python, does it always convert the multiple values to a <strong>list of multiple values</strong> and then returns it from the function?</p>
<p><em>Is the whole process same as converting the multiple values to a <code>list</code> explicitly and then returning the list, for example in Java, as one can return only one object from a function in Java?</em></p> | 0 |
How to enable ligatures in FiraCode for Visual Studio 2015 | <p>I downloaded the FiraCode font's and have selected that as my font in Visual Studio. However the ligatures are not showing and the wiki doesn't have any special instruction for visual studio, although they imply it works because it is listed in their WORKS column for editor support.</p>
<p><a href="https://github.com/tonsky/FiraCode/" rel="noreferrer">https://github.com/tonsky/FiraCode/</a></p>
<p>Anyone have the missing step(s) to display the ligatures in visual studio 2015?</p> | 0 |
Factory Pattern with Open Generics | <p>In ASP.NET Core, one of the things you can do with Microsoft's dependency injection framework <a href="https://stackoverflow.com/questions/35342472/net-core-dependency-injection">is bind "open generics"</a> (generic types unbound to a concrete type) like so:</p>
<pre><code>public void ConfigureServices(IServiceCollection services) {
services.AddSingleton(typeof(IRepository<>), typeof(Repository<>))
}
</code></pre>
<p>You can also employ <a href="http://dotnetliberty.com/index.php/2016/05/09/asp-net-core-factory-pattern-dependency-injection/" rel="noreferrer">the factory pattern to hydrate dependencies</a>. Here's a contrived example:</p>
<pre><code>public interface IFactory<out T> {
T Provide();
}
public void ConfigureServices(IServiceCollection services) {
services.AddTransient(typeof(IFactory<>), typeof(Factory<>));
services.AddSingleton(
typeof(IRepository<Foo>),
p => p.GetRequiredService<IFactory<IRepository<Foo>>().Provide()
);
}
</code></pre>
<p>However, I have not been able to figure out how to combine the two concepts together. It seems like it would start with something like this, but I need the concrete type that is being used to hydrate an instance of <code>IRepository<></code>.</p>
<pre><code>public void ConfigureServices(IServiceCollection services) {
services.AddTransient(typeof(IFactory<>), typeof(Factory<>));
services.AddSingleton(
typeof(IRepository<>),
provider => {
// Say the IServiceProvider is trying to hydrate
// IRepository<Foo> when this lambda is invoked.
// In that case, I need access to a System.Type
// object which is IRepository<Foo>.
// i.e.: repositoryType = typeof(IRepository<Foo>);
// If I had that, I could snag the generic argument
// from IRepository<Foo> and hydrate the factory, like so:
var modelType = repositoryType.GetGenericArguments()[0];
var factoryType = typeof(IFactory<IRepository<>>).MakeGenericType(modelType);
var factory = (IFactory<object>)p.GetRequiredService(factoryType);
return factory.Provide();
}
);
}
</code></pre>
<p>If I try to use the <code>Func<IServiceProvider, object></code> functor with an open generic, I get <a href="https://github.com/aspnet/DependencyInjection/blob/15bda756314f70cce0f6025f6ef8defab3617cfa/src/Microsoft.Extensions.DependencyInjection/ServiceLookup/ServiceTable.cs#L35" rel="noreferrer">this <code>ArgumentException</code></a> with the message <code>Open generic service type 'IRepository<T>' requires registering an open generic implementation type.</code> from the dotnet CLI. It doesn't even get to the lambda.</p>
<p>Is this type of binding possible with Microsoft's dependency injection framework?</p> | 0 |
Get first and second highest values in pandas columns | <p>I am using pandas to analyse some election results. I have a DF, Results, which has a row for each constituency and columns representing the votes for the various parties (over 100 of them):</p>
<pre><code>In[60]: Results.columns
Out[60]:
Index(['Constituency', 'Region', 'Country', 'ID', 'Type', 'Electorate',
'Total', 'Unnamed: 9', '30-50', 'Above',
...
'WP', 'WRP', 'WVPTFP', 'Yorks', 'Young', 'Zeb', 'Party', 'Votes',
'Share', 'Turnout'],
dtype='object', length=147)
</code></pre>
<p>So...</p>
<pre><code>In[63]: Results.head()
Out[63]:
Constituency Region Country ID Type \
PAID
1 Aberavon Wales Wales W07000049 County
2 Aberconwy Wales Wales W07000058 County
3 Aberdeen North Scotland Scotland S14000001 Burgh
4 Aberdeen South Scotland Scotland S14000002 Burgh
5 Aberdeenshire West & Kincardine Scotland Scotland S14000058 County
Electorate Total Unnamed: 9 30-50 Above ... WP WRP WVPTFP \
PAID ...
1 49821 31523 NaN NaN NaN ... NaN NaN NaN
2 45525 30148 NaN NaN NaN ... NaN NaN NaN
3 67745 43936 NaN NaN NaN ... NaN NaN NaN
4 68056 48551 NaN NaN NaN ... NaN NaN NaN
5 73445 55196 NaN NaN NaN ... NaN NaN NaN
Yorks Young Zeb Party Votes Share Turnout
PAID
1 NaN NaN NaN Lab 15416 0.489040 0.632725
2 NaN NaN NaN Con 12513 0.415052 0.662230
3 NaN NaN NaN SNP 24793 0.564298 0.648550
4 NaN NaN NaN SNP 20221 0.416490 0.713398
5 NaN NaN NaN SNP 22949 0.415773 0.751528
[5 rows x 147 columns]
</code></pre>
<p>The per-constituency results for each party are given in the columns <code>Results.ix[:, 'Unnamed: 9': 'Zeb']</code></p>
<p>I can find the winning party (i.e. the party which polled highest number of votes) and the number of votes it polled using:</p>
<pre><code>RawResults = Results.ix[:, 'Unnamed: 9': 'Zeb']
Results['Party'] = RawResults.idxmax(axis=1)
Results['Votes'] = RawResults.max(axis=1).astype(int)
</code></pre>
<p>But, I also need to know how many votes the second-place party got (and ideally its index/name). So is there any way in pandas to return the <em>second</em> highest value/index in a set of columns for each row?</p> | 0 |
PHP 7 interfaces, return type hinting and self | <p><strong>UPDATE</strong>: PHP 7.4 now <a href="https://www.php.net/manual/en/language.oop5.variance.php" rel="noreferrer">does support covariance and contravariance</a> which addresses the major issue raised in this question. </p>
<hr>
<p>I have run into something of an issue with using return type hinting in PHP 7. My understanding is that hinting <code>: self</code> means that you intend for an implementing class to return itself. Therefore I used <code>: self</code> in my interfaces to indicate that, but when I tried to actually implement the interface I got compatibility errors. </p>
<p>The following is a simple demonstration of the issue I've run into: </p>
<pre><code>interface iFoo
{
public function bar (string $baz) : self;
}
class Foo implements iFoo
{
public function bar (string $baz) : self
{
echo $baz . PHP_EOL;
return $this;
}
}
(new Foo ()) -> bar ("Fred")
-> bar ("Wilma")
-> bar ("Barney")
-> bar ("Betty");
</code></pre>
<p>The expected output was: </p>
<blockquote>
<p>Fred
Wilma
Barney
Betty</p>
</blockquote>
<p>What I actually get is: </p>
<blockquote>
<p>PHP Fatal error: Declaration of Foo::bar(int $baz): Foo must be compatible with iFoo::bar(int $baz): iFoo in test.php on line 7</p>
</blockquote>
<p>The thing is Foo is an implementation of iFoo, so as far as I can tell the implementation should be perfectly compatible with the given interface. I could presumably fix this issue by changing either the interface or the implementing class (or both) to return hint the interface by name instead of using <code>self</code>, but my understanding is that semantically <code>self</code> means "return the instance of the class you just called the method on". Therefore changing it to the interface would mean in theory that I could return any instance of something that implements the interface when my intent is for the invoked instance is what will be returned. </p>
<p>Is this an oversight in PHP or is this a deliberate design decision? If it's the former is there any chance of seeing it fixed in PHP 7.1? If not then what is the correct way of return hinting that your interface expects you to return the instance you just called the method on for chaining? </p> | 0 |
apns payload message json format directly shown | <p>we have implemented apple apns push notification. Configured pem file and device tokens in python. They trigger json payload like this</p>
<blockquote>
<p>{"aps" : {
"alert" : "got 1 new offer. To view, please tap here."
},"notification_type":"New Offer
history","redirect_link”:”offers”}.</p>
</blockquote>
<p>we got notification, but the full json shows in message. we need to display only alert message only on notification message</p> | 0 |
Liquid Warning: Liquid syntax error: Expected end_of_string but found id in | <p>i'm using this line of code</p>
<pre><code><img data-animate="zoomIn" srcset="{{ 'device1.png' | asset_path | magick:resize:549x395 magick:quality:100 }} 1024w, {{ 'device1.png' | asset_path | magick:resize:280x201magick:quality:100 }} 640w" src="{{ 'device1.png' | asset_path | magick:resize:549x395 magick:quality:100 }}" alt="Mac" style="width: 100%; top: 0; left: 0;">
</code></pre>
<p>but i'm getting a liquid error like this</p>
<blockquote>
<p>Liquid Warning: Liquid syntax error: Expected end_of_string but found
id in "{{ 'device1.png' | asset_path | magick:resize:549x395
magick:quality</p>
</blockquote>
<p>Can you help me with the right syntax of this ?</p>
<p>Thanks in advance.
Carlos Vieira</p> | 0 |
How to store values retrieved from a loop in different variables in Python? | <p>Just a quick question.<br>
Suppose, I have a simple for-loop like </p>
<pre><code>for i in range(1,11):
x = raw_input()
</code></pre>
<p>and I want to store all the values of <em>x</em> that I will be getting throughout the loop in <em>different variables</em> such that I can use all these <em>different variables</em> later on when the loop is over.</p> | 0 |
How to Refresh a dynamic table without refreshing the whole html page | <p>I have a dynamic table that displays data from a mysql database. My database is updated every time in the server. I want to refresh only the table every 2 seconds without refreshing the whole page. How can do this? Please help how accomplish this?.
Parts of my table look like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="getdata" border="0" align="left" cellpadding="0" cellspacing="0">
<tr>
<td bgcolor="#CCFF00">Name</td>
<td bgcolor="#CCFF00">Comment</td>
<td bgcolor="#CCFF00">DatePosted</td>
</tr>
</table></code></pre>
</div>
</div>
</p> | 0 |
Error: SQLSTATE[HY000] [1049] Unknown database | <p>I've been working on some beginner php exercise recently and have encountered an error to which I have no idea what is causing it.</p>
<p>It says </p>
<blockquote>
<p>"Error: SQLSTATE[HY000] [1049] Unknown database 'otkrica'" </p>
</blockquote>
<p>The sql file is correctly named "otkrica" and my db.php looks like this:</p>
<pre><code><?php
$dsn = "mysql:host=127.0.0.1;charset=utf8;dbname=otkrica";
try{
$pdo = new PDO($dsn,"root","");
}catch(PDOException $e){
die("Error: " . $e->getMessage());
}
?>
</code></pre>
<p>I would really appreciate input on this one. What am I missing?</p> | 0 |
Breakpoint right before page refresh? | <p>I'm debugging some 3rd-party minified Javascript that somewhere is triggering a browser page refresh. However, I can't figure out what part of the code is causing the refresh.</p>
<p>Is there a way to put a breakpoint in Chrome that will be hit just before a page refresh so I can inspect the call stack to see what caused it?</p> | 0 |
Java Collectors.groupingBy()---is List ordered? | <p>For the <code>Collectors.groupingBy()</code> that returns <code>Map<K,List<T>></code> is it implied that the <code>List<T></code> is in order that the stream is evaluated?</p>
<p>I see no explicit description of the ordering of the list, whereas the concurrent version explicitly states no ordering. If it weren't ordered somehow, I'd expect it to be a Collection though, and I don't see what other ordering it could possibly be, other than order received.</p>
<p>I'm hoping it's guaranteed that the last value in each list is the last value received for that group.</p> | 0 |
Creating a queue with structs in C | <p>I have a code (at the end of this post) that implements a circular queue system. Everything works perfectly, but as can be seen in the function <code>createQueue</code> the queue is implemented only for integers. I would like to modify this code to accept a struct informed by the user.</p>
<p>I could create a known struct and replace all sites with integer, but this way I would be coupling the code to a known struct. Bad idea...</p>
<p>How could pass to the function <code>createQueue</code> a struct for memory allocation without needing to know the struct previously? The struct Queue should also be changed, in <strong>int *elements</strong> the value should be changed from integer to void?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
typedef struct Queue
{
int capacity;
int size;
int front;
int rear;
int *elements;
}Queue;
Queue * createQueue(int maxElements)
{
/* Create a Queue */
Queue *Q;
Q = (Queue *)malloc(sizeof(Queue));
/* Initialise its properties */
Q->elements = (int *)malloc(sizeof(int)*maxElements);
Q->size = 0;
Q->capacity = maxElements;
Q->front = 0;
Q->rear = -1;
/* Return the pointer */
return Q;
}
void Dequeue(Queue *Q)
{
/* If Queue size is zero then it is empty. So we cannot pop */
if(Q->size==0)
{
printf("Queue is Empty\n");
return;
}
/* Removing an element is equivalent to incrementing index of front by one */
else
{
Q->size--;
Q->front++;
/* As we fill elements in circular fashion */
if(Q->front==Q->capacity)
{
Q->front=0;
}
}
return;
}
int front(Queue *Q)
{
if(Q->size==0)
{
printf("Queue is Empty\n");
exit(0);
}
/* Return the element which is at the front*/
return Q->elements[Q->front];
}
void Enqueue(Queue *Q,int element)
{
/* If the Queue is full, we cannot push an element into it as there is no space for it.*/
if(Q->size == Q->capacity)
{
printf("Queue is Full\n");
}
else
{
Q->size++;
Q->rear = Q->rear + 1;
/* As we fill the queue in circular fashion */
if(Q->rear == Q->capacity)
{
Q->rear = 0;
}
/* Insert the element in its rear side */
Q->elements[Q->rear] = element;
}
return;
}
int main()
{
Queue *Q = createQueue(5);
Enqueue(Q,1);
Enqueue(Q,2);
Enqueue(Q,3);
Enqueue(Q,4);
printf("Front element is %d\n",front(Q));
Enqueue(Q,5);
Dequeue(Q);
Enqueue(Q,6);
printf("Front element is %d\n",front(Q));
}
</code></pre> | 0 |
FCM - Programmatically Send Push Notification To User Segments | <p>I am able to send the notification to single device, topics and user segment from Firebase Console.</p>
<p>I want to send the push notification to a user segment. I searched a lot but I'm only getting script to send notification to Single User or Topic not to user segments.</p>
<p>I tried the below code</p>
<pre><code>var client = new RestClient("https://fcm.googleapis.com/fcm/send");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "key=mykey");
request.AddParameter("application/json", "\n\n{\"to\" : \"user-segment-name\",\n\"notification\" : {\n \"body\" : \"test message\",\n \"title\" : \"Portugal vs. Denmark\"\n },\n \"priority\":\"high\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Response.Write(response.Content);
</code></pre>
<p>And I am getting the response below</p>
<pre><code>{"multicast_id":5837227475989925972,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
</code></pre> | 0 |
Add component to dom on click of button in angular2 | <p>I have personInvolved component. This component has personDetails component. There is a button in personInvolved component. Onclick of the button I need to append the personDetails on DOM. each time I click it should append the personDetails component. How can I achieve this.</p> | 0 |
Upload file in laravel | <p>I guys I read the documentation for do a upload file in laravel... But I don't understand more it (I'm beginner)
It's my image.blade.php</p>
<pre><code>{{Form::open(['url'=>'administrator/store ', 'files' => true])}}
{!!Form::file('image') !! }
{!! Form::submit('next')!!}
{{Form::close()}}
</code></pre>
<p>Administrator Controller</p>
<pre><code>use Storage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
public function store(Request $request) {
Storage::put($request->image, 'test') ;
}
</code></pre>
<p>I don't understand what I will put into the function..... Help me pls...
Greetings! </p> | 0 |
App rejected due to missing usage descriptions (Xcode8) | <p>So I got this mail today saying that the latest build of my app was rejected by iTunes Connect due to some missing usage descriptions. To be exact:</p>
<blockquote>
<p>This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSContactsUsageDescription key with a string value explaining to the user how the app uses this data.</p>
<p>This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSCalendarsUsageDescription key with a string value explaining to the user how the app uses this data.</p>
<p>This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSPhotoLibraryUsageDescription key with a string value explaining to the user how the app uses this data.</p>
<p>This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSBluetoothPeripheralUsageDescription key with a string value explaining to the user how the app uses this data.</p>
<p>This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSMicrophoneUsageDescription key with a string value explaining to the user how the app uses this data.</p>
<p>This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSMotionUsageDescription key with a string value explaining to the user how the app uses this data.</p>
<p>Once these issues have been corrected, you can then redeliver the corrected binary.</p>
</blockquote>
<p>I figured out that these have become mandatory with iOS 10, but the only problem is that my app is not requesting permission to access any of these.. I thought the description only was mandatory if you actually requested a permission?</p>
<p>Is it because one of my dependencies (Cocoapods) might contain some code to request these permissions? Or are these descriptions mandatory even if I never request to see the users calendar, contacts, etc?</p> | 0 |