date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/15
| 522 | 1,791 |
<issue_start>username_0: ```
@IdClass=(value = TripleKey.class)
class Triple {
String subject;
String predicate;
String object;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Triple triple = (Triple) o;
if (!subject.equals(triple.subject)) return false;
return predicate.equals(triple.predicate);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + subject.hashCode();
result = 31 * result + predicate.hashCode();
return result;
}
}
```
my objects are:
```
{
"subject": "http://www.someurl.com/thing/resources/#SenMLJSON",
"predicate": "probes\_in",
"object":"http://sweet.jpl.nasa.gov/2.3/matrSediment.owl#clay"
}
```
and
```
{
"subject": "http://www.someurl.com/thing/resources/#SenMLJSON",
"predicate": "probes\_in",
"object":"http://sweet.jpl.nasa.gov/2.3/matrSediment.owl#sand"
}
```
When I try the following I still have duplicates :
```
public static List mergeTripleLists(List oldList, List newList) {
Set tripleSet = new HashSet<>(oldList);
tripleSet.removeAll(newList);
tripleSet.addAll(newList);
return new ArrayList<>(tripleSet);
}
```<issue_comment>username_1: The problem is in:
```
if (!super.equals(o)) return false;
```
If should work after removing it.
Upvotes: 3 [selected_answer]<issue_comment>username_2: The problem is the call to the equals method of the super class which uses object reference to test equality, so remove the line with
```
!super.equals(o)
```
You also need to remove the call to the hashCode method of the super class.
Upvotes: 1
|
2018/03/15
| 1,432 | 2,635 |
<issue_start>username_0: I have a time series dataset (`ts`) with sells for each day.
```
ts
## A tibble: 40 x 2
# dates sells
#
# 1 2014-09-01 32
# 2 2014-09-02 8
# 3 2014-09-03 39
# 4 2014-09-04 38
# 5 2014-09-05 1
# 6 2014-09-06 28
# 7 2014-09-07 33
# 8 2014-09-08 21
# 9 2014-09-09 29
#10 2014-09-10 33
## ... with 30 more rows
```
I want to get the sum of sells in a regular interval, for example in four days.
In this case, the output for the firs 8 days would be:
```
## A tibble: 2 x 1
# value
#
#1 117
#2 83
```
I know that it's easy to do with [resample](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html) from `pandas` in python, however I can't accomplish in R.
my data:
```
ts <- structure(list(dates = structure(c(16314, 16315, 16316, 16317,
16318, 16319, 16320, 16321, 16322, 16323, 16324, 16325, 16326,
16327, 16328, 16329, 16330, 16331, 16332, 16333, 16334, 16335,
16336, 16337, 16338, 16339, 16340, 16341, 16342, 16343, 16344,
16345, 16346, 16347, 16348, 16349, 16350, 16351, 16352, 16353
), class = "Date"), sells = c(32L, 8L, 39L, 38L, 1L, 28L, 33L,
21L, 29L, 33L, 13L, 32L, 10L, 15L, 19L, 3L, 17L, 35L, 29L, 10L,
27L, 14L, 30L, 11L, 24L, 31L, 10L, 27L, 32L, 23L, 25L, 2L, 22L,
4L, 18L, 22L, 15L, 16L, 23L, 3L)), .Names = c("dates", "sells"
), row.names = c(NA, -40L), class = c("tbl_df", "tbl", "data.frame"
))
```
Thank you.<issue_comment>username_1: In `R`, one option is to use `cut.Date` in the `group_by` to create an interval of 4 days and then get the `sum` of 'sells'
```
library(dplyr)
out <- ts %>%
group_by(interval = cut(dates, breaks = '4 day')) %>%
summarise(value = sum(sells))
head(out, 2)
# A tibble: 2 x 2
# interval value
#
#1 2014-09-01 117
#2 2014-09-05 83
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: If we switch to a time series representation it makes it particularly simple:
```
library(zoo)
z <- read.zoo(ts)
z4 <- rollapplyr(z, 4, by = 4, sum)
```
giving the following time series indexed by the ending date of each 4 day interval:
```
> z4
2014-09-04 2014-09-08 2014-09-12 2014-09-16 2014-09-20 2014-09-24 2014-09-28
117 83 107 47 91 82 92
2014-10-02 2014-10-06 2014-10-10
82 66 57
```
(If you wanted to convert the output to a data frame then `fortify.zoo(z4)` or if you just wanted the sequence of sums as a plain vector `coredata(z4)`. )
```
library(ggplot2)
autoplot(z4)
```
[](https://i.stack.imgur.com/wkMkX.png)
Upvotes: 1
|
2018/03/15
| 919 | 3,179 |
<issue_start>username_0: I've implemented a simple network using vis.js. Here's my code:
```
//create an array of nodes
var nodes = [
{
id: "1",
label: "item1"
},
{
id: "2",
label: "item2"
},
{
id: "3",
label: "item3"
},
];
// create an array with edges
var edges = [
{
from: "1",
to: "2",
label: "relation-1",
arrows: "from"
},
{
from: "1",
to: "3",
label: "relation-2",
arrows: "to"
},
];
// create a network
var container = document.getElementById('mynetwork');
// provide the data in the vis format
var data = {
nodes: nodes,
edges: edges
};
var options = {};
// initialize your network!
var network = new vis.Network(container, data, options);
```
On performing the zoom-out operation multiple times the network disappears. Are there any functions to limit the zooming level?<issue_comment>username_1: I wrote you some code to get this function working since there is no zoomMax function within the network of vis.js, I wrote some basic logic to help you out.
```
var container = document.getElementById('mynetwork');
var data = {
nodes: nodes,
edges: edges
};
var afterzoomlimit = { //here we are setting the zoom limit to move to
scale: 0.49,
}
var options = {};
var network = new vis.Network(container, data, options);
network.on("zoom",function(){ //while zooming
if(network.getScale() <= 0.49 )//the limit you want to stop at
{
network.moveTo(afterzoomlimit); //set this limit so it stops zooming out here
}
});
```
Here is a jsfiddle: <https://jsfiddle.net/styb8u9o/>
Hope this helps you.
Upvotes: 4 [selected_answer]<issue_comment>username_2: ***You can use this code is better because you will never go to the middle of the network when you reach the zoom limit:***
```
//NetWork on Zoom
network.on("zoom",function(){
pos = [];
pos = network.getViewPosition();
if(network.getScale() <= 0.49 )
{
network.moveTo({
position: {x:pos.x, y:pos.y},
scale: 0.49,
});
}
if(network.getScale() >= 2.00 ){
network.moveTo({
position: {x:pos.x, y:pos.y},
scale: 2.00,
});
}
});
```
Upvotes: 3 <issue_comment>username_3: Here is a version that preserves the last position, to prevent an annoying jump or slow pan when you get to the maximum extent.
```
let MIN_ZOOM = 0.5
let MAX_ZOOM = 2.0
let lastZoomPosition = {x:0, y:0}
network.on("zoom",function(params){
let scale = network.getScale()
if(scale <= MIN_ZOOM )
{
network.moveTo({
position: lastZoomPosition,
scale: MIN_ZOOM
});
}
else if(scale >= MAX_ZOOM ){
network.moveTo({
position: lastZoomPosition,
scale: MAX_ZOOM,
});
}
else{
lastZoomPosition = network.getViewPosition()
}
});
network.on("dragEnd",function(params){
lastZoomPosition = network.getViewPosition()
});
```
Still, it will be redundant once the following issue is resolved:
<https://github.com/visjs/vis-network/issues/574>
Upvotes: 3
|
2018/03/15
| 1,035 | 4,134 |
<issue_start>username_0: I am a beginner in java and during coding, i faced an issue which is not easy to understand for me. My question is "Write a class with a method to find the area of a rectangle. Create a subclass to find the volume of a rectangular shaped box." The error i am facing is below. I wrote this code for the same:-
```
class Rectangle
{
public int w;
public int h;
public Rectangle(int width, int height)
{
w=width;
h=height;
}
public void area()
{
int area=w*h;
System.out.println("Area of Rectangle : "+area);
}
}
class RectangleBox extends Rectangle
{
int d;
public RectangleBox(int width, int height, int depth)
{
d=depth;
w=width;
h=height;
}
public void volume()
{
int volume=w*h*d;
System.out.println("Volume of Rectangle : "+volume);
}
}
class programm8
{
public static void main(String args[])
{
Rectangle r = new Rectangle(10,20);
RectangleBox rb = new RectangleBox(4,5,6);
r.area();
rb.volume();
}
}
```
>
> Error:(23, 5) java: constructor Rectangle in class code.Rectangle
> cannot be applied to given types; required: int,int found: no
> arguments reason: actual and formal argument lists differ in length
>
>
><issue_comment>username_1: You do need to call a constructor of super class at first:
```
class RectangleBox extends Rectangle
{
int d;
public RectangleBox(int width, int height, int depth)
{
super(width, height);
d=depth;
}
public void volume()
{
int volume=w*h*d;
System.out.println("Volume of Rectangle : "+volume);
}
}
```
Upvotes: 0 <issue_comment>username_2: ```
public RectangleBox(int width, int height, int depth)
{
d=depth;
w=width;
h=height;
}
```
The very first thing this constructor does, is call the constructor of the parent class with the same parameters (unless you specifically tell your constructor to call another one), which would be:
```
public Rectangle(int width, int height, int depth)
{
w=width;
h=height;
}
```
This constructor doesn't exist. You'll need to manually call your parent constructor with the appropriate parameters, like this:
```
public RectangleBox(int width, int height, int depth)
{
super(width, height);
d=depth;
}
```
Upvotes: 1 <issue_comment>username_3: When you create a child object firstly a parent constructor works. In this example when you create a RectangleBox object, firstly Rectangle constructor works after that RectangleBox constructor works. So, your child constructor have to call a parent constructor.
Normally if you have default constructors for parent and child classes, child default constructor calls parent default constructor. But you dont have default constructors because of this RectangleBox constructor have to call a Rectangle constructor. And for calling a parent contructor you have to use `super` keyword.
And then your code:
```
public Rectangle(int width, int height)
{
w=width;
h=height;
}
public RectangleBox(int width, int height, int depth)
{
super(width, width)
h=height;
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_4: Your error is related to the subject; Invoking Superclass Constructor
You can search with that title for detailed information.
If a class is inheriting any properties from another class, the subclass has to invoke its parent class constructor. If the parent's class constructor has no argument java invokes it by itself you don't have to do anything. But in your case Rectangle class has the constructor with the arguments "width" and "height". Therefore when you write the constructor for subclass first thing you need to do is invoking parent class'. When you want to call a parameterized constructor of the superclass, you need to use the super keyword as shown below.
```
public RectangleBox(int width, int height, int depth)
{
super(width, height);
d=depth;
w=width;
h=height;
}
```
Upvotes: 0
|
2018/03/15
| 599 | 2,255 |
<issue_start>username_0: I am appending element on a node. I am stuck in a situation that on every click event the same element get append to the parent.
How can I stop preventing the element to append again and again and add just once on the first click.
```js
document.getElementsByClassName("btn")[0].onclick = function(e) {
e.preventDefault();
var div = document.createElement("div");
div.innerHTML="error";
document.getElementsByClassName("errors")[0].appendChild(div);
}
```
```css
div { border: 1px solid black }
```
```html
Click
Errors:
```<issue_comment>username_1: You can check if a `div` (or *any other selector*) is already there or not.
```
var errorEl = document.getElementsByClassName("errors")[0];
var doesDivExist = !!errorEl.querySelector( "div" );
if ( !doesDivExist )
{
errorEl.appendChild(div);
}
```
**Demo**
```js
var div = document.createElement("div");
div.innerHTML = "error";
document.getElementsByClassName("btn")[0].onclick = function(e) {
e.preventDefault();
var errorEl = document.getElementsByClassName("errors")[0];
var doesDivExist = !!errorEl.querySelector("div");
if (!doesDivExist) {
errorEl.appendChild(div);
}
}
```
```css
div {
border: 1px solid black
}
```
```html
Click
Errors:
```
Upvotes: 0 <issue_comment>username_2: You an put a conditional in your click event... like this one, carefull this is asking if it has a a child, you might want to set a more specific conditional....
```
var div = document.createElement("div");
document.getElementsByClassName("btn")[0].onclick = function(e) {
e.preventDefault();
if (document.getElementsByClassName("errors")[0].firstChild) {
document.getElementsByClassName("errors")[0].appendChild(div);
}
}
```
Upvotes: 0 <issue_comment>username_3: After using the event, you could assign an empty function to the event.
```js
document.getElementsByClassName("btn")[0].onclick = function(e) {
var div = document.createElement("div");
e.preventDefault();
div.innerHTML = 'test';
document.getElementsByClassName("errors")[0].appendChild(div);
document.getElementsByClassName("btn")[0].onclick = function () {};
}
```
```html
button
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 931 | 3,315 |
<issue_start>username_0: I have generated the python client and server from <https://editor.swagger.io/> - and the server runs correctly with no editing, but I can't seem to get the client to communicate with it - or with anything.
I suspect I'm doing something really silly but the examples I've found on the Internet either don't work or appear to be expecting that I understand how to craft the object. Here's my code (I've also tried sending nothing, a string, etc):
```
import time
import swagger_client
import json
from swagger_client.rest import ApiException
from pprint import pprint
# Configure OAuth2 access token for authorization: petstore_auth
swagger_client.configuration.access_token = 'special-key'
# create an instance of the API class
api_instance = swagger_client.PetApi()
d = '{"id": 0,"category": {"id": 0,"name": "string"},"name": "doggie","photoUrls": ["string"], "tags": [ { "id": 0, "name": "string" } ], "status": "available"}'
python_d = json.loads(d)
print( json.dumps(python_d, sort_keys=True, indent=4) )
body = swagger_client.Pet(python_d) # Pet | Pet object that needs to be added to the store
try:
# Add a new pet to the store
api_instance.add_pet(body)
except ApiException as e:
print("Exception when calling PetApi->add_pet: %s\n" % e)
```
I'm using python 3.6.4 and when the above runs I get:
```
Traceback (most recent call last):
File "petstore.py", line 14, in
body = swagger\_client.Pet(python\_d) # Pet | Pet object that needs to be added to the store
File "/Users/bombcar/mef/petstore/python-client/swagger\_client/models/pet.py", line 69, in \_\_init\_\_
self.name = name
File "/Users/bombcar/mef/petstore/python-client/swagger\_client/models/pet.py", line 137, in name
raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501
ValueError: Invalid value for `name`, must not be `None`
```
I feel I'm making an incredibly basic mistake, but I've literally copied the JSON from <https://editor.swagger.io/> - but since I can't find an actually working example I don't know what I'm missing.<issue_comment>username_1: The Python client generator produces object-oriented wrappers for the API. You cannot post a dict or a JSON string directly, you need to create a `Pet` object using the generated wrapper:
```
api_instance = swagger_client.PetApi()
pet = swagger_client.Pet(name="doggie", status="available",
photo_urls=["http://img.example.com/doggie.png"],
category=swagger_client.Category(id=42))
response = api_instance.add_pet(pet)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I got similar issue recently and finally fixed by upgrading python version in my local. I generated python-flask-server zip file from <https://editor.swagger.io/>. Then I set up the environment locally with py 3.6.10. I got same error when parsing input by using "Model\_Name.from\_dict()", telling me
```
raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501
ValueError: Invalid value for `name`, must not be `None`
```
Then I upgraded to python 3.7.x, the issue was resolved. I know that your problem is not related to version, however, just in case anyone got similar issue and seeking for help could see this answer.
Upvotes: 1
|
2018/03/15
| 513 | 1,827 |
<issue_start>username_0: i'm new to excel macros and I would like some help with hiding some columns,
I have 2 drop down lists in A2 and A3, both have the options of yes or no. How can I make column C hidden if the No option is chosen in the drop down in A2 and column D disappear if the No option is chosen for the drop down in A3. Then if yes is chosen for both drop downs the columns reappear.<issue_comment>username_1: Try a Worksheet\_Change event sub procedure in the worksheet's code sheet.
```
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A2:A3")) Is Nothing Then
On Error GoTo meh
Application.EnableEvents = False
columns(3).entirecolumn.hidden = cbool(lcase(Range("A2").value) = "no")
columns(4).entirecolumn.hidden = cbool(lcase(Range("A3").value) = "no")
End If
meh:
Application.EnableEvents = True
End Sub
```
I'm assuming that the 'dropdowns' in A2:A3 are data validation lists.
Upvotes: 1 [selected_answer]<issue_comment>username_2: You will have to use events. For a brief tutorial on how to create them, visit: <http://www.excel-easy.com/vba/events.html>
In the example below, I used the `worksheet_calculate` event, which will be triggered everytime the sheet is calculated. You may choose to use the `worksheet_selectionchange`, in case the **Yes/No** dropdown change doesn't trigger a calculation.
```
Private Sub Worksheet_Calculate()
If ActiveSheet.Range("A2").Value = "Yes" Then
Columns(3).Hidden = False
ElseIf ActiveSheet.Range("A2").Value = "No" Then
Columns(3).Hidden = True
End If
If ActiveSheet.Range("A3").Value = "Yes" Then
Columns(4).Hidden = False
ElseIf ActiveSheet.Range("A3").Value = "No" Then
Columns(4).Hidden = True
End If
End Sub
```
Upvotes: 2
|
2018/03/15
| 570 | 1,897 |
<issue_start>username_0: I was reading online about function on PostgreSQL and returns results
In this links:
1. [SQL function return-type: TABLE vs SETOF records](https://stackoverflow.com/questions/22423958/sql-function-return-type-table-vs-setof-records)
2. [How do I reference named parameters in Postgres sql functions?](https://stackoverflow.com/questions/9771546/how-do-i-reference-named-parameters-in-postgres-sql-functions)
3. <http://www.postgresqltutorial.com/plpgsql-function-returns-a-table/>
I have written this Function:
```
create or replace function brand_hierarchy(account_value int)
RETURNS table (topID INTEGER, accountId INTEGER, liveRowCount bigint,archiveRowCount bigint)
AS
$BODY$
SELECT * FROM my_client_numbers
where accountId = coalesce($1,accountId);
$BODY$
LANGUAGE sql;
```
Which works and return the results in a single column Type of record.
Note that might more than one row will return.
Now the response is:
```
record
(1172,1172,1011,0)
(1172,1412,10,40)
.....
```
I would like to get my results not as a record but as multiple columns
```
|---------|---------|------------|----------------|
| topID |accountId|liveRowCount|archiveRowCount |
|---------|---------|------------|----------------|
| 1172 |1172 | 1011 | 0 |
| 1172 |1412 | 10 | 40 |
```
Is there a way to return multiple columns from a PostgreSQL function<issue_comment>username_1: I was able to see it as expected with this query:
```
SELECT * FROM brand_hierarchy (id)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Functions returning a table (or setof) should be used in the FROM clause:
```
select *
from brand_hierarchy(1234)
```
Upvotes: 4 <issue_comment>username_3: I found this function `crosstab` I think it is what you're looking for
<https://www.postgresql.org/docs/9.3/tablefunc.html>
Upvotes: 0
|
2018/03/15
| 1,971 | 4,893 |
<issue_start>username_0: I am trying to follow this tutorial to be abe to use C code in python. <http://dfm.io/posts/python-c-extensions/>
here is the gist <https://gist.github.com/GreenJoey/b08528d6abe62da70f28f73c39c0efd0>
when I try to compile it using `python setup.py build_ext --inplace` it fails with this error message:
```
running build_ext
No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
building '_chi2' extension
creating build\temp.win-amd64-3.6
creating build\temp.win-amd64-3.6\Release
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\XXX\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\core\include -IC:\Users\XXX\AppData\Local\Continuum\anaconda3\include -IC:\Users\XXX\AppData\Local\Continuum\anaconda3\include -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" -I"C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" -I"C:\Program Files (x86)\Windows Kits\8.1\include\shared" -I"C:\Program Files (x86)\Windows Kits\8.1\include\um" -I"C:\Program Files (x86)\Windows Kits\8.1\include\winrt" /Tc_chi2.c /Fobuild\temp.win-amd64-3.6\Release\_chi2.obj
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\XXX\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\core\include -IC:\Users\XXX\AppData\Local\Continuum\anaconda3\include -IC:\Users\XXX\AppData\Local\Continuum\anaconda3\include -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" -I"C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" -I"C:\Program Files (x86)\Windows Kits\8.1\include\shared" -I"C:\Program Files (x86)\Windows Kits\8.1\include\um" -I"C:\Program Files (x86)\Windows Kits\8.1\include\winrt" /Tcchi2.c /Fobuild\temp.win-amd64-3.6\Release\chi2.obj
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Users\XXX\AppData\Local\Continuum\anaconda3\libs /LIBPATH:C:\Users\XXX\AppData\Local\Continuum\anaconda3\PCbuild\amd64 /LIBPATH:"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\LIB\amd64" /LIBPATH:"C:\Program Files (x86)\Windows Kits\10\lib\10.0.10240.0\ucrt\x64" /LIBPATH:"C:\Program Files (x86)\Windows Kits\8.1\lib\winv6.3\um\x64" /EXPORT:PyInit__chi2 build\temp.win-amd64-3.6\Release\_chi2.obj build\temp.win-amd64-3.6\Release\chi2.obj /OUT:C:\workspace\c\b08528d6abe62da70f28f73c39c0efd0-a1d1f0469637e3a3578ab5f8ee0e641a8e31d572\_chi2.cp36-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.6\Release\_chi2.cp36-win_amd64.lib
LINK : error LNK2001: unresolved external symbol PyInit__chi2
build\temp.win-amd64-3.6\Release\_chi2.cp36-win_amd64.lib : fatal error LNK1120: 1 unresolved externals
error: Command "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Users\XXX\AppData\Local\Continuum\anaconda3\libs /LIBPATH:C:\Users\XXX\AppData\Local\Continuum\anaconda3\PCbuild\amd64 /LIBPATH:"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\LIB\amd64" /LIBPATH:"C:\Program Files (x86)\Windows Kits\10\lib\10.0.10240.0\ucrt\x64" /LIBPATH:"C:\Program Files (x86)\Windows Kits\8.1\lib\winv6.3\um\x64" /EXPORT:PyInit__chi2 build\temp.win-amd64-3.6\Release\_chi2.obj build\temp.win-amd64-3.6\Release\chi2.obj /OUT:C:\workspace\c\b08528d6abe62da70f28f73c39c0efd0-a1d1f0469637e3a3578ab5f8ee0e641a8e31d572\_chi2.cp36-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.6\Release\_chi2.cp36-win_amd64.lib" failed with exit status 1120
```
looks like it cannot find `unresolved external symbol PyInit__chi2` but the method is defined. see <https://gist.github.com/GreenJoey/b08528d6abe62da70f28f73c39c0efd0#file-_chi2-c-L33>
I understand that it is a linking error, but I only import "Python.h" once so I do not understand why it cannot find the method.<issue_comment>username_1: I found the soultion here <https://gist.github.com/douglas-larocca/099bf7460d853abb7c17>
PyInit has to be marked with PyMODINIT\_FUNC
```
PyMODINIT_FUNC PyInit__chi2(void)
{
PyObject *module;
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_chi2",
module_docstring,
-1,
module_methods,
NULL,
NULL,
NULL,
NULL
};
module = PyModule_Create(&moduledef);
if (!module) return NULL;
/* Load `numpy` functionality. */
import_array();
return module;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: In my case this error was due to a mismatch between the module name I provided in `setup.py` and the module name used in the `PYBIND11_MODULE()` macro in my `cpp` bindings file (first argument to the macro).
Upvotes: 2
|
2018/03/15
| 1,998 | 5,984 |
<issue_start>username_0: I have this array:
```
$arrayAll = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
```
where the keys are unique - they don't ever repeat. And the value could be either 1 or 2 - nothing else.
And I need to "split" this `$arrayAll` array into `$array1` - that will contain everything with value 1 and `$array2` - that will contain everything with value 2 so in the end I will have:
```
$array1 = [
'156' => '1',
'157' => '1',
'159' => '1',
'161' => '1'
];
```
and
```
$array2 = [
'158' => '2',
'160' => '2'
];
```
and as you can see, I will have the keys from the original array will remain the same.
What is the simplest thing to do to separate the original array like this?<issue_comment>username_1: Use `foreach` and compare each value and assign it to a new array.
```
$array1 = [];
$array2 = [];
foreach($arrayAll as $key=>$val){
if($val == 2){
$array2[$key] = $val;
}else{
$array1[$key] = $val;
}
}
print_r($array1);
print_r($array2);
```
[Demo](https://3v4l.org/cK7YH)
Upvotes: 0 <issue_comment>username_2: This is probably the simplest way.
Loop it and create a temporary array to hold the values then extract the values to your array 1 and 2.
```
Foreach($arrayAll as $k => $v){
$res["array" . $v][$k] = $v;
}
Extract($res);
Var_dump($array1, $array2);
```
<https://3v4l.org/6en6l>
Updated to use extract and a method of variable variables.
The update means it will work even if there is a value "3" in the input array.
<https://3v4l.org/jbvBf>
Upvotes: 0 <issue_comment>username_3: The simplest thing to do is to use a [`foreach` loop](http://php.net/manual/en/control-structures.foreach.php).
```
$array = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
$array1 = [];
$array2 = [];
foreach ($array as $key => $value)
// If value is 1, add to array1
// If value is not 1, add value to array2
if ($value === '1')
$array1[$key] = $value;
else
$array2[$key] = $value;
echo var_dump($array1);
echo '
';
echo var_dump($array2);
```
Upvotes: -1 <issue_comment>username_4: Use indirect reference:
```
$arrayAll = array("156"=>"1", "157"=>"1", "158"=>"2", "159"=>"1", "160"=>"2", "161"=>"1");
foreach($arrayAll as $key=>$value) {
$name = "array".$value;
$$name[$key] = $value;
}
echo "
```
";
print_r($array1);
print_r($array2);
echo "
```
";
```
Upvotes: -1 <issue_comment>username_5: ```
//your array
$yourArray = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
```
With the conditions you mentioned just build two arrays, you can use array\_keys with the second parameter that accepts a search value
```
$array1 = array_keys($yourArray, '1');
$array2 = array_keys($yourArray, '2');
```
If you don't want to use array\_keys, go for an iteration
```
$array1 = array();
$array2 = array();
foreach($yourArray as $key=>$value){
//will always be 1 or 2, so an if-else is enought
if($value == 1){
$array1[] = $key;
} else {
$array2[] = $key;
}
}
```
And that's it.
Check [this link](http://php.net/manual/es/function.array-keys.php) for array\_keys
If you have more than 2 values, the following will work and can be reused for other cases
You want to group them according to the values
```
$arrayOfValues = array_values($yourArray);
//this returns only the values of the array
$arrayOfUniqueValues = array_unique($arrayOfValues);
//this returns an array with the unique values, also with this u consider
//the posibility for more different values
//also u can get the unique values array on a single line
$arrayIfUniqueValues = array_unique(array_values($yourArray));
```
The array you will return
```
$theReturn = array();
foreach($arrayOfUniqueValues as $value ){
//what does this do?
//for each iteration it creates a key in your return array "$theReturn"
//and that one is always equal to the $value of one of the "Unique Values"
//array_keys return the keys of an array, and with the second parameter
//it acceps a search parameter, so the keys it return are the ones
//that matches the value, so here u are getting the array already made
$theReturn[$value] = array_keys($yourArray, $value);
}
```
The var\_dump, in this case, will look like this
```
array(2) {
[1]=>
array(4) {
[0]=>
int(156)
[1]=>
int(157)
[2]=>
int(159)
[3]=>
int(161)
}
[2]=>
array(2) {
[0]=>
int(158)
[1]=>
int(160)
}
}
```
Hope my answer helps you, I tried to organize the solutions starting with the shortest/simplest.
Edit:
I forgot you needed the key value too, at least in this solution the array is always referring to the value, like `$array1, $array2` or the `$key` references to the value as in the last solution
Upvotes: -1 <issue_comment>username_6: The simplest solution for separating an array into others based on the values involves:
1. Getting its unique values using [`array_unique`](http://php.net/manual/en/function.array-unique.php).
2. Looping over these values using [`foreach`](http://php.net/manual/en/control-structures.foreach.php).
3. Getting the key-value pairs intersecting with the current value using [`array_intersect`](http://php.net/manual/en/function.array-intersect.php).
**Code:**
```
# Iterate over every value and intersect it with the original array.
foreach(array_unique($arrayAll) as $v) ${"array$v"} = array_intersect($arrayAll, [$v]);
```
**Advantage:**
The advantage of this answer when compared to other given answers is the fact that it uses [`array_unique`](http://php.net/manual/en/function.array-unique.php) to find the unique values and therefore iterates only twice instead of `n` times.
Check out a live demo [here](https://3v4l.org/Ofnbg).
Upvotes: -1
|
2018/03/15
| 1,852 | 5,850 |
<issue_start>username_0: I have huge pandas crosstab, I want to filter item that just appear once, to make easier to explain, I will make artificial data, here's my data
```
Customer_id Apple Book Candy
1 0 1 1
2 1 1 0
3 1 1 0
4 1 0 0
```
Because `Candy` is just appeared once, so the result will be like
```
Customer_id Apple Book
1 0 1
2 1 1
3 1 1
4 1 0
```<issue_comment>username_1: Use `foreach` and compare each value and assign it to a new array.
```
$array1 = [];
$array2 = [];
foreach($arrayAll as $key=>$val){
if($val == 2){
$array2[$key] = $val;
}else{
$array1[$key] = $val;
}
}
print_r($array1);
print_r($array2);
```
[Demo](https://3v4l.org/cK7YH)
Upvotes: 0 <issue_comment>username_2: This is probably the simplest way.
Loop it and create a temporary array to hold the values then extract the values to your array 1 and 2.
```
Foreach($arrayAll as $k => $v){
$res["array" . $v][$k] = $v;
}
Extract($res);
Var_dump($array1, $array2);
```
<https://3v4l.org/6en6l>
Updated to use extract and a method of variable variables.
The update means it will work even if there is a value "3" in the input array.
<https://3v4l.org/jbvBf>
Upvotes: 0 <issue_comment>username_3: The simplest thing to do is to use a [`foreach` loop](http://php.net/manual/en/control-structures.foreach.php).
```
$array = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
$array1 = [];
$array2 = [];
foreach ($array as $key => $value)
// If value is 1, add to array1
// If value is not 1, add value to array2
if ($value === '1')
$array1[$key] = $value;
else
$array2[$key] = $value;
echo var_dump($array1);
echo '
';
echo var_dump($array2);
```
Upvotes: -1 <issue_comment>username_4: Use indirect reference:
```
$arrayAll = array("156"=>"1", "157"=>"1", "158"=>"2", "159"=>"1", "160"=>"2", "161"=>"1");
foreach($arrayAll as $key=>$value) {
$name = "array".$value;
$$name[$key] = $value;
}
echo "
```
";
print_r($array1);
print_r($array2);
echo "
```
";
```
Upvotes: -1 <issue_comment>username_5: ```
//your array
$yourArray = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
```
With the conditions you mentioned just build two arrays, you can use array\_keys with the second parameter that accepts a search value
```
$array1 = array_keys($yourArray, '1');
$array2 = array_keys($yourArray, '2');
```
If you don't want to use array\_keys, go for an iteration
```
$array1 = array();
$array2 = array();
foreach($yourArray as $key=>$value){
//will always be 1 or 2, so an if-else is enought
if($value == 1){
$array1[] = $key;
} else {
$array2[] = $key;
}
}
```
And that's it.
Check [this link](http://php.net/manual/es/function.array-keys.php) for array\_keys
If you have more than 2 values, the following will work and can be reused for other cases
You want to group them according to the values
```
$arrayOfValues = array_values($yourArray);
//this returns only the values of the array
$arrayOfUniqueValues = array_unique($arrayOfValues);
//this returns an array with the unique values, also with this u consider
//the posibility for more different values
//also u can get the unique values array on a single line
$arrayIfUniqueValues = array_unique(array_values($yourArray));
```
The array you will return
```
$theReturn = array();
foreach($arrayOfUniqueValues as $value ){
//what does this do?
//for each iteration it creates a key in your return array "$theReturn"
//and that one is always equal to the $value of one of the "Unique Values"
//array_keys return the keys of an array, and with the second parameter
//it acceps a search parameter, so the keys it return are the ones
//that matches the value, so here u are getting the array already made
$theReturn[$value] = array_keys($yourArray, $value);
}
```
The var\_dump, in this case, will look like this
```
array(2) {
[1]=>
array(4) {
[0]=>
int(156)
[1]=>
int(157)
[2]=>
int(159)
[3]=>
int(161)
}
[2]=>
array(2) {
[0]=>
int(158)
[1]=>
int(160)
}
}
```
Hope my answer helps you, I tried to organize the solutions starting with the shortest/simplest.
Edit:
I forgot you needed the key value too, at least in this solution the array is always referring to the value, like `$array1, $array2` or the `$key` references to the value as in the last solution
Upvotes: -1 <issue_comment>username_6: The simplest solution for separating an array into others based on the values involves:
1. Getting its unique values using [`array_unique`](http://php.net/manual/en/function.array-unique.php).
2. Looping over these values using [`foreach`](http://php.net/manual/en/control-structures.foreach.php).
3. Getting the key-value pairs intersecting with the current value using [`array_intersect`](http://php.net/manual/en/function.array-intersect.php).
**Code:**
```
# Iterate over every value and intersect it with the original array.
foreach(array_unique($arrayAll) as $v) ${"array$v"} = array_intersect($arrayAll, [$v]);
```
**Advantage:**
The advantage of this answer when compared to other given answers is the fact that it uses [`array_unique`](http://php.net/manual/en/function.array-unique.php) to find the unique values and therefore iterates only twice instead of `n` times.
Check out a live demo [here](https://3v4l.org/Ofnbg).
Upvotes: -1
|
2018/03/15
| 707 | 2,952 |
<issue_start>username_0: Say, I'm Fechting thousands or record using some long runing task from DB and caching it using Redis. Next day somebody have changed few records in DB.
Next time how redis would know that it has to return cached data or again have to revisit that all thousands of records in DB?
How this synchronisation achived?<issue_comment>username_1: Since the source of truth resides on your Database and you push data from this DB to Redis, you always have to update from DB to Redis, at least you create another process to sync data.
My suggestion is just to run a first full update from DB to Redis and then use a synch process which every time you notice update/creation/deletion operation in your database you pull it to Redis.
I don't know which Redis structure are you using to store database records in Redis but I guess it could be a Hash, probably indexed by your table index so the sync operation will be immediate: if a record is created in your database you set a HSET, if deletion HDEL and so on.
You even could omit the first full sync from DB to Redis, and just clean Redis and start the sync process.
If you cannot do the above for some reason you can create a syncher daemon which constantly read data from the database and compare them with the data store in Redis if they are different in somehow you update or if they don't exist in some of both sides you can delete or create the entry in Redis.
Upvotes: 3 <issue_comment>username_2: Redis has no idea whether the data in DB has been updated.
Normally, we use Redis to cache data as follows:
1. Client checks if the data, e.g. key-value pair, exists in Redis.
2. If the key exists, client gets the corresponding value from Redis.
3. Otherwise, it gets data from DB, and sets it to Redis. Also client sets an expiration, say `5` minutes, for the key-value pair in Redis.
4. Then any subsequent requests for the same key will be served by Redis. Although the data in Redis might be out-of-date.
5. However, after `5` minutes, this key will be removed from Redis automatically.
6. Go to step 1.
So in order to keep your data in Redis update-to-date, you can set a short expiration time. However, your DB has to serve lots of requests.
If you want to largely decrease requests to DB, you can set a large expiration time. So that, most of time, Redis can serve the requests with possible staled data.
**You should consider carefully about the trade-off between performance and staled data.**
Upvotes: 5 [selected_answer]<issue_comment>username_3: My solution is:
When you are updating, deleting or adding new data in database, you should delete all data in redis. In your get route, you should check if data exists. If not, you should store all data to redis from db.
Upvotes: 1 <issue_comment>username_4: you may use @CacheEvict on any update/delete applied on DB. that would clear up responding values from cache, so next query would get from DB
Upvotes: 0
|
2018/03/15
| 533 | 1,929 |
<issue_start>username_0: For some reasons I need to use JDK8 and JDK9. Is a good idea to put both paths (to JDK8 and JDK9) into the same JAVA\_HOME system environment's variable?
Details: I need to run both systems at the same time, one with ant (which uses jdk8) and second with maven (which uses jdk9).<issue_comment>username_1: Usually that path is reserved for the current active java command keyword in the command line interface. You can't have multiple JDK active at the same time at any moment when using the terminal. So it is not a good idea.
You can however point the JAVA\_HOME to the folder where you have multiple JDK installations and then set the PATH variable to a certain JDK. So when you want to change the JDK you change only the PATH variable and leave JAVA\_HOME as it is.
If you intend to use different JDK across multiple projects in an IDE, then yes you can have multiple JDK and you can chose the JDK you want to use in the Project Settings.
Upvotes: 1 <issue_comment>username_2: If I were you then I would create function() in `.profile` or `.bashrc` for command prompt or terminal which will export `JAVA_HOME` variable to `Java8` or `Java9` depending on whether I am running `ant` or `mvn` respectively.
Lets say your Java8 and Java9 are installed at below locations ...
* C:\Program Files\Java\jdk1.8.0\_151\bin
* C:\Program Files\Java\jdk1.9.0\_4\bin
Then your functions in `.profile` or `.bashrc` should be like this ...
For `ant` and Java8 (here i am passing command line argument `$1` to `ant` command)...
```
runant() {
export JAVA_HOME="C:\Program Files\Java\jdk1.8.0_151\bin";
ant $1;
}
```
For `mvn` and Java9 ...
```
runmvn() {
export JAVA_HOME="C:\Program Files\Java\jdk1.9.0_4\bin";
mvn clean install;
}
```
With the above functions, you can run `ant` and `mvn` from command prompt and `JAVA_HOME` will be set appropriately ONLY for that specific run.
Upvotes: 0
|
2018/03/15
| 290 | 1,169 |
<issue_start>username_0: I've tried creating a reference to the constraint and then setting the Layout Priority but this makes the app crash
```
let topTrasactionConstraint = transactionsTableviewContainer.topAnchor.constraint(equalTo: buttonsStackContainerView.bottomAnchor, constant: 6)
NSLayoutConstraint.activate([
topTrasactionConstraint,
transactionsTableviewContainer.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
transactionsTableviewContainer.widthAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.widthAnchor, constant: -20),
transactionsTableviewContainer.heightAnchor.constraint(equalToConstant: 500)
])
topTrasactionConstraint.priority = UILayoutPriority.init(999)
```<issue_comment>username_1: How about `topTrasactionConstraint.priority = 999`?
<https://useyourloaf.com/blog/easier-swift-layout-priorities/>
Upvotes: 1 <issue_comment>username_2: I found out that I was calling
```
topTrasactionConstraint.priority = UILayoutPriority.init(999)
```
Before `NSLayoutConstraint.activate`
This was causing my application to crash
Upvotes: 4 [selected_answer]
|
2018/03/15
| 182 | 635 |
<issue_start>username_0: I tried with below two ways. Both are working fine, I want to know which one is good in terms of performance as i have to use it in procedure multiple times.
1. `var1 := var2;`
2. `SELECT var2 INTO var1 FROM dual;`<issue_comment>username_1: How about `topTrasactionConstraint.priority = 999`?
<https://useyourloaf.com/blog/easier-swift-layout-priorities/>
Upvotes: 1 <issue_comment>username_2: I found out that I was calling
```
topTrasactionConstraint.priority = UILayoutPriority.init(999)
```
Before `NSLayoutConstraint.activate`
This was causing my application to crash
Upvotes: 4 [selected_answer]
|
2018/03/15
| 389 | 1,442 |
<issue_start>username_0: I am trying to distinguish currently selected routerLink from others by giving it class which will change some styles.
So in html i added some properties and event to links.
app.component.html:
```
Dashboard
Products List
```
and in typescript I have implemented variable and method.
app.component.ts:
```
import { Component } from '@angular/core';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] })
export class AppComponent {
pageSelected:string;
setActivepage(page){
this.pageSelected = page; }
}
```
but there is nothing happening after link click although activePage class is already set in styles.
Somebody got an idea how to make it work ?<issue_comment>username_1: ```
Dashboard
Products List
```
Upvotes: 0 <issue_comment>username_2: <https://angular.io/api/router/RouterLinkActive>
You just need to use routerLinkActive prop for that on your routerLink's.
Upvotes: 2 <issue_comment>username_3: @vikas and @username_2 already showed you the solution! I show you how you should use it.
The 'angular' router knows which route is active and will set a class on the active `a` tag for you. You only have to define which class should be set.
.css
```
.active-route {
background: black;
border-bottom: 2px solid red;
}
```
.html
```
Dashboard
Products List
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 376 | 1,336 |
<issue_start>username_0: How can I safely put elements in
`ConcurrentMap > cmap = new ConcurrentMap>();`
I operate on my concurrent map as follows:
* If a key does not exist: put an entry with some string and a brand new
`Set`
* If there exists: add a specific `Integer` to this key's
`Set` value.<issue_comment>username_1: ConcurrentMap has a method to initialize the map value if missing. I assume also the set inside should be thread safe:
```
Set set = cmap.computeIfAbsent(key,(k)-> Collections.newSetFromMap(new ConcurrentHashMap<>()));
set.add(value);
```
Before lambda:
```
Set set = cmap.get(key);
if (set == null) {
set = Collections.newSetFromMap(new ConcurrentHashMap<>());
Set prev = cmap.putIfAbsent(key, set);
if (prev != null) {
set = prev;
}
}
set.add(value);
```
Upvotes: 2 <issue_comment>username_2: In concurrent environment you probably should use concurrent map and concurrent set. For example `ConcurrentHashMap`, and `Collections.newSetFromMap(new ConcurrentHashMap<>())`. The `ConcurrentHashMap.putIfAbsent()` method prevent race condition of `if(!containsKey) put` mechanic.
So the code will looks like
```
public void add(String s, Integer i) {
cmap.putIfAbsent(s, Collections.newSetFromMap(new ConcurrentHashMap<>()));
Set set = cmap.get(s);
set.add(i);
}
```
Upvotes: 0
|
2018/03/15
| 569 | 2,069 |
<issue_start>username_0: I'm automating Azure B2B Invitation process. At this stage I need to know if invited user has accepted invite or not.
Is there any way to do it?<issue_comment>username_1: There doesn't seem to be any programmatic way to do this at the moment as far as I can tell.
The attribute that tells you the the status is named `source` and can be read through the UI:
[](https://i.stack.imgur.com/bmZAE.png)
but is not included in the PowerShell cmdlet output for getting a user, nor in the Azure AD Graph API.
See this [link](https://learn.microsoft.com/en-us/azure/active-directory/active-directory-b2b-user-properties) for more information.
Upvotes: 2 [selected_answer]<issue_comment>username_2: I recently needed some way of quickly determining the list of users who hadn't accepted these invitations. I realize the question is tagged with C#, but I ended up using PowerShell to accomplish this goal.
There exists a PowerShell module for [AzureAD](https://learn.microsoft.com/en-us/powershell/module/azuread/?view=azureadps-2.0), which has a Cmdlet named [`Get-AzureADUser`](https://learn.microsoft.com/en-us/powershell/module/azuread/get-azureaduser?view=azureadps-2.0), that can give you the information you need.
Install the AzureAD PowerShell module by running the following command:
```
Install-Module AzureAD
```
After installation, you must import the module to make the Cmdlets available, and then authenticate:
```
Import-Module AzureAd
Connect-AzureAD
```
From here, it's a simple command to pull a list of all the users that *haven't* accepted the invitations:
```
Get-AzureADUser `
| Where-Object { $_.UserType -eq 'Guest' -and $_.UserState -eq 'PendingAcceptance' } `
| Select-Object -Property DisplayName,Mail,UserState,UserStateChangedOn `
| Sort-Object -Property DisplayName `
| Format-Table -AutoSize
```
To see a list of users who have accepted invitations, you can instead use `$_.UserState -eq 'Accepted'` within the `Where-Object` ScriptBlock.
Upvotes: 0
|
2018/03/15
| 1,175 | 3,268 |
<issue_start>username_0: I have below JSON array. I want to give rank based on number of entries of user. Here <EMAIL> will get 1st rank because it has 3 entries. other will get 2nd and 3rd respectively based on number of entries.
```js
let data = [{
"email": "<EMAIL>"
},
{
"email": "<EMAIL>"
},
{
"email": "<EMAIL>"
},
{
"email": "<EMAIL>"
},
{
"email": "<EMAIL>"
},
{
"email": "<EMAIL>"
}
]
function groupBy(list, keyGetter) {
const map = new Map();
list.forEach((item) => {
const key = keyGetter(item);
if (!map.has(key)) {
map.set(key, [item]);
} else {
map.get(key).push(item);
}
});
return map;
}
var grouped = groupBy(data, a => a.email);
console.log(grouped);
```
You see my code to calculate numebr of entries by user. It gives me total entries but I'm not sure how to calculate rank.
Above code gives me grouped by values. But it does not help me to count rank.
Output should just rank of user. like 1, 2 or 3.
[JSFiddle](http://jsfiddle.net/srjahir32/pbaw55nk/)<issue_comment>username_1: You could use [`Array#reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) for that.
You only need to setup an `accumulator` that will contain every email as a `key` and the number of occurences of said email as a `value`.
```js
let arr = [
{"email": "<EMAIL>"},
{"email": "<EMAIL>"},
{"email": "<EMAIL>"},
{"email": "<EMAIL>"},
{"email": "<EMAIL>"},
{"email": "<EMAIL>"}
];
let ranking = arr.reduce((acc, curr) => {
if(acc[curr.email]) acc[curr.email]++;
else acc[curr.email] = 1;
return acc;
},{});
console.log(ranking);
```
Upvotes: 2 <issue_comment>username_2: You could count the occurences and sort the result by the count.
```js
function groupBy(list, key) {
const map = new Map();
list.forEach(item => map.set(item[key], (map.get(item[key]) || 0) + 1));
return [...map]
.sort(({ 1: a }, { 1: b }) => a - b)
.map((rank => (item, i, a) => ({ [key]: item[0], rank: (a[i - 1] || [])[1] === item[1] ? rank : ++rank }))(0));
}
var data = [{ email: "<EMAIL>" }, { email: "<EMAIL>" }, { email: "<EMAIL>" }, { email: "<EMAIL>" }, { email: "<EMAIL>" }, { email: "<EMAIL>" }, { email: "<EMAIL>" }],
grouped = groupBy(data,'email');
console.log(grouped);
```
Upvotes: 2 <issue_comment>username_3: Use the functions `reduce` and `sort`
```js
var array = [ {"email": "<EMAIL>"}, {"email": "<EMAIL>"}, {"email": "<EMAIL>"}, {"email": "<EMAIL>"}, {"email": "<EMAIL>"}, {"email": "<EMAIL>"}];
var result = Object.values(array.reduce((a, c) => {
(a[c.email] || (a[c.email] = {email: c.email, rank: 0})).rank++;
return a;
}, {})).sort((a, b) => b.rank - a.rank);
result.forEach((r, i) => r.rank = i + 1);
console.log(result);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 5,394 | 8,658 |
<issue_start>username_0: I wanted the product of last 12 months data from the current row.
```
Date Open
21/06/11 839.9
22/06/11 853.35
23/06/11 846.55
24/06/11 874.15
27/06/11 866.7
28/06/11 878.9
29/06/11 875.7
30/06/11 888.7
01/07/11 907
04/07/11 874.4
05/07/11 869.3
06/07/11 848.85
07/07/11 858
08/07/11 873
11/07/11 854
12/07/11 847.5
13/07/11 853.05
14/07/11 863.3
15/07/11 867.7
18/07/11 871.9
19/07/11 867.5
20/07/11 886
21/07/11 875.95
22/07/11 866
25/07/11 892
26/07/11 888.25
27/07/11 875
28/07/11 855
29/07/11 840
01/08/11 838
02/08/11 827.55
03/08/11 826.75
04/08/11 828
05/08/11 799.5
08/08/11 776.7
09/08/11 753
10/08/11 785.35
11/08/11 768.35
12/08/11 783
16/08/11 760
17/08/11 760.5
18/08/11 757.7
19/08/11 731.05
22/08/11 731
23/08/11 760.35
24/08/11 764
25/08/11 761.6
26/08/11 751
29/08/11 731.1
30/08/11 765
02/09/11 796.7
05/09/11 794.5
06/09/11 783.2
07/09/11 824
08/09/11 833.5
09/09/11 852.15
12/09/11 810.35
13/09/11 813.2
14/09/11 813.9
15/09/11 833
16/09/11 850
19/09/11 825
20/09/11 823
21/09/11 850.9
22/09/11 823.95
23/09/11 773.9
26/09/11 769.2
27/09/11 774
28/09/11 799.75
29/09/11 790.5
30/09/11 803.5
03/10/11 791.2
04/10/11 784
05/10/11 772.55
07/10/11 786.7
10/10/11 804.25
11/10/11 835
12/10/11 829.4
13/10/11 850
14/10/11 842
17/10/11 867
18/10/11 825
19/10/11 825.5
20/10/11 834.85
21/10/11 840
24/10/11 848
25/10/11 855
26/10/11 879
28/10/11 899.7
31/10/11 898
01/11/11 870.5
02/11/11 855
03/11/11 867.75
04/11/11 905
08/11/11 879
09/11/11 890.05
11/11/11 859
14/11/11 891.4
15/11/11 871
16/11/11 859.1
17/11/11 845.05
18/11/11 800.3
21/11/11 800
22/11/11 788.1
23/11/11 789.9
24/11/11 775
25/11/11 769.7
28/11/11 765
29/11/11 782
30/11/11 756.7
01/12/11 799
02/12/11 797
05/12/11 808.35
07/12/11 807
08/12/11 802
09/12/11 769.9
12/12/11 760.55
13/12/11 723.9
14/12/11 738
15/12/11 731.9
16/12/11 749
19/12/11 719.2
20/12/11 741.7
21/12/11 727
22/12/11 741.35
23/12/11 760
26/12/11 747.05
27/12/11 766
28/12/11 757.7
29/12/11 733.65
30/12/11 713
02/01/12 696.8
03/01/12 712.25
04/01/12 727.4
05/01/12 715
06/01/12 697.05
07/01/12 716.7
09/01/12 714.45
10/01/12 712
11/01/12 737.9
12/01/12 747.5
13/01/12 742
16/01/12 729.95
17/01/12 716
18/01/12 762
19/01/12 789
20/01/12 790
23/01/12 755.3
24/01/12 774.6
25/01/12 788.7
27/01/12 800
30/01/12 813.9
31/01/12 804.5
01/02/12 818.9
02/02/12 835
03/02/12 830
06/02/12 845.9
07/02/12 842
08/02/12 847
09/02/12 856.75
10/02/12 850.35
13/02/12 841.1
14/02/12 846.9
15/02/12 854.2
16/02/12 831
17/02/12 822.05
21/02/12 817.5
22/02/12 848
23/02/12 832
24/02/12 833.5
27/02/12 821.8
28/02/12 789.05
29/02/12 805.05
01/03/12 811.8
02/03/12 816.25
03/03/12 811
05/03/12 812.05
06/03/12 797
07/03/12 776.55
09/03/12 775.3
12/03/12 790
13/03/12 803.45
14/03/12 828
15/03/12 818
16/03/12 780
19/03/12 781
20/03/12 756.1
21/03/12 760
22/03/12 765.9
23/03/12 743.8
26/03/12 743.9
27/03/12 738
28/03/12 730
29/03/12 718
30/03/12 729.5
02/04/12 749.35
03/04/12 744.25
04/04/12 745
09/04/12 740.05
10/04/12 746
11/04/12 739
12/04/12 733.3
13/04/12 746.05
16/04/12 747.1
17/04/12 754.8
18/04/12 750
19/04/12 753.9
20/04/12 740.05
23/04/12 725.85
24/04/12 739
25/04/12 734.1
26/04/12 737.1
27/04/12 741.3
28/04/12 739.8
30/04/12 737.5
02/05/12 747.9
03/05/12 738.5
04/05/12 733.4
07/05/12 715
08/05/12 718
09/05/12 702
10/05/12 697.25
11/05/12 693
14/05/12 698
15/05/12 679
16/05/12 675
17/05/12 680.25
18/05/12 676.9
21/05/12 686.5
22/05/12 704.6
23/05/12 685.2
24/05/12 694
25/05/12 695
28/05/12 692
29/05/12 702.2
30/05/12 699.65
31/05/12 697
01/06/12 707.35
04/06/12 677
05/06/12 696
06/06/12 704.45
07/06/12 721.05
08/06/12 718
11/06/12 732.7
12/06/12 715
13/06/12 722.25
14/06/12 716
15/06/12 718.5
18/06/12 730.35
19/06/12 717
20/06/12 738
21/06/12 734
22/06/12 713.55
25/06/12 714.2
26/06/12 717.5
27/06/12 726.4
28/06/12 724.4
29/06/12 725.1
02/07/12 735.5
03/07/12 739.95
04/07/12 740
05/07/12 734.95
06/07/12 738
09/07/12 729
10/07/12 731.45
11/07/12 733.45
12/07/12 721.9
13/07/12 720
16/07/12 720
17/07/12 724.8
18/07/12 718
19/07/12 720.2
20/07/12 722.3
23/07/12 715
24/07/12 721
25/07/12 720.4
26/07/12 720.9
27/07/12 719
30/07/12 723
31/07/12 731.6
01/08/12 740.25
02/08/12 742.1
03/08/12 735
06/08/12 748.05
07/08/12 786.05
08/08/12 785.05
09/08/12 788.9
10/08/12 777.65
13/08/12 779.5
14/08/12 787.9
16/08/12 802.05
17/08/12 817.9
21/08/12 816
22/08/12 809.2
23/08/12 810.55
24/08/12 791.75
27/08/12 786
28/08/12 786.85
29/08/12 791
30/08/12 779.75
31/08/12 780
03/09/12 768
04/09/12 763.95
05/09/12 775.25
06/09/12 766.3
07/09/12 778.7
08/09/12 793.5
10/09/12 800
11/09/12 789.5
12/09/12 793.5
13/09/12 798.1
14/09/12 813
17/09/12 848.1
18/09/12 870.2
```
I tried using something on these lines but did not find a solution:
```
df['val']= df['Open'].last('12M').transform('prod')
```
How can I get the result?<issue_comment>username_1: You could use [`Array#reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) for that.
You only need to setup an `accumulator` that will contain every email as a `key` and the number of occurences of said email as a `value`.
```js
let arr = [
{"email": "<EMAIL>"},
{"email": "<EMAIL>"},
{"email": "<EMAIL>"},
{"email": "<EMAIL>"},
{"email": "<EMAIL>"},
{"email": "<EMAIL>"}
];
let ranking = arr.reduce((acc, curr) => {
if(acc[curr.email]) acc[curr.email]++;
else acc[curr.email] = 1;
return acc;
},{});
console.log(ranking);
```
Upvotes: 2 <issue_comment>username_2: You could count the occurences and sort the result by the count.
```js
function groupBy(list, key) {
const map = new Map();
list.forEach(item => map.set(item[key], (map.get(item[key]) || 0) + 1));
return [...map]
.sort(({ 1: a }, { 1: b }) => a - b)
.map((rank => (item, i, a) => ({ [key]: item[0], rank: (a[i - 1] || [])[1] === item[1] ? rank : ++rank }))(0));
}
var data = [{ email: "<EMAIL>" }, { email: "<EMAIL>" }, { email: "<EMAIL>" }, { email: "<EMAIL>" }, { email: "<EMAIL>" }, { email: "<EMAIL>" }, { email: "<EMAIL>" }],
grouped = groupBy(data,'email');
console.log(grouped);
```
Upvotes: 2 <issue_comment>username_3: Use the functions `reduce` and `sort`
```js
var array = [ {"email": "<EMAIL>"}, {"email": "<EMAIL>"}, {"email": "<EMAIL>"}, {"email": "<EMAIL>"}, {"email": "<EMAIL>"}, {"email": "<EMAIL>"}];
var result = Object.values(array.reduce((a, c) => {
(a[c.email] || (a[c.email] = {email: c.email, rank: 0})).rank++;
return a;
}, {})).sort((a, b) => b.rank - a.rank);
result.forEach((r, i) => r.rank = i + 1);
console.log(result);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 3,260 | 9,641 |
<issue_start>username_0: I am attempting to implement a grid of cells, analogous to that of Conway's game of life.
While each individual grid should have fixed size in both dimensions, I would like a Grid struct that allows for any size in both dimensions.
This is in analogy to how arrays can be of any size, but an array once initialized has a fixed size.
This is what I have so far:
```
typedef struct Cell {
int data;
// stuff to be added later
} Cell;
typedef struct Grid {
unsigned width;
unsigned height;
Cell cell[][];
} Grid;
Grid initGrid(unsigned width, unsigned height) {
Grid g;
g.width = width;
g.height = height;
g.cell = malloc( sizeof(Cell)*width*height );
return g;
}
```
However I get the following compile-time error:
```
main.c|12|note: declaration of `‘cell’ as multidimensional array must have bounds for all dimensions except the first|
```
>
> How can I define a `Grid` data type with flexible size?
>
>
>
Post scriptum: as a C newbie, I thought the following would work:
```
typedef struct Grid {
unsigned width;
unsigned height;
Cell cell[width][height];
} Grid;
```
Post post scriptum: I am always uneasy whenever I use `malloc`. Am I doing (or trying to do) anything horribly wrong here?<issue_comment>username_1: You can't do it with double indexing (`cell[x][y]`) in C, there's no way to express that the number of bytes to jump for each row is dynamic.
So, the best (in my opinion) way to do is it to just do the indexing manually, using a one-dimensional array.
Put a plain:
```
Cell *cell;
```
in the `struct` (keeping `width` and `height`) and then index like so:
```
set_cell(Grid *g, unsigned int x, unsigned int y, Cell value)
{
g->cell[y * g->width + x] = value;
}
```
it's not unlikely that the compiler will inline this, and it's going to be pretty tight. Probably faster than the jagged array" approach which uses much more memory and another layer of indirection.
Allocation is simple:
```
Grid initGrid(unsigned int width, unsigned int height)
{
Grid g;
g.width = width;
g.height = height;
g.cell = malloc(width * height * sizeof *g.cell);
// add assert or error here, can't return NULL for value type
return g;
}
```
if you wanted to heap-allocate `Grid` too, you could co-allocate it with its elements.
And yes, you need to `free()` the allocation when you're done with it, in order to not leak memory. Strictly speaking on modern systems the OS will free all resources when the program ends anyway, but it's good form to free anyway:
```
void destroyGrid(Grid g)
{
free(g.cell);
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: You are pretty much out of luck here, as there is no way in C to use variable array lengths within a `struct` definition. What you can do is this:
```
typedef struct Grid {
unsigned width, height;
void* cell_internal; //Type: Cell(*)[height]
} Grid;
#define cell(myGrid) ((Cell(*)[(myGrid).height])(myGrid).cell_internal)
//in the constructor of Grid
newGrid->width = ...;
newGrid->height = ...;
cell(*newGrid) = malloc(newGrid->width*sizeof(*cell(*newGrid)));
for(unsigned x = 0; x < newGrid->width; x++) {
for(unsigned y = 0; y < newGrid->height; y++) {
cell(*newGrid)[x][y] = ...;
}
}
```
This is a dirty little hack, but it should work fine. The cool part is, that you can simply address your grid cells with `cell(aGrid)[x][y]`. The downside is, that it does obscure what is actually going on quite thoroughly. And there are not many people who can actually read what the `cell()` macro does. (Hint: It simply casts the `void*` to a pointer to a column array `Cell(*)[myGrid.height]`, whatever `myGrid.height` may be at that point in time.)
---
Of course, you can go more explicit like this:
```
typedef struct Grid {
unsigned width, height;
void* cell_internal; //Type: Cell(*)[height]
} Grid;
//in the constructor of Grid
newGrid->width = ...;
newGrid->height = ...;
Cell (*cells)[newGrid->height] = malloc(newGrid->width*sizeof(*cells));
newGrid->cell_internal = cells;
for(unsigned x = 0; x < newGrid->width; x++) {
for(unsigned y = 0; y < newGrid->height; y++) {
cells[x][y] = ...;
}
}
```
The downside of this approach is, that you will need to explicitly create an alias pointer for the `cell_internal` pointer in each function that works on the cell data with
```
Cell (*cells)[myGrid->height] = myGrid->cell_internal;
```
Probably, this is the better approach, as it would seem to be readable to more people.
Upvotes: 0 <issue_comment>username_3: Use a flexible array. It's trivial to do with two `malloc()` calls, and possible to do with just one if you care to push the limits of alignment restrictions or strict aliasing or want to write the code to coerce the alignment of the portion of `malloc()`'d used to store `Cell` structures.
```
typedef struct Grid {
unsigned width;
unsigned height;
Cell *cell[];
} Grid;
Grid *initGrid(unsigned width, unsigned height )
{
// the Grid structure itself
size_t bytesNeeded = sizeof( Grid );
// space for pointers
bytesNeeded += height * sizeof( Cell * );
Grid *g = malloc( bytesNeeded );
g->width = width;
g->height = height;
// get all the data needed with one malloc call
g->cell[ 0 ] = malloc( width * height * sizeof( Cell ) );
// fill in the pointers
for ( unsigned ii = 1; ii < height; ii++ )
{
g->cell[ ii ] = g->cell[ 0 ] + ii * width;
}
return g;
}
void freeGrid( Grid *g )
{
free( g->cell[ 0 ] );
free( g );
}
```
If you don't mind pushing the limits of strict aliasing, you can do it with a flexible array and a single call to `malloc()` (it's left as an exercise for the reader to coerce the alignment of the data portion so that there's no potential alignment problems - that definitely is possible to do):
```
typedef struct Grid {
unsigned width;
unsigned height;
Cell *cell[];
} Grid;
Grid *initGrid(unsigned width, unsigned height )
{
// the Grid structure itself
size_t bytesNeeded = sizeof( Grid );
// space for pointers
bytesNeeded += height * sizeof( Cell * );
// space for data
bytesNeeded += width * height * sizeof( Cell );
Grid *g = malloc( bytesNeeded );
g->width = width;
g->height = height;
// fill in the pointers
// (technically a strict-aliasing/alignment violation as it assumes
// that &(g->cell[ height ]) is suitable to store a Cell...)
for ( unsigned ii = 0; ii < height; ii++ )
{
g->cell[ ii ] = ( Cell * ) &(g->cell[ height ]) +
ii * width;
}
return g;
}
```
Upvotes: 0 <issue_comment>username_4: following this excelent post:
[How do I work with dynamic multi-dimensional arrays in C?](https://stackoverflow.com/questions/917783/how-do-i-work-with-dynamic-multi-dimensional-arrays-in-c)
read @JensGustedt post and follow his link [variable length arrays (VLAs)](http://www.drdobbs.com/the-new-cwhy-variable-length-arrays/184401444)
there is actually a way - I followed his post and written a small test program to verify:
```
#include
#include
int main(int argc, char \*\* argv)
{
unsigned int height = 100;
unsigned int width = 10;
int (\*array)[width] = malloc (sizeof(int[height][width]));
array[90][2] = 1231;
printf("%d", array[90][2]);
}
```
---
```
#include
#include
int main(int argc, char \*\* argv)
{
unsigned int height;
unsigned int width;
int i,j;
printf("enter width: ");
scanf("%d", &width);
printf("enter height: ");
scanf("%d", &height);
int (\*array)[width] = malloc (sizeof(int[height][width]));
for (i = 0; i < height; i++ )
for (j = 0; j < width; j++ )
array[i][j] = i;
for (i = 0; i < height; i++ ) {
for (j = 0; j < width; j++ )
printf("%d ", array[i][j]);
printf("\n");
}
}
```
---
and the console:
```
enter width: 10
enter height: 6
0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5
```
---
I'll admit it suprising - I was not aware this exists...
---
EDIT - using structs:
```
#include
#include
typedef struct Cell {
int data;
// stuff to be added later
} Cell;
typedef struct Grid {
unsigned width;
unsigned height;
Cell \*cell;
} Grid;
Grid initGrid(unsigned width, unsigned height) {
Grid g;
g.width = width;
g.height = height;
g.cell = malloc( sizeof(Cell[height][width]) );
return g;
}
int main(int argc, char \*\* argv)
{
unsigned int height;
unsigned int width;
int i,j;
Grid test;
printf("enter width: ");
scanf("%d", &width);
printf("enter height: ");
scanf("%d", &height);
test = initGrid (width, height);
Cell (\*array)[width] = test.cell;
for (i = 0; i < height; i++ )
for (j = 0; j < width; j++ )
array[i][j].data = i;
for (i = 0; i < height; i++ ) {
for (j = 0; j < width; j++ )
printf("%d ", array[i][j].data);
printf("\n");
}
}
```
console output:
```
enter width: 20
enter height: 10
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
```
there is a casting warning which i did not have time to resolve, but one can implement the idea - just do it cleanly... again it's a POC not an actual program
Upvotes: 1
|
2018/03/15
| 633 | 2,233 |
<issue_start>username_0: I am trying to make work icecast 2 and my letsencrypt SSL with no luck. So far what I did is built icecast 2 with openssl support and I also made it run but it always give the next error in the log file.
```
[2018-03-15 12:48:21] WARN connection/get_ssl_certificate Invalid private key file /usr/local/icecast/share/fullchain.pem
[2018-03-15 12:48:21] INFO connection/get_ssl_certificate No SSL capability on any configured ports
```
I have set these cert files readable by user: richard and of course I am also running the server itself with the richard user.
Maybe you have any idea what is wrong?
You may also see my config file here:
```
8443
1
```
In the path section I have set the ssl-certificate part to the SSL.
```
/usr/local/icecast/share/icecast/fullchain.pem
```
Nothing so far. The server itself is starting on the port, however when visiting it through https:// it just doesn't load. with http:// the port (8443) works fine.
Any help appricated.<issue_comment>username_1: Actually, I solved the issue myself.
The problem was the SSL not the configurations. Seems the LetsEncrypt SSL that is generated (fullchain.pem) is not working correctly. So instead of using that, I have copied the content from cert.pem and privkey.pem and made a new file named icecast.pem and pasted both into one. (first cert and then the privkey) and now everything is works fine and secure!
I am a genius!!!
Upvotes: 5 [selected_answer]<issue_comment>username_2: For the Icecast2 complete certificate, you can use the command:
```
cat /etc/letsencrypt/live/domain.com/fullcert.pem /etc/letsencrypt/live/domain.com/privkey.pem > /etc/icecast2/bundle.pem
```
This will concatenate and save both certificates to a single file called bundle.pem under icecast2 folder, to which you can point the icecast2 configuration.
I have also found this very helpful and complete guide for reference: <https://mediarealm.com.au/articles/icecast-https-ssl-setup-lets-encrypt/>
Upvotes: 1 <issue_comment>username_3: There is another way, by forwarding of Nginx, whose config is common on internet. So that the server only expose 80 and 443 port for http web. Then use letsencrypt for SSL of Nginx.
Upvotes: 0
|
2018/03/15
| 1,718 | 5,809 |
<issue_start>username_0: I'm using the following code to create a 2D array of booleans (initially filled with false), and then flipping the value individually.
```
constructor(props) {
super(props);
this.state = {
fullGrid: Array(3).fill(Array(5).fill(false))
};
this.toggleFullGrid = this.toggleFullGrid.bind(this);
}
//Toggles boolean value found at id
toggleFullGrid(cols, rows) {
alert("This is index.js, we got everything: " + cols + " " + rows);
let alteredGrid = this.state.fullGrid;
console.log(alteredGrid);
console.log(cols + " " + rows);
console.log(alteredGrid[cols][rows]);
//change alteredGrid at cols,rows
alteredGrid[cols][rows] = !alteredGrid[cols][rows];
console.log(alteredGrid);
this.setState({fullGrid: alteredGrid});
}
```
However, rather than flipping individual values, this causes an entire column to be flipped (in a very confusing way). Here's the console output:
```
(3) [Array(5), Array(5), Array(5)]
0 : (5) [true, false, false, false, false]
1 : (5) [true, false, false, false, false]
2 : (5) [true, false, false, false, false]
length : 3
__proto__ : Array(0)
index.js:21 0 0
index.js:22 false
index.js:26
(3) [Array(5), Array(5), Array(5)]
0 : (5) [true, false, false, false, false]
1 : (5) [true, false, false, false, false]
2 : (5) [true, false, false, false, false]
length : 3
__proto__ : Array(0)
```
The first array is a copy of before the flip, so I'm unsure why it's not all false. The second and third output prove that the program knows what it's flipping and where. The fourth output (second array) is identical to the first one.
Furthermore, it's not truly updating either. The state change should force other elements to update (and change color based on whether they correspond to true or false in the array), but that is not happening.
**Question: Why is it flipping the entire column? Why is the first outputted array the same as the second outputted array? How would I get it to flip single values? How would I get it to update correctly?**
Also, someone told me weird things happen with arrays in javascript when trying to flip values, so I tested a version where I saved the array value to a separate var, flipped that, and then saved it back. The result was identical.<issue_comment>username_1: Seems like the way you have used `Array.fill()` is causing the issue.
The reason for this is, that there has only been one row, which had internally been referenced three times. So when you changed any cell in any row, that particular cell in other rows also change.
You can use the `Array fill` like this :
```
this.state = {
fullGrid : Array(3).fill(0).map(row => new Array(5).fill(false))
}
```
The above solution will first create an array with 0s and then map each row with a new array in which you can fill false.
Also you can test that:
```
var a = new Array(3).fill(new Array(5).fill(false));
(3) [Array(5), Array(5), Array(5)]
0 : (5) [false, false, false, false, false]
1 : (5) [false, false, false, false, false]
2 : (5) [false, false, false, false, false]
length : 3
__proto__ : Array(0)
```
if you do
```
a[0][0] = true
```
now a will become :
```
(3) [Array(5), Array(5), Array(5)]
0 : (5) [true, false, false, false, false]
1 : (5) [true, false, false, false, false]
2 : (5) [true, false, false, false, false]
length : 3
__proto__ : Array(0)
```
Since the value is changed by reference, each row's first cell has become `true`.
Your `console.log` output is same because `console.log` happens in an `asynchronous` manner.
[Checkout this link for more details about it](https://stackoverflow.com/questions/44362783/value-below-was-evaluated-just-now-in-javascript-object/44362860#44362860)
Upvotes: 3 [selected_answer]<issue_comment>username_2: Welcome to the magical (sic!) world of Javascript Arrays, References and Mutable objects!
---
To answer: **Why is it flipping the entire column?**
Arrays do not work like simple values (booleans, string, numbers) where data are copied. When you assign a variable an array, you are only assigning its **reference** not the actual object (all non-primitive values in javascript are objects).
So to follow what you wrote:
`Array(3).fill(Array(5).fill(false))` is two statements:
1. `Array(5).fill(false)`
2. `Array(3).fill(...)`
In the first one, you create **one** Array(5) filled with false, and in the second, you fill a new Array(3) with the **same** Array(5) **3** times.
So when you alter the `array[0][0]` you are actually modifying the same object behind it, and you find yourself altering three different references, but still the same and only Array(5) created before.
---
To answer: **Why is the first outputted array the same as the second outputted array?**
Because a `console.log` does not freeze the values displayed, and if it usually works for simple values, it is not **immediate**. The time needed to "print" the value in the console, the original array has already been altered. And because you print a **reference**, this reference will reflect changes applied to its value.
*I'm sorry if it's not really comprehensible, as it's difficult for me to explain properly how it works as English it's not my mother-tongue.*
---
To answer: **How would I get it to flip single values? How would I get it to update correctly?**
You need to work with "Immutable" values.
First, create a truly immutable state:
```
const array5 = Array(5).fill(false);
this.state = {
fullGrid: Array(3).fill(null).map(() => array5.slice())
};
```
Then, when working with your state, also copy the new array to work with:
```
let alteredGrid = this.state.fullGrid.slice();
```
Now, you are safe to set your new clean state which will properly replace the old state.
Upvotes: 1
|
2018/03/15
| 571 | 2,047 |
<issue_start>username_0: I know im doing it wrong because i edited this from just a name search can someone help me figure out what im doing wrong? Tried searching but nothing shows up.
```
| Search by date
"> Between
">
|
if($_GET["ftxtKeyword"] != "")
{
$objConnect = mysql_connect("localhost","root","1234") or die("Error Connect to Database");
$objDB = mysql_select_db("mydatabase");
$strSQL = "SELECT * FROM service WHERE Service_date BETWEEN ".$_GET["ftxtKeyword"]." AND ".$_GET["btxtKeyword"]."";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
?
```<issue_comment>username_1: Dates, assuming they are in the right format, need to be in quotes like this
```
BETWEEN '".$_GET["ftxtKeyword"]."' AND '".$_GET["btxtKeyword"]."'";
```
The right format would be `YYYY-MM-DD`
Upvotes: 1 <issue_comment>username_2: Your SQL statement, is not quoting the dates correctly.
Instead of
```
$strSQL = "SELECT * FROM service WHERE Service_date BETWEEN ".$_GET["ftxtKeyword"]." AND ".$_GET["btxtKeyword"]."";
```
Change it to
```
$strSQL = "SELECT * FROM service WHERE Service_date BETWEEN '".$_GET["ftxtKeyword"]."' AND '".$_GET["btxtKeyword"]."'";
```
**Few things to note:**
1. Do take @username_1's suggestion into account... do not use deprecated function, as when you eventually move to a server (or upgrade PHP to a higher version), you will run into a lot of headaches.
2. Avoid using PHP short tags for `echo`s. Instead of `=</code use `php echo</code. Why? Think what might happen when you move your code to an environment where `php.ini` settings has the short tags turned off?... headaches.``
3. In general, I would recommend using `POST` as a form's method instead of `GET`; when you use `GET`, you expose the params etc. right in the URL when you hit the submit button... and
4. Do not use `POST` or `GET` values directly within your SQL statement. Use prepared statements and always sanitize user inputs... As a golden rule of thumb: **NEVER trust the user** :)
Upvotes: 2
|
2018/03/15
| 487 | 1,765 |
<issue_start>username_0: Need to convert below string into object
```
"{"taskStatus":"Not Started","taskFields":{"originalTransactionDate":"${datafield:feerefund:originalTranDate}","transactionPostingDate":"${datafield:feerefund:tranPostingDate}","referenceNumber":"${datafield:feerefund:referenceNum}","promotionIdentifier":"${datafield:feerefund:promoId}","merchantAdjustmentDescription":"${datafield:feerefund:merchantAdjDesc}","transactionAmount":"${datafield:feerefund:tranAmount}","batchPrefix":"${datafield:feerefund:batchPrefix}","transactionCode":"${datafield:feerefund:tranCode}"}}"
```<issue_comment>username_1: Take a look at JSON.parse:
```
let object = JSON.parse(string)
```
where string is your json string
Upvotes: 1 <issue_comment>username_2: Correct JSON String is
```
"{"taskStatus":"Failed","taskFields":{"originalTransactionDate":"2017-08-17","transactionPostingDate":"2017-08-17","referenceNumber":"12345","promotionIdentifier":"undefined","merchantAdjustmentDescription":"test","transactionAmount":"150.00","batchPrefix":"IF","transactionCode":"Failed 6"}}"
```
and to convert string into object
```
var object = JSON.parse(String)
```
Upvotes: 0 <issue_comment>username_3: ```js
var str = '{"taskStatus":"Failed","taskFields":{"originalTransactionDate":"2017-08-17","transactionPostingDate":"2017-08-17","referenceNumber":"12345","promotionIdentifier":"undefined","merchantAdjustmentDescription":"test","transactionAmount":"150.00","batchPrefix":"IF","transactionCode":"Failed6"}}';
str = JSON.parse(str);
document.write(JSON.stringify(str));
```
```html
Your string input have double quote the end "transactionCode":~~"~~"Failed6"
============================================================================
```
Upvotes: 0
|
2018/03/15
| 383 | 1,342 |
<issue_start>username_0: I'm adding content to a predefined layout that I cannot modify but allows any HTML. I wish to align a piece of text like a floating text box but due to the h4 and p classes that I can't change it is proving difficult.
What I'd like to see is: [](https://i.stack.imgur.com/TlMLD.png)
But it currently looks like: [](https://i.stack.imgur.com/aDk17.png)
The resulting HTML is currently:
```
#### Foo
BAR
*quite a long but of text that needs to wrap*
```
...where my content starts at *BAR* and ends with the *i* and *div* end tags.
I think I may be missing a formatting trick.<issue_comment>username_1: ```
#### Foo
BAR
*quite a long but of text that needs to wrap*
```
That should be more what you're after, tags are suited for changing/styling text within paragraphs because tags are more for structural elements.
Your original code also had an extra opening on the last line.
Upvotes: 1 <issue_comment>username_2: I used MS Word to create a document as I wanted it to appear and then tripped out all the extraneous twaddle it puts in; leaving me with:
```
```
then found a workaround to mimic the `#### and `sections so that it all fit into one instead.``
Upvotes: 1 [selected_answer]
|
2018/03/15
| 373 | 1,455 |
<issue_start>username_0: In parents controller $onInit() I'm waiting for resolving promise to set page title and get opid for list which has own controller.
This is from parent controller:
```
public $onInit = () => {
this.swSubviewInfo.resolved.then((response: IDashboardResponseData) => {
this.setGroupId(response.opid);
this.updateTitle(response.objectName);
});
}
```
I'd like to use state provider to wait for parent to resolve $onInit because correct opid is needed in initialization of child controller. Can sb give me example how to do that?
Below config file for child controller.
```
const state: IStateProvider = {
controller: "groupMembersSubviewListController",
controllerAs: "vm",
template: require("./groupMembersSubviewList.html"),
resolve: {
parent: ???
}
};
```<issue_comment>username_1: ```
#### Foo
BAR
*quite a long but of text that needs to wrap*
```
That should be more what you're after, tags are suited for changing/styling text within paragraphs because tags are more for structural elements.
Your original code also had an extra opening on the last line.
Upvotes: 1 <issue_comment>username_2: I used MS Word to create a document as I wanted it to appear and then tripped out all the extraneous twaddle it puts in; leaving me with:
```
```
then found a workaround to mimic the `#### and `sections so that it all fit into one instead.``
Upvotes: 1 [selected_answer]
|
2018/03/15
| 571 | 2,540 |
<issue_start>username_0: I want to use Angular Universal for two things: SEO and preview of the site on social media. I know it is possible with static site content.
But what about dynamic content? What if I want search engines and social media crawlers to find not only the main site with a welcome-screen, but individual blog-posts like `www.example.com/posts?articleName=what-is-angular-universal-good-for`? Here the route `/posts` is handled by a PostsComponent, which subscribes to queryParam `articleName`. So it always renders an article which it dynamically fetches from a database.
Would Angular Universal's server-side-rendering be applied here?
I see that Universal does have something called TransferState. But can that be used for dynamic content? I assume if you rebuild the server-side-app every time you update the posts-DB, it should be able to run the rendering on every (dynamically resolved) post. E.g. this would be the action list for the server-side code:
1. Prerender Main Site
2. Load array of all possible blog-article-URLs from a DB
3. Fetch their content and prerender every single one of them
4. When User requests a blog post, only the main site and that post is served. All the other other posts are prerendered and available on the server too, but do not get delivered unless explicitly requested
So is that possible or should I stop looking further into Universal?<issue_comment>username_1: Angular Server side will work as any other server side platform. If you have to get articles from url will render the information of that article, is not different than a Wordpress or Django website in that terms.
Angular TransferState is just a mechanism that will pass all the information you gather in the server to the client so you don't have to do some requests again when the application starts on the client side. So you might what to do some HttpIntercerptor that will check the TransferState before doing a request to make sure the infromation is not there yet.
Upvotes: 4 [selected_answer]<issue_comment>username_2: Once you add angular universal it will automatically add ssr and it will load the dynamic content automatically. If it is not loading then check you console by running command "ng run blog:serve-ssr"(blog is name of project) in your local. There should be some error that's why it will not be loading. Once you resolve the issue then it will load the dynamic content automatically.
Note: Prerending does not allow load of dynamic content only server side rendering does.
Upvotes: 2
|
2018/03/15
| 875 | 2,809 |
<issue_start>username_0: So I have been searching, but couldn't exactly find a solution for the thing I want to do. Basically User input's a char like "asdasdasd" and I need to go thru each symbol to check if it's 'a', and need to stop the loop after it has reached the end of char. I got this far and it works, it output's the char symbols one by one, but in this case I can't stop the loop, I tried adding another char at the end and make it something specific like "." and use that to stop the loop but then I need to use char o[] which brakes the symbol by symbol thing going on there. Need help.. any input would be appreciated.
```
#include
using namespace std;
int main(){
char o;
cout<<"input: "; cin>>o;
while(o!= '\0'){
cout<> o;
}
return 0;
}
```<issue_comment>username_1: When I understand your question correct you will input a string like "ahobansodfb" and search in there after a specific char? If yes, this is a little example:
```
#include
using namespace std;
int main() {
string input;
char search;
int findPos = 0, countOfSearchedChars = 0;
cout << "input searched char: ";
cin >> search;
cout << "input string: ";
cin >> input;
while((findPos = input.find\_first\_of(search, findPos)) != string::npos){
cout << "Find searched char on pos: " << findPos << endl;
++findPos;
++countOfSearchedChars;
}
if(countOfSearchedChars == 0)
cout << "Char: " << search << " not found in: " << input << endl;
else
cout << "Char: " << search << " found: " << countOfSearchedChars << " time/s in string: " << input << endl;
}
```
Explanation for: `while((findPos = input.find_first_of(search, findPos)) != string::npos)`
`input.find_first_of(search, findPos)` find the first place where the searched char lies. When the char doesn't found it returns `string::npos` (18446744073709551615)
So we loop so long the return value is not string::npos: `!= string::npos`
**Edit to answer comment question:**
Possibilities to iterate through a string:
```
std::string str = "aabaaba";
for(char& c : str) {
if(c == 'a'){
//it's a
} else if(c == 'b') {
//it's b
}
}
std::string str = "abaaba;
for(std::string::iterator it = str.begin(); it != str.end(); ++it) {
if(*it == 'a'){
//it's a
} else if(*it == 'b') {
//it's b
}
}
```
[For every character in string](https://stackoverflow.com/questions/9438209/for-every-character-in-string)
Upvotes: 2 [selected_answer]<issue_comment>username_2: THANKS for all the answers!, you were big help, this code will do for me, going to go research what it does x.x
```
std::string str = "abaaba;
for(std::string::iterator it = str.begin(); it != str.end(); ++it) {
if(*it == 'a'){
//it's a
} else if(*it == 'b') {
//it's b
}
}
```
Upvotes: 0
|
2018/03/15
| 883 | 3,620 |
<issue_start>username_0: I am coming from PHP ecosystem, and now i want upgrade my skills to *Asp.Net Core 2.0*.
There a problem with sessions **since these will be destroyed on each build**, and that's is really annoyng during **development**.
Asp.net authentication system isn't destroyed at **builds/restart**, while sessions are.
There a way to make Sessions persistent like the Auth behavior?
My workaround is; Since i'm using asp.net Auth i could store a unique id and load the session (containing custom object) from the database. Then save it again on changes...
Note: *My application is multi-user so i need to referee the user ID from Session on each request to the database to select related data.*<issue_comment>username_1: The default session store is in-memory, mostly because every other type of store requires some type of configuration. When you have anything that's stored in-memory (session, cache, etc.) it's inherently process-bound, so when the process terminates, everything stored in-memory goes along with it. Rebuilding a running web app causes the process to be terminated and restarted, so there's your issue in a nutshell.
If you want the session to persist, then you need to use *a persistent store*, i.e. SQL Server, Redis, etc. The [ASP.NET Core Distributed Cache](https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed) (which is what ASP.NET Core uses for sessions) documentation covers how to to set all that up.
Upvotes: 0 <issue_comment>username_2: ASP.NET Sessions were never related to authentication. They use their own storage to store temporary data that is used during a singel user session.
In ASP.NET Core the Session middleware *always* [uses the service registered](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?tabs=aspnetcore2x#working-with-session-state) for IDistributedCache. The default implementation is a local in-memory cache :
```
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Adds a default in-memory implementation of IDistributedCache.
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
}
```
There are two persistent storage providers, [one for Redis](https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed#using-a-redis-distributed-cache) and one for [SQL Server](https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed#using-a-sql-server-distributed-cache). To use them simply replace the call to `AddDistributedMemoryCache()`, eg :
```
services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = @"Data Source=(localdb)\v11.0;Initial Catalog=DistCache;Integrated Security=True;";
options.SchemaName = "dbo";
options.TableName = "TestCache";
});
```
The linked doc page explains how to configure the providers.
All three providers can be found in the [ASP.NET\Caching](https://github.com/aspnet/Caching) repository. You can use them as a starting point to implement your own provider, eg to use MySQL, assuming there isn't one already available.
You can also configure ASP.NET Core to use the in-memory cache for general caching and SQL Server or Redis for distributed caching and session storage, eg :
```
services.AddMemoryCache();
services.AddDistributedRedisCache(options =>
{
options.Configuration = "localhost";
options.InstanceName = "SampleInstance";
});
```
Upvotes: 2
|
2018/03/15
| 1,083 | 3,570 |
<issue_start>username_0: I would like to have default string as values of an associative array if a user didn't fill in the field. For example "not inserted". If a user fills in the field, a variable should take the value the user put. So I wrote this code:
```
php
if (isset($_POST['submit'])){
if (isset($_POST['name'])){
$name =$_POST['name'];
} else {
$name = "not inserted";
}
if (isset($_POST['surname'])){
$surname =$_POST['surname'];
} else {
$surname = "not inserted";
}
if (isset($_POST['job'])) {
$job = $_POST['job'];
} else {
$job = "not inserted";
}
$data = array('name'=$name, 'surname'=>$surname, 'job'=>$job);
print_r($data);
}
?>
```
But if I don't fill in some field instead of "not inserted" string print\_r shows me the following result:
```
Array ( [name] => [surname] => [job] => )
```
Please, can someone tell me where did I go wrong? Thanks.<issue_comment>username_1: Blank inputs are still posted to a forms action page, even if they have no content. So if you were to `var_dump($_POST)` when leaving all your fields empty, you'd see something like this:
```
array (size=3)
'name' => string '' (length=0)
'surname' => string '' (length=0)
'job' => string '' (length=0)
...
```
They *are* set (i.e. they exist) but are empty. You can check if there is a value in there using the `empty()` function like this:
```
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = "not inserted";
}
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = "not inserted";
}
if (!empty($_POST['job'])) {
$name = $_POST['job'];
} else {
$name = "not inserted";
}
```
Read more about how `empty` works [in the documentation](http://php.net/manual/en/function.empty.php).
Upvotes: 2 [selected_answer]<issue_comment>username_2: This should work the way you want it to.
```
php
if ($_POST['submit']) {
$name = $_POST['name'];
if ($name == "") { $name = "not interested";}
$surname = $_POST['surname'];
if ($surname == "") { $surname = "not interested";}
$job = $_POST['job'];
if ($job == ""){$job = "not interested";}
$data = array('name'=$name, 'surname'=>$surname, 'job'=>$job);
print_r($data);
}
?>
```
Upvotes: 0 <issue_comment>username_3: In addition to the other answers and just to show another way to do this, you could use the ternary operator.Which kind of makes it neater, but that is a matter of taste.
```
php
$name = ! empty($_POST['name']) ? $_POST['name'] : "not inserted";
$surname = ! empty($_POST['surname']) ? $_POST['surname'] : "not inserted";
$job = ! empty($_POST['job']) ? $_POST['job'] : "not inserted";
$data = array('name' = $name, 'surname' => $surname, 'job' => $job);
?>
```
As an aside...You could refactor it a bit further to make a function you can reuse. Typically the function would go into another file that you would include with your files that use the forms... and on and on.
```
php
$name = read_post_value('name', 'not inserted');
$surname = read_post_value('surname', 'not inserted');
$job = read_post_value('job', 'not inserted');
$data = array('name' = $name, 'surname' => $surname, 'job' => $job);
var_dump($_POST); // Debug - Show $_POST contents
var_dump($data); // Debug - Show $data contents
/**
* Read a post entry.
* Assign a default value if it is empty or does not exist
*/
function read_post_value($name, $default_text = '') {
return ! empty($_POST[$name]) ? $_POST[$name] : $default_text;
}
?>
```
Upvotes: 0
|
2018/03/15
| 811 | 2,700 |
<issue_start>username_0: I try insert image on API 21 and that not working, but on API 26 everything working. **Where my mistake or what is missing here?**
```
public class MainActivity extends AppCompatActivity {
ImageView img1,img2,img3,img4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img1 = (ImageView) findViewById(R.id.img1);
img2 = (ImageView) findViewById(R.id.img2);
img3 = (ImageView) findViewById(R.id.img3);
img4 = (ImageView) findViewById(R.id.img4);
//setResource
// if(img1 != null) img1.setImageResource(R.drawable.china); //Вылетает
//setDrawable
if(img2 != null) `img2.setImageDrawable(Drawable.createFromPath("/res/drawable/tokyo1.png"));`
//setBitmap
if(img3 != null) img3.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.tokyo2));
//Picasso(local)
if(img4 != null) {
Picasso.get()
.load(R.drawable.china)
.into(img4);
}
//Picasso(URI)
if(img1 != null) {
Picasso.get()
.load("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTmG5K1tMdQ4W3G1WlZSfSWfL6jo8E9rS4NTHflXoT1CsF2Na_i")
.into(img1);
}
}
}
```
**XML:**
```
xml version="1.0" encoding="utf-8"?
```<issue_comment>username_1: The problem is with the `layout_width tag` in your xml file.
You are specifying the `layout_width size as 1 dp`. Make it large enough to display the image in the ImageView
**OR**
`use layout_width="wrap_content"` to display the image properly without any adjustments in the width of the image.
So, in conclusion just replace the line `android:layout_width="1dp"` with `android:layout_width="wrap_content"` or `android:layout_width="any size in dp"`
Hope this helps !!
Upvotes: 1 <issue_comment>username_2: Ok Although i have no idea what you are trying to achieve here . I am pointing out some steps . Use Unit `0dp` with `layout_weight` according to orientation.
So your layout should look like this.
```
```
And you can set image to `ImageView` in several way.
```
imageView.setImageResource(R.drawable.ic_launcher);
imageView.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_launcher));
Picasso.with(context).load(R.drawable.ic_launcher).into(imageView);
```
Use `android:scaleType` attribute in xml for if you set image with `src`. Also no need to check `if(img2 != null)`. Also read [what-is-the-difference-between-src-and-background-of-imageview](https://stackoverflow.com/questions/5454491/what-is-the-difference-between-src-and-background-of-imageview).
Upvotes: 0
|
2018/03/15
| 591 | 2,404 |
<issue_start>username_0: I have a component (properties.component.html) that renders real estate properties. When a user clicks on a specific property, I set a Behavior Subject equal to this property.
```
private property = new BehaviorSubject();
setProperty(property) {
this.property.next(property);
}
```
The component (property.component.html) renders just fine with the data returned from the observable in the service from the Behavior Subject.
```
this.propertyService.getProperty()
.subscribe((property) => {
this.currentProperty = property;
})
```
My issue: when the page reloads, the Behavior Subject is now 'empty?' with no data because the .next(property) gets called in properties.component.html on a click.
How can an application hold data on page refresh/reload?
Another poster mentions storing the property in localStorage as a stringified JSON. If that's the solution, then how can a user access this specific property by directly visiting <https://www.myapp.com/property/1234>?<issue_comment>username_1: Not the most elegant solution, but you can do something like this:
```
@Injectable()
export class PropertyService {
private property = new ReplaySubject(1);
constructor() {
let storedProp = localStorage.get('storedProp');
if (storedProp)
this.setProperty(JSON.parse(storedProp), false);
}
setProperty(property: Property, storeProp: boolean = false) {
if (storeProp)
localStorage.set('storedProp', JSON.stringify(property));
this.property.next(property);
}
getProperty() {
return this.property;
}
}
```
The subscriber would get the value whenever it subscribes to proptery through getProperty().subscribe().
Upvotes: 3 [selected_answer]<issue_comment>username_2: Like others have mentioned you can use localStorage to solve this. I did something similar to this by using the queryParams property of route.
`import { ActivatedRoute } from '@angular/router'`
```
routeSubscription!: Subscription
paramData: number //since desired property in url is a number (1234)`
constructor(private route: ActivatedRoute)
{
this.routeSubscription = this.route.queryParams.subscribe(params => {
this.paramData = params.data //params.data holds value 1234
});
```
}`
After storing the parameters in a variable I called a function with paramData as the argument to load the appropriate data from a post (or get) httpClient
Upvotes: 0
|
2018/03/15
| 700 | 1,963 |
<issue_start>username_0: This code is supposed to increment each value in a vector by 1:
```
fn main() {
let mut v = vec![2, 3, 1, 4, 2, 5];
let i = v.iter_mut();
for j in i {
*j += 1;
println!("{}", j);
}
println!("{:?}", &mut v);
}
```
It doesn't work because of the borrowing rules of Rust:
```none
error[E0499]: cannot borrow `v` as mutable more than once at a time
--> src/main.rs:8:27
|
3 | let i = v.iter_mut();
| - first mutable borrow occurs here
...
8 | println!("{:?}", &mut v);
| ^ second mutable borrow occurs here
9 | }
| - first borrow ends here
```
How can I accomplish this task?<issue_comment>username_1: Don't store the mutable iterator; use it directly in the loop instead:
```
fn main() {
let mut v = vec![2, 3, 1, 4, 2, 5];
for j in v.iter_mut() { // or for j in &mut v
*j += 1;
println!("{}", j);
}
println!("{:?}", &v); // note that I dropped mut here; it's not needed
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Your code will work as-is in a future version of Rust thanks to *non-lexical lifetimes*:
```
#![feature(nll)]
fn main() {
let mut v = vec![2, 3, 1, 4, 2, 5];
let i = v.iter_mut();
for j in i {
*j += 1;
println!("{}", j);
}
println!("{:?}", &mut v);
}
```
[playground](https://play.rust-lang.org/?gist=2645a333347ceeac807e1319a032d041&version=nightly)
Upvotes: 2 <issue_comment>username_3: You call also just use `map` and `collect` like,
```
>> let mut v = vec![5,1,4,2,3];
>> v.iter_mut().map(|x| *x += 1).collect::>();
>> v
[6, 2, 5, 3, 4]
```
Upvotes: 0 <issue_comment>username_4: In my opinion the simplest and most readable solution:
```
#![feature(nll)]
fn main() {
let mut v = vec![2, 3, 1, 4, 2, 5];
for i in 0..v.len() {
v[i] += 1;
println!("{}", j);
}
println!("{:?}", v);
}
```
Upvotes: 0
|
2018/03/15
| 705 | 2,098 |
<issue_start>username_0: I'm getting this error trying to deploy a card to a working blockchain on cloud, any idea? Thanks in advance. I'm using a mac, following the guide (Kubernetes installed/configured well, I think):
<https://ibm-blockchain.github.io/interacting/>
```
./create/create_composer-rest-server.sh --paid --business-network-card /Users/sm/jsblock/tutorial-network/PeerAdmin@fabric-network.card
Configured to setup a paid storage on ibm-cs
Preparing yaml file for create composer-rest-server
sed: 1: "s/%COMPOSER_CARD%//User ...": bad flag in substitute command: 'U'
Creating composer-rest-server pod
Running: kubectl create -f /Users/sm/jsblock/ibm-container-service/cs-offerings/scripts/../kube-configs/composer-rest-server.yaml
error: no objects passed to create
Composer rest server created successfully
```<issue_comment>username_1: Don't store the mutable iterator; use it directly in the loop instead:
```
fn main() {
let mut v = vec![2, 3, 1, 4, 2, 5];
for j in v.iter_mut() { // or for j in &mut v
*j += 1;
println!("{}", j);
}
println!("{:?}", &v); // note that I dropped mut here; it's not needed
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Your code will work as-is in a future version of Rust thanks to *non-lexical lifetimes*:
```
#![feature(nll)]
fn main() {
let mut v = vec![2, 3, 1, 4, 2, 5];
let i = v.iter_mut();
for j in i {
*j += 1;
println!("{}", j);
}
println!("{:?}", &mut v);
}
```
[playground](https://play.rust-lang.org/?gist=2645a333347ceeac807e1319a032d041&version=nightly)
Upvotes: 2 <issue_comment>username_3: You call also just use `map` and `collect` like,
```
>> let mut v = vec![5,1,4,2,3];
>> v.iter_mut().map(|x| *x += 1).collect::>();
>> v
[6, 2, 5, 3, 4]
```
Upvotes: 0 <issue_comment>username_4: In my opinion the simplest and most readable solution:
```
#![feature(nll)]
fn main() {
let mut v = vec![2, 3, 1, 4, 2, 5];
for i in 0..v.len() {
v[i] += 1;
println!("{}", j);
}
println!("{:?}", v);
}
```
Upvotes: 0
|
2018/03/15
| 1,472 | 5,424 |
<issue_start>username_0: `ARKit` 1.5 introduces image recognition. In the code you have to create a Set of the reference images like this:
```
let referenceImages = ARReferenceImage.referenceImages(inGroupNamed: "AR Resources", bundle: nil)
```
and then images contained in the Set can be recognised.
I wanted to know if it is possible to add images on the fly to this `AR Resources` folder. For example a user could take a picture and send it to a server, it is then recognised by the `ARKit`. Or a user could receive a set of images based on his location, etc.<issue_comment>username_1: You cannot amend the contents of the default folder at runtime, although you can create images on the fly.
[](https://i.stack.imgur.com/P245T.png)
As an example let's put an image into the `Assets Folder` (not the ARResources one), which in my case is called 'moonTarget'.
We could then create a function which we call in `viewDidLoad` etc:
```
/// Create ARReference Images From Somewhere Other Than The Default Folder
func loadDynamicImageReferences(){
//1. Get The Image From The Folder
guard let imageFromBundle = UIImage(named: "moonTarget"),
//2. Convert It To A CIImage
let imageToCIImage = CIImage(image: imageFromBundle),
//3. Then Convert The CIImage To A CGImage
let cgImage = convertCIImageToCGImage(inputImage: imageToCIImage)else { return }
//4. Create An ARReference Image (Remembering Physical Width Is In Metres)
let arImage = ARReferenceImage(cgImage, orientation: CGImagePropertyOrientation.up, physicalWidth: 0.2)
//5. Name The Image
arImage.name = "CGImage Test"
//5. Set The ARWorldTrackingConfiguration Detection Images
configuration.detectionImages = [arImage]
}
/// Converts A CIImage To A CGImage
///
/// - Parameter inputImage: CIImage
/// - Returns: CGImage
func convertCIImageToCGImage(inputImage: CIImage) -> CGImage? {
let context = CIContext(options: nil)
if let cgImage = context.createCGImage(inputImage, from: inputImage.extent) {
return cgImage
}
return nil
}
```
We can then test this in the `ARSCNViewDelegate`:
```
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
//1. If Out Target Image Has Been Detected Than Get The Corresponding Anchor
guard let currentImageAnchor = anchor as? ARImageAnchor else { return }
let x = currentImageAnchor.transform
print(x.columns.3.x, x.columns.3.y , x.columns.3.z)
//2. Get The Targets Name
let name = currentImageAnchor.referenceImage.name!
//3. Get The Targets Width & Height In Meters
let width = currentImageAnchor.referenceImage.physicalSize.width
let height = currentImageAnchor.referenceImage.physicalSize.height
print("""
Image Name = \(name)
Image Width = \(width)
Image Height = \(height)
""")
//4. Create A Plane Geometry To Cover The ARImageAnchor
let planeNode = SCNNode()
let planeGeometry = SCNPlane(width: width, height: height)
planeGeometry.firstMaterial?.diffuse.contents = UIColor.white
planeNode.opacity = 0.25
planeNode.geometry = planeGeometry
//5. Rotate The PlaneNode To Horizontal
planeNode.eulerAngles.x = -.pi/2
//The Node Is Centered In The Anchor (0,0,0)
node.addChildNode(planeNode)
//6. Create AN SCNBox
let boxNode = SCNNode()
let boxGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)
//7. Create A Different Colour For Each Face
let faceColours = [UIColor.red, UIColor.green, UIColor.blue, UIColor.cyan, UIColor.yellow, UIColor.gray]
var faceMaterials = [SCNMaterial]()
//8. Apply It To Each Face
for face in 0 ..< 5{
let material = SCNMaterial()
material.diffuse.contents = faceColours[face]
faceMaterials.append(material)
}
boxGeometry.materials = faceMaterials
boxNode.geometry = boxGeometry
//9. Set The Boxes Position To Be Placed On The Plane (node.x + box.height)
boxNode.position = SCNVector3(0 , 0.05, 0)
//10. Add The Box To The Node
node.addChildNode(boxNode)
}
```
As you can see the same could also be applied from a live feed as well.
Hope this helps...
As @Karlis said you could also look at using `OnDemandResouces` and then converting them to desired specs of an `ARReferenceImage`.
**Update:** For anyone looking to see an example of creating dynamic reference images from a Server please take a look at the following project I have created: [Dynamic Reference Images Sample Code](https://github.com/username_1/ARKitDynamicReferenceImages)
Upvotes: 6 [selected_answer]<issue_comment>username_2: ```
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let pathToObject = documentDirectory + "/reference.jpg"
let imageUrl = URL(fileURLWithPath: pathToObject)
let imageData: Data = try! Data(contentsOf: imageUrl)
let image = UIImage(data: imageData, scale: UIScreen.main.scale)
let cgImage = image!.cgImage
let referenceImages = ARReferenceImage.init(cgImage!, orientation: .up, physicalWidth: 0.595)
referenceImages.name = "Reference Image"
let configuration = ARImageTrackingConfiguration()
configuration.trackingImages = [referenceImages]
session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
```
Upvotes: 3
|
2018/03/15
| 1,506 | 5,502 |
<issue_start>username_0: I have a HTML `div` that are assigned with different `id` attribute using `EJS`. It looks like this:
**HTML**
```
```
This `div` is generated several times in the HTML depending on how many posts a particular user has. Each of the `div` has a different `posts._id`.
I would like that when a user click on a `div`, JQuery will do something with that particular `div` only. Other `div` should not be changed. How can I change the JQuery selector based on the `id` attribute of a particular `div`?
**JQuery**
```
$("//How to change this part based on the `div`'s id?").click(function(){
//action taken
});
```<issue_comment>username_1: You cannot amend the contents of the default folder at runtime, although you can create images on the fly.
[](https://i.stack.imgur.com/P245T.png)
As an example let's put an image into the `Assets Folder` (not the ARResources one), which in my case is called 'moonTarget'.
We could then create a function which we call in `viewDidLoad` etc:
```
/// Create ARReference Images From Somewhere Other Than The Default Folder
func loadDynamicImageReferences(){
//1. Get The Image From The Folder
guard let imageFromBundle = UIImage(named: "moonTarget"),
//2. Convert It To A CIImage
let imageToCIImage = CIImage(image: imageFromBundle),
//3. Then Convert The CIImage To A CGImage
let cgImage = convertCIImageToCGImage(inputImage: imageToCIImage)else { return }
//4. Create An ARReference Image (Remembering Physical Width Is In Metres)
let arImage = ARReferenceImage(cgImage, orientation: CGImagePropertyOrientation.up, physicalWidth: 0.2)
//5. Name The Image
arImage.name = "CGImage Test"
//5. Set The ARWorldTrackingConfiguration Detection Images
configuration.detectionImages = [arImage]
}
/// Converts A CIImage To A CGImage
///
/// - Parameter inputImage: CIImage
/// - Returns: CGImage
func convertCIImageToCGImage(inputImage: CIImage) -> CGImage? {
let context = CIContext(options: nil)
if let cgImage = context.createCGImage(inputImage, from: inputImage.extent) {
return cgImage
}
return nil
}
```
We can then test this in the `ARSCNViewDelegate`:
```
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
//1. If Out Target Image Has Been Detected Than Get The Corresponding Anchor
guard let currentImageAnchor = anchor as? ARImageAnchor else { return }
let x = currentImageAnchor.transform
print(x.columns.3.x, x.columns.3.y , x.columns.3.z)
//2. Get The Targets Name
let name = currentImageAnchor.referenceImage.name!
//3. Get The Targets Width & Height In Meters
let width = currentImageAnchor.referenceImage.physicalSize.width
let height = currentImageAnchor.referenceImage.physicalSize.height
print("""
Image Name = \(name)
Image Width = \(width)
Image Height = \(height)
""")
//4. Create A Plane Geometry To Cover The ARImageAnchor
let planeNode = SCNNode()
let planeGeometry = SCNPlane(width: width, height: height)
planeGeometry.firstMaterial?.diffuse.contents = UIColor.white
planeNode.opacity = 0.25
planeNode.geometry = planeGeometry
//5. Rotate The PlaneNode To Horizontal
planeNode.eulerAngles.x = -.pi/2
//The Node Is Centered In The Anchor (0,0,0)
node.addChildNode(planeNode)
//6. Create AN SCNBox
let boxNode = SCNNode()
let boxGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)
//7. Create A Different Colour For Each Face
let faceColours = [UIColor.red, UIColor.green, UIColor.blue, UIColor.cyan, UIColor.yellow, UIColor.gray]
var faceMaterials = [SCNMaterial]()
//8. Apply It To Each Face
for face in 0 ..< 5{
let material = SCNMaterial()
material.diffuse.contents = faceColours[face]
faceMaterials.append(material)
}
boxGeometry.materials = faceMaterials
boxNode.geometry = boxGeometry
//9. Set The Boxes Position To Be Placed On The Plane (node.x + box.height)
boxNode.position = SCNVector3(0 , 0.05, 0)
//10. Add The Box To The Node
node.addChildNode(boxNode)
}
```
As you can see the same could also be applied from a live feed as well.
Hope this helps...
As @Karlis said you could also look at using `OnDemandResouces` and then converting them to desired specs of an `ARReferenceImage`.
**Update:** For anyone looking to see an example of creating dynamic reference images from a Server please take a look at the following project I have created: [Dynamic Reference Images Sample Code](https://github.com/username_1/ARKitDynamicReferenceImages)
Upvotes: 6 [selected_answer]<issue_comment>username_2: ```
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let pathToObject = documentDirectory + "/reference.jpg"
let imageUrl = URL(fileURLWithPath: pathToObject)
let imageData: Data = try! Data(contentsOf: imageUrl)
let image = UIImage(data: imageData, scale: UIScreen.main.scale)
let cgImage = image!.cgImage
let referenceImages = ARReferenceImage.init(cgImage!, orientation: .up, physicalWidth: 0.595)
referenceImages.name = "Reference Image"
let configuration = ARImageTrackingConfiguration()
configuration.trackingImages = [referenceImages]
session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
```
Upvotes: 3
|
2018/03/15
| 524 | 2,013 |
<issue_start>username_0: I'm trying to achieve the following:
User will submit a form and be redirected to the thank you page. In the thank you page load, user's "marks-list" (`MarksList.cshtml`) has to be converted to pdf and then emailed (all happening in background).
I have tried `Rotativa` following this [article](http://www.intstrings.com/ramivemula/articles/export-asp-net-mvc-view-to-pdf-in-3-quick-steps/). But it explains how to load the other view as PDF. In my case, I don't need to view it. Just convert it run time, so that it can be emailed as an attachment.
Is this possible with Rotativa. If not, are there any alternatives.<issue_comment>username_1: I have never use *Rotativa* but I used [SelectPdf](https://selectpdf.com/community-edition/) and I highly recommend to you (Community Edition).
It's really easy to use and configurable.
That's the sample code from their site. you can also find a lot of demo about it.
```
// instantiate the html to pdf converter
HtmlToPdf converter = new HtmlToPdf();
// convert the url to pdf
PdfDocument doc = converter.ConvertUrl(url);
// save pdf document
doc.Save(file);
// close pdf document
doc.Close();
```
This is also a great [example](http://www.intstrings.com/ramivemula/articles/convert-an-asp-net-mvc-webpage-html-to-pdf/) for the beginning.
Upvotes: 1 <issue_comment>username_2: you can use bytescout to simplify your work :
```
using (HtmlToPdfConverter converter = new HtmlToPdfConverter())
{
converter.PageSize = PaperKind.A4;
converter.Orientation = PaperOrientation.Portrait;
converter.Footer = "FOOTER TEXT
";
converter.ConvertHtmlToPdf("sample.html", "result.pdf");
// You can also pass a link instead of the input file:
//converter.ConvertHtmlToPdf("http://google.com", "result.pdf");
}
// Open result file in default PDF viewer
Process.Start("result.pdf");
```
Upvotes: 0
|
2018/03/15
| 764 | 2,450 |
<issue_start>username_0: I have some trouble achieving my requirement. I have a table called accounts\_invoice and data as mentioned below.
DB Table
```
AC_NO VARCHAR2(20 BYTE)
INV_NO VARCHAR2(20 BYTE)
CC VARCHAR2(20 BYTE)
FT VARCHAR2(20 BYTE)
AC_NO INV_NO CC FT
-----------------------------
1 A PTN INVOICE
1 A PTN BDE
2 B ABC INVOICE
2 B PTN INVOICE
2 B PTN BDE
```
I have written a code as below, but my output seems not right as per my requirement.
```
SELECT
ac_no,
CASE WHEN FT like '%INVOICE%' THEN 'AVAILABLE' else 'NOTAVAILABLE'
END AS INVOICE,
CASE WHEN FT like '%BDE%' THEN 'AVAILABLE' else 'NOTAVAILABLE' END AS BDE
FROM Account_info
where CC='PTN';
```
Output
```
1 A Available Notavailable
1 A Notavailable Available
2 B Available Notavailable
2 B Notavailable Available
```
I'm Expecting the Output as below:
But Output should be
```
AC_NO INVOICE BDE
----------------------------------
1 AVAILABLE AVAILABLE
2 AVAILABLE AVAILABLE
```
Please help me, how can I achieve the above output.<issue_comment>username_1: A slightly modified pivot query should work:
```
SELECT
AC_NO,
CASE WHEN COUNT(CASE WHEN FT = 'INVOICE' THEN 1 END) > 0
THEN 'AVAILABLE' ELSE 'NOTAVAILABLE' END AS INVOICE,
CASE WHEN COUNT(CASE WHEN FT = 'BDE' THEN 1 END) > 0
THEN 'AVAILABLE' ELSE 'NOTAVAILABLE' END AS BDE
FROM yourTable
GROUP BY AC_NO
```
[](https://i.stack.imgur.com/Vgna9.png)
In this case, we wrap the counts in a second `CASE` expression to check for the presence/absence of invoices and bde.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is another way of doing it, not sure which will have better performance. Also, FT='INVOICE' will definitely works better, but I am not sure if you data really needs FT like '%INVOICE%'. I have just keep it that way below.
```
SELECT
a1.AC_NO,
NVL((select 'AVAILABLE' from ACCOUNT_INFO a
where a.AC_NO=a1.AC_NO and a.FT like '%INVOICE%'
and rownum=1
),'NOTAVAILABLE') as INVOICE,
NVL((select 'BDE' from ACCOUNT_INFO a
where a.AC_NO=a1.AC_NO and a.FT like '%BDE%'
and rownum=1
),'NOTAVAILABLE') as BDE
FROM (
SELECT DISTINCT AC_NO
FROM ACCOUNT_INFO
WHERE CC='PTN'
) a1
```
Upvotes: 0
|
2018/03/15
| 636 | 2,198 |
<issue_start>username_0: I try to dynamic create variables in class to store values and use it in ngModel and other placese.
I know, that I can assign value to variables in ngOnInit() like this
```
export class Component implements OnInit{
name: string;
ngOnInit(){
this.name = '<NAME>';
}
}
```
But I have some problem - I get my fields from server API and don't know what and how many items I get. I can only parsing server response and assign value to new variables after get it.
I can't do it like this (TS2540: Cannot assign to 'name' because it is a constant or a read-only property.)
```
export class Component implements OnInit{
ngOnInit(){
name = '<NAME>';
}
}
```
How can I assign new fields to my class in ngOnInit() or maybe in other place? (I think I can do it in constructor, but documentation say i shouldn't use it with Observable call to API and other difficult things)<issue_comment>username_1: A slightly modified pivot query should work:
```
SELECT
AC_NO,
CASE WHEN COUNT(CASE WHEN FT = 'INVOICE' THEN 1 END) > 0
THEN 'AVAILABLE' ELSE 'NOTAVAILABLE' END AS INVOICE,
CASE WHEN COUNT(CASE WHEN FT = 'BDE' THEN 1 END) > 0
THEN 'AVAILABLE' ELSE 'NOTAVAILABLE' END AS BDE
FROM yourTable
GROUP BY AC_NO
```
[](https://i.stack.imgur.com/Vgna9.png)
In this case, we wrap the counts in a second `CASE` expression to check for the presence/absence of invoices and bde.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is another way of doing it, not sure which will have better performance. Also, FT='INVOICE' will definitely works better, but I am not sure if you data really needs FT like '%INVOICE%'. I have just keep it that way below.
```
SELECT
a1.AC_NO,
NVL((select 'AVAILABLE' from ACCOUNT_INFO a
where a.AC_NO=a1.AC_NO and a.FT like '%INVOICE%'
and rownum=1
),'NOTAVAILABLE') as INVOICE,
NVL((select 'BDE' from ACCOUNT_INFO a
where a.AC_NO=a1.AC_NO and a.FT like '%BDE%'
and rownum=1
),'NOTAVAILABLE') as BDE
FROM (
SELECT DISTINCT AC_NO
FROM ACCOUNT_INFO
WHERE CC='PTN'
) a1
```
Upvotes: 0
|
2018/03/15
| 1,370 | 3,633 |
<issue_start>username_0: I would like to simulate data for a logistic regression where I can specify its explained variance beforehand. Have a look at the code below. I simulate four independent variables and specify that each logit coefficient should be of size log(2)=0.69. This works nicely, the explained variance (I report Cox & Snell's r2) is 0.34.
However, I need to specify the regression coefficients in such a way that a pre-specified r2 will result from the regression. So if I would like to produce an r2 of let's say exactly 0.1. How do the coefficients need to be specified? I am kind of struggling with this..
```
# Create independent variables
sigma.1 <- matrix(c(1,0.25,0.25,0.25,
0.25,1,0.25,0.25,
0.25,0.25,1,0.25,
0.25,0.25,0.25,1),nrow=4,ncol=4)
mu.1 <- rep(0,4)
n.obs <- 500000
library(MASS)
sample1 <- as.data.frame(mvrnorm(n = n.obs, mu.1, sigma.1, empirical=FALSE))
# Create latent continuous response variable
sample1$ystar <- 0 + log(2)*sample1$V1 + log(2)*sample1$V2 + log(2)*sample1$V3 + log(2)*sample1$V4
# Construct binary response variable
sample1$prob <- exp(sample1$ystar) / (1 + exp(sample1$ystar))
sample1$y <- rbinom(n.obs,size=1,prob=sample1$prob)
# Logistic regression
logreg <- glm(y ~ V1 + V2 + V3 + V4, data=sample1, family=binomial)
summary(logreg)
```
The output is:
```
Call:
glm(formula = y ~ V1 + V2 + V3 + V4, family = binomial, data = sample1)
Deviance Residuals:
Min 1Q Median 3Q Max
-3.7536 -0.7795 -0.0755 0.7813 3.3382
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -0.002098 0.003544 -0.592 0.554
V1 0.691034 0.004089 169.014 <2e-16 ***
V2 0.694052 0.004088 169.776 <2e-16 ***
V3 0.693222 0.004079 169.940 <2e-16 ***
V4 0.699091 0.004081 171.310 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 693146 on 499999 degrees of freedom
Residual deviance: 482506 on 499995 degrees of freedom
AIC: 482516
Number of Fisher Scoring iterations: 5
```
And Cox and Snell's r2 gives:
```
library(pscl)
pR2(logreg)["r2ML"]
> pR2(logreg)["r2ML"]
r2ML
0.3436523
```<issue_comment>username_1: R-squared (and its variations) is a random variable, as it depends on your simulated data. If you simulate data with the exact same parameters multiple times, you'll most likely get different values for R-squared each time. Therefore, you cannot produce a simulation where the R-squared will be exactly 0.1 just by controlling the parameters.
On the other hand, since it's a random variable, you could potentially simulate your data from a conditional distribution (conditioning on a fixed value of R-squared), but you would need to find out what these distributions look like (math might get really ugly here, [cross validated](https://stats.stackexchange.com/) is more appropriate for this part).
Upvotes: 1 <issue_comment>username_2: If you add a random error term to the ystar variable making ystat.r and then work with that, you can tweek the standard deviation until it meets you specifications.
```
sample1$ystar.r <- sample1$ystar+rnorm(n.obs, 0, 3.8) # tried a few values
sample1$prob <- exp(sample1$ystar.r) / (1 + exp(sample1$ystar.r))
sample1$y <- rbinom(n.obs,size=1,prob=sample1$prob)
logreg <- glm(y ~ V1 + V2 + V3 + V4, data=sample1, family=binomial)
summary(logreg) # the estimates "shrink"
pR2(logreg)["r2ML"]
#-------
r2ML
0.1014792
```
Upvotes: 2
|
2018/03/15
| 354 | 1,289 |
<issue_start>username_0: I have an input field which I add to html using ajax here:
```
function WritePrices(categories) {
var strResult = "from: ";
strResult += "from: ";
$("#price-range").html(strResult);
}
```
And then I want to catch a moment when this input is changed by the user. That's why in the script I also have change method
```
jQuery("input#minCost").change(function () {
//...
});
```
But this method doesn't "hear" any changes to my input field. It hears changes only when my input field is created in html(not during in the script). what should I change to make jQuery seen changes to my input field?<issue_comment>username_1: You need to use `document` change pattern
```
$(document).on('change','input#minCost',function(){
...
});
```
Upvotes: 1 <issue_comment>username_2: You must assign event just after the creation. Please find working snippet below:
```js
function WritePrices(categories) {
var strResult = "from: ";
strResult += "from: ";
$("#price-range").html(strResult);
jQuery("input#minCost").change(function () {
alert("working");
});
}
var categories = {};
categories.MinPrice = 0.0;
categories.MaxPrice= 10;
WritePrices(categories);
```
```html
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 509 | 1,793 |
<issue_start>username_0: I've got a page im trying to develop which will take user input and then add it to an array and then take that array and make a select and option list out of it as such.
```
var option\_list = [];
// for loop at thats option\_list to select select tag
for (var i = 0; i < option\_list.length; i++){
var opt = option\_list[i];
var option = document.createElement("option");
var select = document.getElementById("select");
option.setAttribute("id", opt); //Adding ID to the option list
option.setAttribute("class", "intersect-option"); // adds classes to option
option.value(opt); // adds value to option list
select.appendChild(option); // Adds option to the list.
}
function add\_option(name){
var name = document.getElementById("name").value;
name.push(option\_list());
}
```
The issue i am having is that it says when i try and input the information i get back-
>
> Uncaught TypeError: option\_list is not a function
>
>
> at add\_option (selectTest.html:19)
>
>
> at HTMLInputElement.onclick (selectTest.html:25)
>
>
>
I am unsure what i am doing wrong and any help would be greatly appreciated.<issue_comment>username_1: You need to use `document` change pattern
```
$(document).on('change','input#minCost',function(){
...
});
```
Upvotes: 1 <issue_comment>username_2: You must assign event just after the creation. Please find working snippet below:
```js
function WritePrices(categories) {
var strResult = "from: ";
strResult += "from: ";
$("#price-range").html(strResult);
jQuery("input#minCost").change(function () {
alert("working");
});
}
var categories = {};
categories.MinPrice = 0.0;
categories.MaxPrice= 10;
WritePrices(categories);
```
```html
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 427 | 1,342 |
<issue_start>username_0: * Converted large text file to list of strings (each row = one element in list) ['...','...','...']
* sample\_data = ['2017-May-15 13:56:49.578 Event Dispense Sc 06mm Beschichtungsbreite ist: 5.99 mm', '2017-May-15 14:12:11.062 Event Runtime SC 09mm neuer Druck: 27.560PSI']
* Trying to extract dates from each list element (each row contains one date with standardized format)
my code:
```
dparser.parse(sample_data[0],fuzzy=True))
```
returns the desired date.
However, **when trying to iterate** through the list as shown below
```
for elements in sample_data:
dparser.parse(elements,fuzzy=True)
```
I get an error message: `ValueError: Unknown string format`<issue_comment>username_1: You need to use `document` change pattern
```
$(document).on('change','input#minCost',function(){
...
});
```
Upvotes: 1 <issue_comment>username_2: You must assign event just after the creation. Please find working snippet below:
```js
function WritePrices(categories) {
var strResult = "from: ";
strResult += "from: ";
$("#price-range").html(strResult);
jQuery("input#minCost").change(function () {
alert("working");
});
}
var categories = {};
categories.MinPrice = 0.0;
categories.MaxPrice= 10;
WritePrices(categories);
```
```html
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 647 | 2,235 |
<issue_start>username_0: I am kinda new to react and to the webitself.
this is my render function
```
render() {
const {repositories} = this.props
return (
{
repositories.map((repo, index) => {
console.log(repo.name)
return
})
}
)
}
```
The repositories is changing the way I want, but for some reason the its not get re-rendered. I passing the repositiores property from the parent.
The first time I render it (click to the search button, get a response from the server, and set the repo array), its working fine. But at the 2nd search, when there is something in the array, its not working properly, and not re-render.
UPDATE:
The parent's render / onClick
```
render() {
const {repositories} = this.state
return (
//
//
//
);
}
onClick = (event) => {
const {searchTerm} = this.state
let endpoint = 'https://api.github.com/search/repositories?sort=starsℴ=desc&q=' + searchTerm;
fetch(endpoint)
.then(blob => blob.json())
.then(response => {
if(response.items)
this.setState({ repositories: response.items });
})
}
```
UP-UPDATE:
Search Comp:
```
constructor({onClick, onChange}) {
super()
this.onClick = onClick
this.onChange = onChange
this.state = {
imageHover: false
}}
render() {
return (
)this.setState({imageHover: true})}
onMouseOut={()=>this.setState({imageHover: false})}
onClick={this.onClick}/>
)}
```
[first responde](https://i.stack.imgur.com/NYbLy.png)
[second responde](https://i.stack.imgur.com/ta8iA.png)<issue_comment>username_1: You need to use `document` change pattern
```
$(document).on('change','input#minCost',function(){
...
});
```
Upvotes: 1 <issue_comment>username_2: You must assign event just after the creation. Please find working snippet below:
```js
function WritePrices(categories) {
var strResult = "from: ";
strResult += "from: ";
$("#price-range").html(strResult);
jQuery("input#minCost").change(function () {
alert("working");
});
}
var categories = {};
categories.MinPrice = 0.0;
categories.MaxPrice= 10;
WritePrices(categories);
```
```html
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 417 | 1,594 |
<issue_start>username_0: I have to launch several times an executable with different argument each time and I need to get back the process ID for each of them.
I have the used command line and I need the process ID of the process started with this command.
Following some others question here I have found this:
```
Get-CimInstance Win32_Process -Filter "name = 'evolution4.exe'" | select CommandLine
```
Which can give me the command Line use for the process started, but I now need to do a filter on the CommandLine and not on the name and Select the PID.
I tried replacing "name" by "commandLine" or "CommandLine" without result and I don't even know if it's the proper way to do. What should I put in my filter ? Does this command can be filtered by command line instead of name or pid ?
---
Edit: It seems that my problem is more about giving a path in the string of the filter than the argument which seems to be "commandLine" as I thouht.<issue_comment>username_1: You need to use `document` change pattern
```
$(document).on('change','input#minCost',function(){
...
});
```
Upvotes: 1 <issue_comment>username_2: You must assign event just after the creation. Please find working snippet below:
```js
function WritePrices(categories) {
var strResult = "from: ";
strResult += "from: ";
$("#price-range").html(strResult);
jQuery("input#minCost").change(function () {
alert("working");
});
}
var categories = {};
categories.MinPrice = 0.0;
categories.MaxPrice= 10;
WritePrices(categories);
```
```html
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 947 | 3,718 |
<issue_start>username_0: Yesterday I managed to have my API working on my local computer, however today (same code) on another computer, it's not working, I am getting this error on the console:
>
> Failed to load <http://localhost:52056/api/task>: The
> 'Access-Control-Allow-Origin' header has a value 'null' that is not
> equal to the supplied origin. Origin 'null' is therefore not allowed
> access.
>
>
>
**Here is the http request and response on Chrome:**
[](https://i.stack.imgur.com/lRb4d.png)
(I don't see errors in IE/Firefox)
**Here is my startup class (using .net core 2)**
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TodoApi;
namespace TestCors
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton();
services.AddCors();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseMvc();
}
}
}
```
What is wrong here?
The code is the same from yesterday, however I was running on Windows 10 and this machine has Windows 7.
Any thoughts?
Thanks<issue_comment>username_1: Try removing
```
.AllowCredentials()
```
CORS doesn't allow you to have .`AllowCredentials()` AND `.AllowAnyOrigin()` for the same policy. I don't why it worked on a different machine.
This is from [ASP.NET](https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api#passing-credentials-in-cross-origin-requests) page
>
> The CORS spec also states that setting origins to "\*" is invalid if
> SupportsCredentials is true.
>
>
>
Upvotes: 3 <issue_comment>username_2: The problem is your are opening html page which makes this request by just double clicking on it, without using a server. So url in your browser is "file:///...". That means there is no origin, and as you see on screenshot from your question - CORS request has "Origin: null" header. Different browsers handle this siutation differently. Chrome restricts cross-origin requests from such origin, even if response allows it (via returning "null" as "Access-Control-Allow-Origin").
So to fix - use proper server (local one), or use another browser for development. Also some people claim that starting chrome like this
```
chrome.exe --allow-file-access-from-files
```
Should also "fix" this, though I didn't try myself.
Update: I was under impression that even with `Access-Control-Allow-Origin: *` chrome will not allow it, but your comment on other answer seems to claim otherwise (by removing `AllowCredentials()` you made response to use "\*" as allowed origin instead of origin provided in request). If so - that's another way to fix it (not sure, maybe it behaves differently in different chrome versions though).
Upvotes: 2
|
2018/03/15
| 929 | 3,275 |
<issue_start>username_0: I have the following table in Mysql
```
Name Age Group
```
---
```
abel 7 A
joe 6 A
Rick 7 A
Diana 5 B
Billy 6 B
Pat 5 B
```
I want to randomize the rows, but they should still remain grouped by the Group column.
For exmaple i want my result to look something like this.
```
Name Age Group
```
---
```
joe 6 A
abel 7 A
Rick 7 A
Billy 6 B
Pat 5 B
Diana 5 B
```
What query should i use to get this result? The entire table should be randomised and then grouped by "Group" column.<issue_comment>username_1: Do the random first then sort by column group.
```
select Name, Age, Group
from (
select *
FROM yourtable
order by RAND()
) t
order by Group
```
Upvotes: 0 <issue_comment>username_2: What you describe in your question as GROUPing is more correctly described as sorting. This is a particular issue when talking about SQL databases where "GROUP" means something quite different and determines the scope of aggregation operations.
Indeed "group" is a reserved word in SQL, so although mysql and some other SQL databases can work around this, it is a poor choice as an attribute name.
```
SELECT *
FROM yourtable
ORDER BY `group`
```
Using random values also has a lot of semantic confusion. A truly random number would have a different value every time it is retrieved - which would make any sorting impossible (and databases do a *lot* of sorting which is normally invisible to the user). As long as the implementation uses a finite time algorithm such as quicksort that shouldn't be a problem - but a bubble sort would never finish, and a merge sort could get very confused.
There are also *degrees* of randomness. There are different algorithms for generating random numbers. For encryption it's critical than the random numbers be evenly distributed and completely unpredictable - often these will use hardware events (sometimes even dedicated hardware) but I don't expect you would need that. But do you want the ordering to be repeatable across invocations?
```
SELECT *
FROM yourtable
ORDER BY `group`, RAND()
```
...will give different results each time.
OTOH
```
SELECT
FROM yourtable
ORDER BY `group`, MD5(CONCAT(age, name, `group`))
```
...would give the results always sorted in the same order. While
```
SELECT
FROM yourtable
ORDER BY `group`, MD5(CONCAT(DATE(), age, name, `group`))
```
...will give different results on different days.
Upvotes: 2 <issue_comment>username_3: ```
DROP TABLE my_table;
CREATE TABLE my_table
(name VARCHAR(12) NOT NULL
,age INT NOT NULL
,my_group CHAR(1) NOT NULL
);
INSERT INTO my_table VALUES
('Abel',7,'A'),
('Joe',6,'A'),
('Rick',7,'A'),
('Diana',5,'B'),
('Billy',6,'B'),
('Pat',5,'B');
SELECT * FROM my_table ORDER BY my_group,RAND();
+-------+-----+----------+
| name | age | my_group |
+-------+-----+----------+
| Joe | 6 | A |
| Abel | 7 | A |
| Rick | 7 | A |
| Pat | 5 | B |
| Diana | 5 | B |
| Billy | 6 | B |
+-------+-----+----------+
```
Upvotes: 1 [selected_answer]<issue_comment>username_4: Try this:
```
SELECT * FROM table order by Group,rand()
```
Upvotes: 0
|
2018/03/15
| 776 | 2,786 |
<issue_start>username_0: I'm trying to read and write a file from a path (ex: "/Desktop/folder"). If this can't be done, then from Documents (ex: "/Documents/folder"). I saw and tried several examples, but the problem is that the file is located in a location such:
>
> file:///Users/name/Library/Developer/CoreSimulator/Devices/AE6A47DE-D6D0-49AE-B39F-25C7A2335DC8/data/Containers/Data/Application/09F890C1-081F-46E7-88BC-F8453BAFC1CB/Documents/Test.txt"
> 0x00006000000af780
>
>
>
Even if i have the "Test.txt" in Documents and even in project.
Here's the code which reads and writes a file at the above location:
```
let file = "Test.txt" //this is the file. we will write to and read from it
let text = "some text" //just a text
var text2 = ""
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
//writing
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */print(error)}
//reading
do {
text2 = try String(contentsOf: fileURL, encoding: .utf8)
}
catch {/* error handling here */ print(error)}
}
```
Is it possible to read and write file from path i need (ex: "Documents/Folder")?<issue_comment>username_1: So, like you're doing now, take the documents dir, and append the path you need:
```
let file = "Test.txt" //this is the file. we will write to and read from it
guard let dir = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask).first { else return }
let subDir = dir.appendingPathComponent("Folder", isDirectory: true)
let fileURL = subDir.appendingPathComponent(file)
```
Note that trying to write to that file URL will fail if the sub-folder "Folder" doesn't already exist. You'd have to use one of the file manager createDirectory calls to create the "Folder" directory if it doesn't exist.
Upvotes: 1 <issue_comment>username_2: I find the solution:
```
let file = "Test.txt" //this is the file. we will write to and read from it
let text = "some text" //just a text
var text2 = ""
let fileURL = URL(fileURLWithPath: "/Users/name/Documents/Folder/Test.txt")
//writing
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */print(error)}
//reading
do {
text2 = try String(contentsOf: fileURL, encoding: .utf8)
var s = ""
}
catch {/* error handling here */ print(error)}
}
```
Upvotes: 0
|
2018/03/15
| 1,917 | 6,757 |
<issue_start>username_0: I'm working with django, during inserting data into tables the error is generates as given below...
Error:
```
int() argument must be a string, a bytes-like object or a number, not 'Tbl_rule_category', How can we solve such error?
```
view.py
```
dataToRuleCtgry = Tbl_rule_category(category=category, created_by="XYZ",created_date=datetime.date.today())
dataToRuleCtgry.save()
dataToRule = Tbl_rule(rule_name=rule_name, closure=closure,category_id=Tbl_rule_category.objects.latest('category_id'), created_by="XYZ",created_date=datetime.date.today(), updated_by="XYZ", updated_date=datetime.date.today(), rule_type=rule_type, fk_tbl_rule_tbl_rule_category_id=Tbl_rule_category.objects.latest('category_id'))
dataToRule.save()
```
models.py
```
class Tbl_rule_category(models.Model):
category_id = models.AutoField(primary_key=True)
category = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
def __str__(self):
pass # return self.category, self.created_by
class Tbl_rule(models.Model):
rule_id = models.AutoField(primary_key=True)
rule_name = models.CharField(max_length=50)
closure = models.CharField(max_length=50)
category_id = models.IntegerField()
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
updated_by = models.CharField(max_length=50)
updated_date = models.DateField(auto_now=True)
rule_type = models.CharField(max_length=50)
fk_tbl_rule_tbl_rule_category_id = models.ForeignKey(Tbl_rule_category,on_delete=models.CASCADE, related_name='fk_tbl_rule_tbl_rule_category_id_r')
def __str__(self):
return self.rule_name, self.closure, self.created_by, self.updated_by, self.rule_type
```<issue_comment>username_1: The error is occurring because the following is trying to add an object into an integer field: `category_id=Tbl_rule_category.objects.latest('category_id')`
You could just add: `category_id=dataToRuleCtgry.get('category_id')` or `category_id=dataToRuleCtgry.category_id` which will solve the error.
You also don't need to add: `created_date=datetime.date.today()` because your model defines auto\_now=true.
As mentioned you should also amend the `def __str__(self):` to return a string.
[https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model.**str**](https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model.__str__)
Alternatively
-------------
You could just add the object link directly to your foreign key for the category model.`fk_tbl_rule_tbl_rule_category_id=dataToRuleCtgry`. You would no longer need the integer field category\_id.
It would be better practice to use the model field name category\_id instead of fk\_tbl\_rule\_tbl\_rule\_category\_id. This would mean deleting category\_id and then rename fk\_tbl\_rule\_tbl\_rule\_category\_id to category\_id.
Upvotes: 2 <issue_comment>username_2: In Django, the ORM takes care of the basic database details for you; which means in your code you really don't have to worry about individual row ids for maintaining foreign key relationships.
In fact, Django automatically assigns primary keys to all your objects so you should concentrate on fields that are relevant to your application.
You also don't have to worry about naming fields in the database, again Django will take care of that for you - you should create objects that have fields that are meaningful to *users* (that includes you as a programmer of the system) and not designed for databases.
Each Django model class represents a object in your system. So you should name the classes as you would name the objects. `User` and not `tbl_user`. The best practice is to use *singular names*. Django already knows how to create plural names, so if you create a model class `User`, django will automatically display `Users` wherever it makes sense. You can, of course, customize this behavior.
Here is how you should create your models (*we will define `__str__` later*):
```
class RuleCategory(models.Model):
name = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
class Rule(models.Model):
name = models.CharField(max_length=50)
closure = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
updated_by = models.CharField(max_length=50)
updated_date = models.DateField(auto_now=True)
rule_type = models.CharField(max_length=50)
category = models.ForeignKey(RuleCategory,on_delete=models.CASCADE)
```
Django will automatically create any primary or foreign key fields, and any intermediary tables required to manage the relationship between the two models.
Now, to add some records:
```
new_category = RuleCategory(name='My Category', created_by='XYZ')
new_category.save()
# Another way to set values
new_rule = Rule()
new_rule.name = 'Sample Rule'
new_rule.closure = closure
new_rule.created_by = 'XYZ'
new_rule.updated_by = 'XYZ'
new_rule.rule_type = rule_type
new_rule.category = new_category
new_rule.save()
```
Note this line `new_rule.category = new_category` - this is how we link two objects. Django knows that the primary key should go in the table and will take care of that automatically.
The final item is customizing the models by creating your own `__str__` method - this should return some meaningful string that is meant for humans.
```
class RuleCategory(models.Model):
name = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
def __str__(self):
return '{}'.format(self.name)
class Rule(models.Model):
name = models.CharField(max_length=50)
closure = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
updated_by = models.CharField(max_length=50)
updated_date = models.DateField(auto_now=True)
rule_type = models.CharField(max_length=50)
category = models.ForeignKey(RuleCategory,on_delete=models.CASCADE)
def __str__(self):
return '{} for category {}'.format(self.name, self.category)
```
If you notice something, I just put `self.category` in the `__str__` for the `Rule` model. This is because we have already defined a `__str__` for the `RuleCategory` model, which just returns the category name; so now when we print our Rule we created, we will get `Sample Rule for category My Category` as a result.
Upvotes: -1 [selected_answer]
|
2018/03/15
| 399 | 1,591 |
<issue_start>username_0: Can anyone explain the following bash snippet?
```
for i in $(seq 1 1 10)
do
VAR=${2%?}$i
break;
done
```<issue_comment>username_1: It removes the trailing character from `$2` (second positional parameter) and concatenates that value with `$i`
example:
```
$ v1="myvalue1x"
$ v2="myvalue2"
$ combined="${v1%?}$v2"
$ echo $combined
myvalue1myvalue2
```
For more info how the substitution works you can check the `Parameter Expansion` section of the bash manual
Upvotes: 2 <issue_comment>username_2: See the bash man page, section *parameter expansion*:
```
${parameter%word}
${parameter%%word}
Remove matching suffix pattern. The word is expanded to produce a
pattern just as in pathname expansion. If the pattern matches a
trailing portion of the expanded value of parameter, then the
result of the expansion is the expanded value of parameter with the
shortest matching pattern (the ``%'' case) or the longest matching
pattern (the ``%%'' case) deleted. If parameter is @ or *, the
pattern removal operation is applied to each positional parameter
in turn, and the expansion is the resultant list. If parameter is
an array variable subscripted with @ or *, the pattern removal
operation is applied to each member of the array in turn, and the
expansion is the resultant list.
```
Since **?** matches a single character, the trailing character is removed from the second argument of the script.
Upvotes: 0
|
2018/03/15
| 755 | 2,774 |
<issue_start>username_0: I am doing an sql query where I retrieve a list over Accounts for a specific year. I thought the below code was fine.
```
SELECT count(DISTINCT ACCOUNT) AS ACCOUNT,
CASE when MONTH(Created)=1 then 'January'
when MONTH(Created)=2 then 'February'
when MONTH(Created)=3 then 'March'
when MONTH(Created)=4 then 'April'
when MONTH(Created)=5 then 'May'
when MONTH(Created)=6 then 'June'
when MONTH(Created)=7 then 'July'
when MONTH(Created)=8 then 'August'
when MONTH(Created)=9 then 'September'
when MONTH(Created)=10 then 'October'
when MONTH(Created)=11 then 'November'
when MONTH(Created)=12 then 'December'
else '3' end AS MONTH
FROM DB_Table
WHERE
AND (DB_Table.Cancelled < '1901-01-01' OR DB_Table Cancelled > '2017-12-31')
AND YEAR(Created)='2017'
GROUP BY MONTH(Created)
Order BY MONTH(Created)
```
Until I did a check this way:
```
Select count(DISTINCT ACCOUNT) AS ACCOUNT
FROM DB_Table
WHERE
AND (DB_Table.Cancelled < '1901-01-01' OR DB_Table Cancelled > '2017-12-31')
AND YEAR(Created)='2017'
```
I'm having two different sums, but it seems like the Group by is giving me a higher count than the bottom query.
Any suggestions?<issue_comment>username_1: It removes the trailing character from `$2` (second positional parameter) and concatenates that value with `$i`
example:
```
$ v1="myvalue1x"
$ v2="myvalue2"
$ combined="${v1%?}$v2"
$ echo $combined
myvalue1myvalue2
```
For more info how the substitution works you can check the `Parameter Expansion` section of the bash manual
Upvotes: 2 <issue_comment>username_2: See the bash man page, section *parameter expansion*:
```
${parameter%word}
${parameter%%word}
Remove matching suffix pattern. The word is expanded to produce a
pattern just as in pathname expansion. If the pattern matches a
trailing portion of the expanded value of parameter, then the
result of the expansion is the expanded value of parameter with the
shortest matching pattern (the ``%'' case) or the longest matching
pattern (the ``%%'' case) deleted. If parameter is @ or *, the
pattern removal operation is applied to each positional parameter
in turn, and the expansion is the resultant list. If parameter is
an array variable subscripted with @ or *, the pattern removal
operation is applied to each member of the array in turn, and the
expansion is the resultant list.
```
Since **?** matches a single character, the trailing character is removed from the second argument of the script.
Upvotes: 0
|
2018/03/15
| 450 | 1,841 |
<issue_start>username_0: I have a problem with creating files in Android. I have followed [this](https://developer.android.com/training/data-storage/files.html#java) tutorial, and wrote this method:
```
public File getStorageDir(String name) {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
File file = new File(path, name);
System.out.println(path);
if (!file.mkdirs()) {
System.out.println("Directory not created");
}
return file;
}
```
Path variable prints /storage/emulated/0/Documents, however if goes off and no such directory is created. I have added
```
```
permissions to manifest file. I have tried using file.getParentFile().mkdirs() but got same result. What am I doing wrong?<issue_comment>username_1: You use below code to create folder.
```
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "folderName");
if (!folder.exists()) {
success = folder.mkdirs();
}
```
Upvotes: 0 <issue_comment>username_2: So turns out it was being created the whole time, just not visible in file explorer. I have fixed it with answer from [this post](https://stackoverflow.com/questions/13507789/folder-added-in-android-not-visible-via-usb). Final code looks like this:
```
public File getStorageDir(Context context, String name) {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getPath();
File file = new File(path, name);
file.getParentFile().mkdirs();
MediaScannerConnection.scanFile(context, new String[] {path}, null, null);
return file;
}
```
Thanks everyone for answers, hope this helps someone who faces same problem.
Upvotes: -1
|
2018/03/15
| 590 | 2,067 |
<issue_start>username_0: I have an query string in Python as follows:
```
query = "select name from company where id = 13 order by name;"
```
I want to be able to change the `id` dynamically. Thus I want to find `id = 13` and replace it with a new id.
I can do it as follows:
```
query.replace("id = 13", "id = {}".format(some_new_id))
```
But if in the query is `id= 13` or `id=13` or `id =13`, `...` it will not work.
How to avoid that?<issue_comment>username_1: It is better to use formatted sql.
**Ex:**
```
query = "select name from company where id = %s order by name;".
cursor.execute(query, (id,))
```
Upvotes: 0 <issue_comment>username_2: Gluing variables directly into your query leaves you vulnerable to SQL injection.
If you are passing your query to a function to be executed in your database, that function should accept additional parameters.
For instance,
```
query = "select name from company where id = %s order by name"
cursor.execute(query, params=(some_other_id,))
```
Upvotes: 1 <issue_comment>username_3: The usual solution when it comes to dynamically building strings is string formatting, ie
```
tpl = "Hello {name}, how are you"
for name in ("little", "bobby", "table"):
print(tpl.format(name))
```
**BUT** (and that's a BIG "but"): you do **NOT** want to do this for SQL queries (assuming you want to pass this query to your db using your db's python api).
There are two reasons to not use string formatting here: the first one is that correctly handling quoting and escaping is tricky at best, the second and much more important one is that [it makes your code vulnerable to SQL injections attacks](http://bobby-tables.com/).
So in this case, the proper solution is to [use prepared statements instead](http://bobby-tables.com/python):
```
# assuming MySQL which uses "%" as placeholder,
# consult your db-api module's documentation for
# the proper placeholder
sql = "select name from company where id=%s order by name"
cursor = yourdbconnection.cursor()
cursor.execute(sql, [your_id_here])
```
Upvotes: 0
|
2018/03/15
| 244 | 854 |
<issue_start>username_0: Hello I'm developing Ionic-3 Hybrid application.I am inspect app on samsung J7 device with chrome remote device inspect and everything was good but unfortunatly i'm stuck When clicking "inspect" next to the url of the page open on the google chrome an empty window shows up and nothing happens.
google chrome version:
>
> Version 64.0.3282.186 (Official Build) (64-bit)
>
>
>
google chrome empty window image is below.
[](https://i.stack.imgur.com/abvi5.png)<issue_comment>username_1: I just update my Chrome to version 65.0.3325.162 and it works.
Upvotes: 3 [selected_answer]<issue_comment>username_2: if your browser not show anything after update
open **chrome://appcache-internals/** and clear the manifest cache , then reload the resource
Upvotes: 1
|
2018/03/15
| 1,062 | 2,934 |
<issue_start>username_0: I'm trying to remove the contents of an array
`positions = ['CF','ST','RW','LW','CB','RB','LB','CM','CAM','CDM','RM','LM','RWB','LWB']`from the column Name in my dataframe with football players.Sample of this dataframe below.
[Player dataframe](https://i.stack.imgur.com/hKRYM.png)
Can anyone help me remove these strings, I have tried str.replace and it won't work,
Thanks<issue_comment>username_1: I think need if is necessary remove all strings after last whitespace:
```
df['Name'] = df['Name'].str.rsplit(n=1).str[0]
```
Or if need remove values by `positions` only (with username_2 DataFrame):
```
d = {r'\s+(\b){}(\b)'.format(x):r'' for x in positions}
df['Name'] = df['Name'].replace(d, regex=True)
print (df)
Name
0 ABC
1 DEF
2 GHI
3 JKL
```
Upvotes: 0 <issue_comment>username_2: The below method matches specifically on space-separated values.
```
df = pd.DataFrame({'Player': ['ABC CF ST RW', 'DEF LB CM', 'GHI RM', 'JKL']})
rem = ['CF','ST','RW','LW','CB','RB','LB',
'CM','CAM','CDM','RM','LM','RWB','LWB']
rem_set = set(rem)
def remover(p):
return ' '.join([x for x in p.split() if x not in rem_set])
df['Player'] = df['Player'].map(remover)
# Player
# 0 ABC
# 1 DEF
# 2 GHI
# 3 JKL
```
**Performance benchmarking**
```
df = pd.DataFrame({'Player': ['ABC CF ST RW', 'DEF LB CM', 'GHI RM', 'JKL']})
rem = ['CF','ST','RW','LW','CB','RB','LB',
'CM','CAM','CDM','RM','LM','RWB','LWB']
rem_set = set(rem)
df = pd.concat([df]*20000)
def jez(df):
d = {r'(\b){}(\b)'.format(x):r'' for x in rem_set}
df['Player'] = df['Player'].replace(d, regex=True)
return df
def jp(df):
def remover(p):
return ' '.join([x for x in p.split() if x not in rem_set])
df['Player'] = df['Player'].map(remover)
return df
%timeit jez(df) # 1.24s
%timeit jp(df) # 86ms
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: ```
df = pd.DataFrame({"Name": ["James kon CF ST RW", "Rom CAM"], "Overall": [23,65], "Club": ["a", "b"]})
positions = set(['CF','ST','RW','LW','CB','RB','LB','CM','CAM','CDM','RM','LM','RWB','LWB'])
def f(name, position):
item = set(name.split(" "))
newobj = item - position
return " ".join(newobj)
df["Name"].map(lambda x: f(x, positions))
```
Upvotes: -1 <issue_comment>username_4: You might find it enough to just remove all 2 or 3 character uppercase entries at the end as follows:
```
import pandas as pd
data = [
['Name', 'Overall', 'Club'],
['L. Messi CF ST RW', 94, 'FC Barcelona'],
['<NAME> LW LM ST RM', 92, 'Real Madrid CF']]
df = pd.DataFrame(data[1:], columns=data[0])
df['Name'] = df['Name'].replace(r'((\s+[A-Z]{2,3}))+$', '', regex=True)
print(df)
```
This would give you:
```none
Name Overall Club
0 L. Messi 94 FC Barcelona
1 <NAME> 92 Real Madrid CF
```
Upvotes: 0
|
2018/03/15
| 1,138 | 3,468 |
<issue_start>username_0: Edit: solved! The server was redirecting from /whales to /whales/, which transformed the request into a GET. My curl command had the trailing slash, but my form and Postman request did not.
---
My basic server always has "GET" as r.Method, even for post requests from Postman and html forms. r.Form is always an empty map.
My code:
```
func whaleHandler(w http.ResponseWriter, r *http.Request) {
fmt.Print(r.Method)
fmt.Print(r.Form)
}
func main() {
http.HandleFunc("/whales/", whaleHandler)
log.Fatal(http.ListenAndServe(":9002", nil))
}
```
And this prints:
```
GETmap[]
```
What am I doing wrong here? Thanks in advance, all!
---
Edit: everything works as expected with curl, but Postman and regular forms are still being treated like GET requests.
`curl -d "Name=Barry" -X POST http://localhost:9002/whales/`
results in:
`POSTmap[]`,
and `r.FormValue("Name")` spits out `Barry`
---
Sample form:
```
```
And full output from `fmt.Print(r)`, formatted a little for readability:
```
&{GET
/whales/
HTTP/1.1
1
1
map[
Accept:[
text/html,
application/xhtml+xml,
application/xml;q=0.9,*\/*;q=0.8
]
Accept-Language:[en-US,en;q=0.5]
Accept-Encoding:[gzip, deflate]
Cookie:[io=08-aNjAMs8v6ntatAAAA]
Connection:[keep-alive]
Upgrade-Insecure-Requests:[1]
User-Agent:[Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:58.0) Gecko/20100101 Firefox/58.0] Referer:[http://localhost:9002/whales/create]
]
{}
0
[]
false
localhost:9002
map[]
map[]
map[]
[::1]:61037
/whales/
0xc420162400}
```
---
Edit:
Sample Postman request, which results in r.Method => "GET"
[Posting with Postman](https://i.stack.imgur.com/QMNZ9.png)<issue_comment>username_1: You need to call [`Request.ParseForm()`](https://golang.org/pkg/net/http/#Request.ParseForm) (or something that calls it indirectly, such as [`Request.FormValue()`](https://golang.org/pkg/net/http/#Request.FormValue)), until then `Request.Form` will not contain form data. See possible duplicate [Getting No data received for go language form](https://stackoverflow.com/questions/28610030/getting-no-data-received-for-go-language-form/28610108#28610108).
This is documented at `Request.Form`:
```
// Form contains the parsed form data, including both the URL
// field's query parameters and the POST or PUT form data.
// This field is only available after ParseForm is called.
// The HTTP client ignores Form and uses Body instead.
Form url.Values
```
If you change your handler to this:
```
func whaleHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Method)
fmt.Println(r.Form)
if err := r.ParseForm(); err != nil {
fmt.Println("Error parsing form:", err)
}
fmt.Println(r.Form)
}
```
And performing the `curl` command:
```
curl -d "Name=Barry" -X POST http://localhost:9002/whales/
```
Output will be:
```
POST
map[]
map[Name:[Barry]]
```
Upvotes: 0 <issue_comment>username_2: You registered your handler under "/whales/", but your form action is "/whales" (without trailing slash). Go will redirect requests from /whales to /whales/ in this configuration -- most clients choose to follow via GET requests.
Either register the handler for "/whales", or change the form action to "/whales/", depending on other URLs you wish to handle. E.g., if you need to handle /whales/willy, leave the handler as-is and change the form action.
Upvotes: 3 [selected_answer]
|
2018/03/15
| 627 | 2,286 |
<issue_start>username_0: **Introduction:**
I've been studying machine learning this last couple of months, more specifically neural networks. I found out that categorical data, such as cities, could be transformed to integer data, but shouldn't because there's no linearity. What I mean by this is: there is no reason why New York should be 1 or 100. A better solution to this is one hot encoding. However, it greatly increases the dimensionality of the problem (Picture a network input with the number of cities as input nodes).
**Example:**
New York = [1, 0, 0]
Buenos Aires = [0, 1, 0]
Tokio = [0, 0, 1]
You need N inputs, N being the number of cities.
**Possible Solution:**
I don't really know if this already exists or if it could work, I haven't tested it yet. That being said, in the example above, I'm using *decimal* inputs. Could you use **binary inputs**, in order to reduce the dimensionality of the problem?
**Example using binary inputs**
New York = [0, 1]
Buenos Aires = [1, 0]
Tokio = [1, 1]
In this way, you only need ≈ **log(N) (base 2)** number of inputs which greatly increases, specially if there are a great number of features. For example: if you have 1000 categorical data inputs, it would only result in 10 inputs for a neural network.
Thank you in advance. Remember I'm only learning.<issue_comment>username_1: But then you would only be changing the numbering base system from base 10 to base 2 not solving the problem i.e there is no reason for New York to be 1111 not 0001.
Upvotes: 0 <issue_comment>username_2: I do not think that you can translate One Hot Encoding (OHE) to binary inputs.
The meaning of One Hot Encoding is that you have as many features as you have cities. No two cities share value for any feature, as they are distinct. After you translation to binary inputs, various cities randomly share values for the same feature.
E.g. both Buenos Aires and Tokio would have 1 as the first feature. The neural network would think that they really have this feature in common. Yet it is not the case, depending on your ordering, New York could easily share value of the first feature with Tokio:
```
Buenos Aires = [0, 1]
Tokio = [1, 0]
New York = [1, 1]
```
Now, Tokio and New York seem more similar to each other.
Upvotes: 1
|
2018/03/15
| 1,544 | 5,711 |
<issue_start>username_0: I have an input field on my html that I need to limit the value of.
I am trying doing like this:
HTML:
```
```
Typescript:
```
onChangeValue(valueString: string, option: OptionViewModel) {
var value: number = parseInt(valueString);
// Check some conditions. Simplified code just for example
if (option.value != value && value > 5) {
value = 5;
}
option.value = value;
}
```
OptionViewModel:
```
export class OptionViewModel {
public optionId: number;
public description: string;
public pollId: number;
public value?: number;
}
```
I tried using two-way binding, but my code relies on the previous value of option.value, and using two-way binding changes the variable before entering the function.
The problem is, sometimes the input field is not being updated.
It looks like I just work the first time the value need to be changed, so for example, if input 6 the field is correctly changed to 5, but then if I add a 0 (making it 50), it doesn't correct to 5.
I debbuged the code and it is running the function and changing the option.value, and even using Augury to inspect the objects show the correct value.<issue_comment>username_1: Hi try to change ng model two way binding ,like that
```
```
Upvotes: 2 <issue_comment>username_2: You can try also creating a simple observable that will check the information for you.
```
import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/map';
@Component({
selector: 'my-app',
template: ``,
})
export class AppComponent implements OnInit {
value: string = '';
@ViewChild('inputName') inputName: ElementRef;
ngOnInit() {
const input = this.inputName.nativeElement as HTMLInputElement;
Observable.fromEvent(input, 'input')
.map((evt: Event) => evt.target as HTMLInputElement)
.subscribe(target => target.value = Number(target.value) > 5 ? '5' : target.value);
}
}
```
Upvotes: 0 <issue_comment>username_3: On your second edit, the content of the input element is not updated because Angular has not detected any change (`option.value` was 5, and it is still 5). Here are two methods to force the refresh of the element.
---
**Method 1 - Replace the option item in the array**
You can force the field to update by replacing the option in the array with a cloned copy, as shown in **[this stackblitz](https://stackblitz.com/edit/template-driven-form-2-nxzhgm?file=app%2Fapp.component.ts)**:
```
```
```
onChangeValue(valueString: string, index: number) {
var value: number = parseInt(valueString);
if (value > 5) {
value = 5;
}
this.options[index] = this.options[index].cloneWithValue(value);
}
export class OptionViewModel {
public optionId: number;
public description: string;
public pollId: number;
public value?: number;
public cloneWithValue(value: number): OptionViewModel {
let dest = new OptionViewModel();
dest.optionId = this.optionId;
dest.description = this.description;
dest.pollId = this.pollId;
dest.value = value;
return dest;
}
}
```
---
**Method 2 - Use an additional field in the trackBy function**
An alternative solution is to add an additional field to `OptionViewModel` (e.g. `lastModified`) and to use it in a `trackBy` method of the `ngFor` directive (see [**this stackblitz**](https://stackblitz.com/edit/template-driven-form-2-kqvecm?file=app/app.component.ts)):
```
```
```
onChangeValue(valueString: string, option: OptionViewModel) {
var value: number = parseInt(valueString);
if (value > 5) {
value = 5;
}
option.value = value;
option.lastModified = Date.now();
}
trackByFn(index: number, option: OptionViewModel) {
return `${index}___${option.lastModified}`;
}
```
```
export class OptionViewModel {
public optionId: number;
public description: string;
public pollId: number;
public value?: number;
public lastModified: number = 0;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: The simplest solution worked for me is to use [ChangeDetectorRef](https://angular.io/api/core/ChangeDetectorRef).The change detection tree collects all views and updates the values of all components
1. Make variable type of ChangeDetectorRef in contructor like below:-
```
constructor(private changeDet:ChangeDetectorRef) { }
```
2. Now just call **changeDet.detectChanges()** after setting/updating your value
```
onChangeValue(valueString: string, option: OptionViewModel) {
var value: number = parseInt(valueString);
// Check some conditions. Simplified code just for example
if (option.value != value && value > 5) {
value = 5;
}
option.value = value;
this.changeDet.detectChanges();//Detects changes and updates value
}
```
Upvotes: 2 <issue_comment>username_5: Found a simpler workaround. Just use *(keyup)* instead of *(change)*.
```
```
I haven't passed the event as argument because I already have the ngModel updating my variable.
```
editableFieldValueChanged() {
if (this.editableFieldValue < -100) {
this.editableFieldValue = -100;
}
if (this.editableFieldValue > 100) {
this.editableFieldValue = 100;
}
}
```
The TLDR version is, Angular considers this the same as choosing the same option in a dropdown over and over again, because the previous and current value is the same and hence it finds no reason to update the DOM element.
I believe this approach works because the *(keyup)* has a different execution order compared to the other events. I will leave the explaining to the people who are a lot more knowledgeable than I am.
Upvotes: 1
|
2018/03/15
| 1,595 | 5,900 |
<issue_start>username_0: I have many assumptions about android because I lack of knowledge of android internal.
I'm developing apps with Android Studio. I usually search code snippet for java instead of android.
For example I search "java read file into byte array" rather than "android read file into byte array" so search results show java code snippets.
But sometimes, I see something like - "JAVA 7+" or "java 6+" which I translate as - "this code only work if I'm writing for this version (or above) of java".
I'm running android studio with JRE version 8 so I'm sure that my code will work in android studio and my APK will be generated successfully. But I'm also afraid that if a device does not have that version of java, my APK will crash on that device. This is all because I have the following assumptions:
>
> 1. android is based on JAVA and XML.
> 2. so android has JRE or JDK internally.
> 3. that JRE or JDK version(6/7/8..) depends on what android version that device has. For example may be Jellybean has JRE 6 and Oreo has
> JRE 8 etc (if it's true then what version has what?).
> 4. my app will crash if I compile code for JAVA 8 and my APK meets a device that runs on a lower version of JRE.
>
>
>
That are my assumptions, it's a long question so I couldn't search it using keywords. Please guide me (tell me which assumption is wrong and what is right).<issue_comment>username_1: Hi try to change ng model two way binding ,like that
```
```
Upvotes: 2 <issue_comment>username_2: You can try also creating a simple observable that will check the information for you.
```
import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/map';
@Component({
selector: 'my-app',
template: ``,
})
export class AppComponent implements OnInit {
value: string = '';
@ViewChild('inputName') inputName: ElementRef;
ngOnInit() {
const input = this.inputName.nativeElement as HTMLInputElement;
Observable.fromEvent(input, 'input')
.map((evt: Event) => evt.target as HTMLInputElement)
.subscribe(target => target.value = Number(target.value) > 5 ? '5' : target.value);
}
}
```
Upvotes: 0 <issue_comment>username_3: On your second edit, the content of the input element is not updated because Angular has not detected any change (`option.value` was 5, and it is still 5). Here are two methods to force the refresh of the element.
---
**Method 1 - Replace the option item in the array**
You can force the field to update by replacing the option in the array with a cloned copy, as shown in **[this stackblitz](https://stackblitz.com/edit/template-driven-form-2-nxzhgm?file=app%2Fapp.component.ts)**:
```
```
```
onChangeValue(valueString: string, index: number) {
var value: number = parseInt(valueString);
if (value > 5) {
value = 5;
}
this.options[index] = this.options[index].cloneWithValue(value);
}
export class OptionViewModel {
public optionId: number;
public description: string;
public pollId: number;
public value?: number;
public cloneWithValue(value: number): OptionViewModel {
let dest = new OptionViewModel();
dest.optionId = this.optionId;
dest.description = this.description;
dest.pollId = this.pollId;
dest.value = value;
return dest;
}
}
```
---
**Method 2 - Use an additional field in the trackBy function**
An alternative solution is to add an additional field to `OptionViewModel` (e.g. `lastModified`) and to use it in a `trackBy` method of the `ngFor` directive (see [**this stackblitz**](https://stackblitz.com/edit/template-driven-form-2-kqvecm?file=app/app.component.ts)):
```
```
```
onChangeValue(valueString: string, option: OptionViewModel) {
var value: number = parseInt(valueString);
if (value > 5) {
value = 5;
}
option.value = value;
option.lastModified = Date.now();
}
trackByFn(index: number, option: OptionViewModel) {
return `${index}___${option.lastModified}`;
}
```
```
export class OptionViewModel {
public optionId: number;
public description: string;
public pollId: number;
public value?: number;
public lastModified: number = 0;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: The simplest solution worked for me is to use [ChangeDetectorRef](https://angular.io/api/core/ChangeDetectorRef).The change detection tree collects all views and updates the values of all components
1. Make variable type of ChangeDetectorRef in contructor like below:-
```
constructor(private changeDet:ChangeDetectorRef) { }
```
2. Now just call **changeDet.detectChanges()** after setting/updating your value
```
onChangeValue(valueString: string, option: OptionViewModel) {
var value: number = parseInt(valueString);
// Check some conditions. Simplified code just for example
if (option.value != value && value > 5) {
value = 5;
}
option.value = value;
this.changeDet.detectChanges();//Detects changes and updates value
}
```
Upvotes: 2 <issue_comment>username_5: Found a simpler workaround. Just use *(keyup)* instead of *(change)*.
```
```
I haven't passed the event as argument because I already have the ngModel updating my variable.
```
editableFieldValueChanged() {
if (this.editableFieldValue < -100) {
this.editableFieldValue = -100;
}
if (this.editableFieldValue > 100) {
this.editableFieldValue = 100;
}
}
```
The TLDR version is, Angular considers this the same as choosing the same option in a dropdown over and over again, because the previous and current value is the same and hence it finds no reason to update the DOM element.
I believe this approach works because the *(keyup)* has a different execution order compared to the other events. I will leave the explaining to the people who are a lot more knowledgeable than I am.
Upvotes: 1
|
2018/03/15
| 760 | 2,410 |
<issue_start>username_0: Fiddle here: <https://jsfiddle.net/mv5ut6sw/>
I have a list of links at the top of my webpage contained in a . I would like a horizontal `---` line above and below this to visually separate the links from the rest of the page. Simplified example:
```
---
* [Link1](/link1)
* [Link2](/link2)
* [Link3](/link3)
* [Link4](/link4)
---
```
I am using bootstrap to pretty the page up. Without bootstrap, the `---`s behave as expected, appearing above and below the link section. When I use bootstrap, however, the two horizontal lines both appear above the link section.
I am at a loss. I don't want to edit bootstrap code. Is there inline css I can include to fix this weird placement?<issue_comment>username_1: >
> "Is there inline css I can include to fix this weird placement?"
>
>
>
It's because of the floats. Just clear the last `---`..
```
---
```
<https://jsfiddle.net/s9L0Lf9b/>
```html
###
Ye old title
---
* [Race Entry](/go/entry)
* [Start](/go)
* [Position Transfer](/go/transfer)
* [Contracts](/contracts)
* [Statements](/statement)
* [Race Position](/position)
* [Advertising Firm](/firm)
* [Report1](/report1)
* [Report2](/report2)
* [Settle it!](/settleit)
* [Upload](/upload)
* [Search](/search)
---
```
>
> "The float CSS property specifies that an element should be taken from
> the normal flow and placed along the left or right side of its
> container, where text and inline elements will wrap around it." \_\_ [from MDN posted on a related question](https://stackoverflow.com/questions/20188510/why-a-div-with-float-right-does-not-respect-the-margin-of-the-hr-tag-below/20188655)
>
>
>
P.S. - There's no need to use floats with Bootstrap 4.
Upvotes: 1 <issue_comment>username_2: Its because floats take the elements out of the flow...either you can clear the float value `clear:both` or by applying `overflow:hidden` in the parent div...
Well If you are using **bootstrap4** then why use `floats`...just Use `d-flex` class on the parent div
```html
###
Ye old title
---
* [Race Entry](/go/entry)
* [Start](/go)
* [Position Transfer](/go/transfer)
* [Contracts](/contracts)
* [Statements](/statement)
* [Race Position](/position)
* [Advertising Firm](/firm)
* [Report1](/report1)
* [Report2](/report2)
* [Settle it!](/settleit)
* [Upload](/upload)
* [Search](/search)
---
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 1,374 | 4,839 |
<issue_start>username_0: Lets say I have two classes car and service. Is it possible to create the elements for both vector objects(note: I don't know if is actually refereed to as vector objects), of the car and service classes. Once both elements are created I would only like the car class constructor to be called later to have the service constructor called to get the user information?
Also if it is possible is it possible without having to change the Service constructor to a method?
```
using namespace std; // I know this is not the best, prof wants us to use it
class Car { Car() { //Get data from user } };
class Service { Service(){ //Get data from user } };
int main () {
int num;
vector car;
vector service;
car.push\_back(Car{});
service.push\_back();
for (int i = 0; i < car.size(); i++)
car[i].display(i);
cout << endl << car.size() + 1 << ". exit";
cin >> num;
service[num].Service::Service();
}
```<issue_comment>username_1: Since C++11, you have the list-initialization for vector and other containers.
<http://en.cppreference.com/w/cpp/language/list_initialization>
Which means, you can put an enumeration of elements in a vector while initialization.
You can use your own class constructor in it:
```
std::vector cars {Car(...), Car(...), Car(...)}; //C++11
```
Since I can't comment your question yet, is it what you expected?
Upvotes: 1 <issue_comment>username_2: I would recommend using a `std::map` instead of `std::vector` which choice naturally follows from your task. By using it, you will be storing valid Service elements only.
```
map service;
car.push\_back(Car{});
for (int i = 0; i < car.size(); i++)
car[i].display(i);
cout << endl << car.size() + 1 << ". exit";
cin >> num;
service[num]; //Service constructor will be called
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: I'm thinking you are looking for something like this:
```
class Car {
private:
std::string _make;
std::string _model;
std::string _vinNumber;
std::size_t _year;
public:
Car() : _year( 0 ) {} // default
Car( const std::string& make, const std::string& model,
const std::string& vinNumber, const std::size_t& year ) :
_make( make ), _model( model ),
_vinNumber( vinNumber ), _year( year ) {
}
void setCarInfo( const std::string& make, const std::string& model,
const std::string& vinNumber, const std::size_t& year ) {
_make = make;
_model = model;
_vinNumber = vinNumber;
_year = year;
}
std::string makeOf() const { return _make; }
std::string modelOf() const { return _model; }
std::string vinNumberOf() const { return _vinNumber; }
std::size_t yearOf() const { return _year; }
};
class Service {
private:
std::string _dealership;
std::size_t _currentMiles;
public:
Serivce() {}
std::string dealershipOf() const { return _dealership; }
std:size_t currentMilesOf() const { return _currentMiles; }
void setOrChangeDealership( const std::string& dealership ) {
_dealership = dealership;
}
void setOrChangeCurrentMiles( std::size_t miles ) {
_currentMiles = miles;
}
void setOrChangeCurrentMiles( const std::size_t& miles ) {
_currentMiles = miles;
}
};
int main() {
std::vector cars;
std::vector services;
// you can add Car to vector by either default constructor
// to be filled out later or by user defined constructor
cars.push\_back( Car( "Honda", "Civic", "75273250323XMD252AG9", 2017 ) );
// or
cars.push\_back( Car() );
// then you can at some point in time update elements in container
cars[i].setCarInfo( "Dodge", "Charger", "9259356M325D2680A217B", 2015 );
// As with the service class there is only a "default" constructor
services.push\_back( Service() );
// Service's members will have to be updated manually and later.
return 0;
}
```
Regardless of what container you use, or even if you have a single instance of a class object; a `CTOR` for that class will be called. The only way that one will not is if either A: you declare it as `protected` or `private` in the class the prevents the class from being declared which is used with inheritance and polymorphism, or if you declare the constructor as a deleted function: `SomeClass() = delete`. There is no possible way to have a class instance without its constructor being called either implicitly by the compiler or explicitly by you.
Even something as simple as this:
```
class A {
public:
int x;
};
int main() {
A a;
a.x = 5;
return 0;
}
```
The line `A a;` behind the scenes the compiler will invoke `A()` on `a` so it would actually look like this:
```
A a();
```
Using its default constructor.
Upvotes: 1
|
2018/03/15
| 1,876 | 6,747 |
<issue_start>username_0: I'm **not** asking how to loop through an array in typescript. My question is a bit different so let me explain first.
I have a json which looks like this:
```
{
"forename": "Maria",
"colors": [
{
"name": "blue",
"price": 10
},
{
"name": "yellow",
"price": 12
}
],
"items": [
{
"name": "sword",
"price": 20
}
],
"specialPowers": [
{
"name": "telekinesis",
"price": 34
}
]
},
{
"forename": "Peter",
"colors": [
{
"name": "blue",
"price": 10
}
],
"items": [
{
"name": "hat",
"price": 22
},
{
"name": "hammer",
"price": 27
}
]
}
// some more persons
```
As you can see, I have persons which can have arrays like colors, items or specialPowers. BUT a person can also have none of them. As you can see Maria has the array specialPowers, but Peter has not.
I need a function which checks if a person has one of these arrays and if so, I have to sum its price to a total. So I want the total price of all the things a person has.
At the moment I have three functions which basically look like this:
```
getTotalOfColors(person) {
let total = 0;
if(person.colors)
for (let color of person.colors) {
total = total + color.price;
}
return total;
}
getTotalOfItems(person) {
let total = 0;
if(person.items)
for (let item of person.items) {
total = total + item.price;
}
return total;
}
// SAME FUNCTION FOR SPECIALPOWERS
```
I basically have the same function for three times. The only difference is, that I'm looping through another array. But these functions do all the same. They first check, if the person has the array and secondly they loop through this array to add the price to a total.
Finally to my question: Is there a way to do this all in ONE function? Because they all are basically doing the same thing and I don't want redundant code. My idea would be to loop through all the arrays while checking if the person has the array and if so, adding its price to the total.
I assume the function would look something like this:
```
getTotal(person) {
let total = 0;
for (let possibleArray of possibleArrays){
if(person.possibleArray )
for (let var of person.possibleArray ) {
total = total + var.price;
}
}
return total;
}
```
Like this I would have a "universal" function but for that I have to have an array of the possible arrays like this: **possibleArrays = [colors, items, specialPowers]**
How do I achieve this? How and where in my code should I make this array ? Or is there even a better solution for this problem?<issue_comment>username_1: Since C++11, you have the list-initialization for vector and other containers.
<http://en.cppreference.com/w/cpp/language/list_initialization>
Which means, you can put an enumeration of elements in a vector while initialization.
You can use your own class constructor in it:
```
std::vector cars {Car(...), Car(...), Car(...)}; //C++11
```
Since I can't comment your question yet, is it what you expected?
Upvotes: 1 <issue_comment>username_2: I would recommend using a `std::map` instead of `std::vector` which choice naturally follows from your task. By using it, you will be storing valid Service elements only.
```
map service;
car.push\_back(Car{});
for (int i = 0; i < car.size(); i++)
car[i].display(i);
cout << endl << car.size() + 1 << ". exit";
cin >> num;
service[num]; //Service constructor will be called
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: I'm thinking you are looking for something like this:
```
class Car {
private:
std::string _make;
std::string _model;
std::string _vinNumber;
std::size_t _year;
public:
Car() : _year( 0 ) {} // default
Car( const std::string& make, const std::string& model,
const std::string& vinNumber, const std::size_t& year ) :
_make( make ), _model( model ),
_vinNumber( vinNumber ), _year( year ) {
}
void setCarInfo( const std::string& make, const std::string& model,
const std::string& vinNumber, const std::size_t& year ) {
_make = make;
_model = model;
_vinNumber = vinNumber;
_year = year;
}
std::string makeOf() const { return _make; }
std::string modelOf() const { return _model; }
std::string vinNumberOf() const { return _vinNumber; }
std::size_t yearOf() const { return _year; }
};
class Service {
private:
std::string _dealership;
std::size_t _currentMiles;
public:
Serivce() {}
std::string dealershipOf() const { return _dealership; }
std:size_t currentMilesOf() const { return _currentMiles; }
void setOrChangeDealership( const std::string& dealership ) {
_dealership = dealership;
}
void setOrChangeCurrentMiles( std::size_t miles ) {
_currentMiles = miles;
}
void setOrChangeCurrentMiles( const std::size_t& miles ) {
_currentMiles = miles;
}
};
int main() {
std::vector cars;
std::vector services;
// you can add Car to vector by either default constructor
// to be filled out later or by user defined constructor
cars.push\_back( Car( "Honda", "Civic", "75273250323XMD252AG9", 2017 ) );
// or
cars.push\_back( Car() );
// then you can at some point in time update elements in container
cars[i].setCarInfo( "Dodge", "Charger", "9259356M325D2680A217B", 2015 );
// As with the service class there is only a "default" constructor
services.push\_back( Service() );
// Service's members will have to be updated manually and later.
return 0;
}
```
Regardless of what container you use, or even if you have a single instance of a class object; a `CTOR` for that class will be called. The only way that one will not is if either A: you declare it as `protected` or `private` in the class the prevents the class from being declared which is used with inheritance and polymorphism, or if you declare the constructor as a deleted function: `SomeClass() = delete`. There is no possible way to have a class instance without its constructor being called either implicitly by the compiler or explicitly by you.
Even something as simple as this:
```
class A {
public:
int x;
};
int main() {
A a;
a.x = 5;
return 0;
}
```
The line `A a;` behind the scenes the compiler will invoke `A()` on `a` so it would actually look like this:
```
A a();
```
Using its default constructor.
Upvotes: 1
|
2018/03/15
| 585 | 2,321 |
<issue_start>username_0: Looking at the liquibase documention <http://www.liquibase.org/documentation/changes/create_index.html>, CIC is not possible with create index, as liquibase doesn't have a tag to specify concurrent option.
Is there a way to create index concurrently with liquibase?<issue_comment>username_1: You can specify `runInTransaction` as `false` to create the index concurrently.
Upvotes: 4 <issue_comment>username_2: Creating a concurrent index must be done with the arbitrary [sql change](https://www.liquibase.org/documentation/changes/sql.html):
```
CREATE INDEX CONCURRENTLY
IF NOT EXISTS idx\_widgets\_kind
ON widgets(kind)
```
This is a combination of [a\_horse\_with\_no\_name's comment](https://stackoverflow.com/questions/49300553/postgres-how-to-create-index-concurrently-using-liquibase#comment85603002_49300553) and [username_1's answer](https://stackoverflow.com/a/50804878/460826).
Upvotes: 3 <issue_comment>username_3: The previous answers do the job. I would like to offer an alternative that doesn't directly answer the OP's question, but does offer a solution with the same end result with some added advantages. I feel it is good to show other options for people that stumble upon this answer like I did.
In order to create the index using only Liquibase, you would need to use the tag. I caution against this as it can cause undesired consequences in the event that you use a different database for any reason (development, evaluation, testing, etc). The sql statement will be skipped and you can be left thinking that the index was added when in reality it was not.
Additionally, this can lead to a less controlled migration, assuming you are running this on a production system without taking it down for maintenance and the migration being part of the build process.
I would propose creating the index directly on Postgres and adding the index migration normally using Liquibase and a precondition check.
First, add the index manually:
```
CREATE INDEX CONCURRENTLY widgets_kind_idx ON widgets (kind);
```
And then add to your Liquibase changeSet:
```
```
This offers the ability to add the index in any manner desired and keeps your Liquibase migrations in a known state. A fresh database being setup would not require the `CONCURRENTLY` keyword.
Upvotes: 3
|
2018/03/15
| 605 | 2,056 |
<issue_start>username_0: Here's my [code](http://rextester.com/ETPT71475):
```
public class Program
{
public static void Main(string[] args)
{
Factory factory = new Factory();
}
}
public class Factory
{
public Factory() {
Animal animal = new Animal();
MVCSender(animal);
}
public void MVCSender(object elem) {
WebAPIReceiver(elem);
}
public void WebAPIReceiver(object elem) {
WebAPIProcesser((T)elem);
}
public void WebAPIProcesser(Animal elem) {
elem.Speak();
}
}
public class Animal
{
public Animal() {}
public void Speak()
{
Console.WriteLine("Animal Speak!");
}
}
```
I pass the `T` across functions, and on the "endpoints" I try to cast the generic `object` type using the type `T` I've passed across functions.
Its an self-learning question, the whole doesn't make any sense.
1. Why can't I cast `WebAPIProcesser((T)elem)` to `Animal` from `T`?
2. What is the meaning of writing (after the function name) on generics in C#? Does it simply substitute the `template` (on `C++` for example) before any function declaration?<issue_comment>username_1: ```
public void WebAPIReceiver(object elem) {
WebAPIProcesser((T)elem);
}
```
In contrast to C++ templates, that only fail if what you *actually do* with them is illegal, C# makes sure *any* call you *could* make must be legal.
In your case: Although `T` *in your case* is `Animal`, the compiler has to make sure that your method works for *any* `T`. And it does not. It fails for any non-`Animal`. So the compiler will give you an error.
Upvotes: 2 <issue_comment>username_2: >
> If you reply to me with an answer where you show to me how to convert
> from template T to string (i.e. infer Animal to string "Animal") you
> will get my "accepted" answer!
>
>
>
```
void Main()
{
Foo foo = new Foo();
Animal animal = new Animal();
Console.Write(foo.Get(animal));
}
public class Animal
{
}
public class Foo {
public string Get(T entity)
{
return entity.GetType().Name;
}
}
```
Upvotes: 0
|
2018/03/15
| 722 | 2,803 |
<issue_start>username_0: I have two methods that are almost identical. The only difference is that I have two separate events for the click event on the button click. Is there a clean way to transform this into one method call? Can I pass in an event name in the method parameter list? If I instantiate two different events and pass them into the same method, I need each event to have it's own event handling method definition (crowdDynoButtonClick\_Event and playerDynoButtonClick\_Event)
```
private void loadChildCrowdObjectsOnScreen(UniformGrid ug) {
foreach (PlayerCrowdObjectBO childObject in childCrowdObjectOC) {
Button b = new Button();
b.Tag = childObject.ObjectNbr;
b.Height = 25;
b.Margin = new Thickness(5);
b.Content = childObject.ObjectName + " #" + childObject.ObjectNbr;
b.Click += crowdDynoButtonClick_Event;
ug.Children.Add(b);
}
}
private void loadChildPlayerObjectsOnScreen(UniformGrid ug) {
foreach (PlayerCrowdObjectBO childObject in childPlayerObjectOC) {
Button b = new Button();
b.Tag = childObject.ObjectNbr;
b.Height = 25;
b.Margin = new Thickness(5);
b.Content = childObject.ObjectName + " #" + childObject.ObjectNbr;
b.Click += playerDynoButtonClick_Event;
ug.Children.Add(b);
}
}
```<issue_comment>username_1: You could go for an extraction of the event handler
```
private void loadCrowdObjectsOnScreen(UniformGrid ug, RoutedEventHandler handler) {
foreach (PlayerCrowdObjectBO childObject in childCrowdObjectOC) {
Button b = new Button();
b.Tag = childObject.ObjectNbr;
b.Height = 25;
b.Margin = new Thickness(5);
b.Content = childObject.ObjectName + " #" + childObject.ObjectNbr;
b.Click += handler;
ug.Children.Add(b);
}
}
```
Note: I'm not sure what your `handler` type is, you may have to enhance this to apply to your code.
Upvotes: 4 [selected_answer]<issue_comment>username_2: What is wrong with just keeping it simple with two event handlers and one method?
```
private void loadChildCrowdObjectsOnScreen(UniformGrid ug) {
DoStuff(childCrowdObjectOC);
}
private void loadChildPlayerObjectsOnScreen(UniformGrid ug) {
DoStuff(childPlayerObjectOC);
}
private void DoStuff(List objs){
foreach (PlayerCrowdObjectBO childObject in objs) {
Button b = new Button();
b.Tag = childObject.ObjectNbr;
b.Height = 25;
b.Margin = new Thickness(5);
b.Content = childObject.ObjectName + " #" + childObject.ObjectNbr;
b.Click += playerDynoButtonClick\_Event;
ug.Children.Add(b);
}
}
```
Upvotes: 1
|
2018/03/15
| 384 | 1,129 |
<issue_start>username_0: Here I am using a css file where I am setting height for tootltip
```
.md-tooltip{
width : 120px;
height: 200px;
background-color:white;
}
```
dynamically trying to set the height using
```
$(".md-tooltip").height(100);
```
how to override the height 100px from CSS file. I want the height to need to be set by $ jquery. It's not working currently.
**EDIT**
```js
$(".md-tooltip").height(50);
```
```css
.md-tooltip{
width : 120px;
height: 200px;
background-color:red;
}
```
```html
```<issue_comment>username_1: `$(".md-tooltip").css("height","100px");` should work for you. EDIT: if you have a variable, put it like this: (" css attr.name", var+"px")
Upvotes: 2 <issue_comment>username_2: To achieve expected result , use below option of setProperty
```
$(".md-tooltip")[0].style.setProperty('height', '100px', 'important');
```
code sample - <https://codepen.io/nagasai/pen/rdLVBy>
**Option2:**
Using attr() option ,add style
```
$(".md-tooltip").attr('style','height: 50px !important');
```
code sample - <https://codepen.io/nagasai/pen/NYrGWj>
Upvotes: 2
|
2018/03/15
| 676 | 2,784 |
<issue_start>username_0: We use Simple Injector in ASP.NET Core application. Recently we've decided to use Serilog for logging purposes.
Configuration was done in Program.cs as stated in their [documentation](https://github.com/serilog/serilog-aspnetcore). Then, in order to make Simple Injector able to resolve `ILoggerFactory` I did something like this:
```
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
// As per my understanding, we force SimpleInjector to use
// ILoggerFactory registration from IApplicationBuilder
container.CrossWire(app)
}
```
After that `ILoggerFactory` can be injected wherever we use it. And it works fine (creates new instances `ILogger`).
But this is annoying, to create instance from factory every time we need.
It would be better to get `ILogger` directly in dependent class, instead of `ILoggerFactory`.
So, how can I register `ILogger` to get instance in case like below?
```
public class HelloWorldController : Controller
{
public HelloWorldController(ILogger logger)
{
// ...
}
}
```<issue_comment>username_1: You also have to register the logger iteself as a generic type.
I don't know simple injector but this should be the correct syntax.
```
container.Register(typeof(ILogger<>), typeof(Logger<>), Lifestyle.Singleton);
```
Upvotes: 2 <issue_comment>username_2: Although Alsami's answer would work, use the following registration instead:
```cs
container.RegisterConditional(
typeof(ILogger),
c => typeof(Logger<>).MakeGenericType(c.Consumer.ImplementationType),
Lifestyle.Singleton,
c => true);
// This next call is not required if you are already calling AutoCrossWireAspNetComponents
container.CrossWire(app);
```
This exact example is shown in the [documentation](https://simpleinjector.readthedocs.io/en/latest/advanced.html?highlight=registerconditional#context-based-injection).
This registration allows injecting the `Logger` into a *non-generic* `ILogger` constructor argument, where the `T` of `Logger` becomes the type the logger is injected into. In other words, when `HelloWorldController` depends on `ILogger`, it will get injected with a `Logger`. This means you can simplify your `HelloWorldController` to the following:
```
public class HelloWorldController : Controller
{
public HelloWorldController(ILogger logger)
{
// ...
}
}
```
By letting your application components depend on `ILogger` rather than `ILogger` you:
* Simplify your application code
* Simplify your unit tests
* Remove the possibility of making accidental errors, because it becomes impossible to inject the wrong logger.
Upvotes: 4 [selected_answer]
|
2018/03/15
| 496 | 1,631 |
<issue_start>username_0: I am using ReactTable and I need to create some summary in the end.
It should be visible every time also when pagination is there. Is it possible to achieve it with react table? I can partly solve it by creating next table. But I did not find the way how to hide header. Another problem is when resizing columns width, then it is not applied to another table.
Example table
```
| id | product | stock data | price |
| 1 | apple | 1 | 123 |
| 2 | pie | 2 | 22 |
...
|prev page | 2 / 5 | next page |
| | summary | | 145 |
```
or that summary can be above of pagination<issue_comment>username_1: The solution is footer.
<https://react-table.js.org/#/story/footers>
Please see if it fits to your use case.
Upvotes: 3 [selected_answer]<issue_comment>username_2: To add a footer on your `ReactTable`, simply define a [`Footer`](https://react-table.js.org/#/story/footers) property on your `columns` props. You can set a simple text like `Summary`, JSX, or even another component.
Here's an example like yours:
```
import React from "react";
import { render } from "react-dom";
import ReactTable from "react-table";
import "react-table/react-table.css";
const data = [
{
id: 1,
product: "apple",
stock: 1,
price: 123
},
{
id: 2,
product: "pie",
stock: 2,
price: 22
}
];
const App = () => (
{
// Get the total of the price
data.reduce((total, { price }) => total += price, 0)
}
)
}
]}
defaultPageSize={2}
/>
);
render(, document.getElementById("root"));
```
Hope this gives you an idea.
Upvotes: 3
|
2018/03/15
| 369 | 1,187 |
<issue_start>username_0: In my dataset I have a variable (numeric) which is year+month, called *year\_month* with values 201702, 201703 etc.
Normally my code looks like this:
```
select
year_month
,variable2
,variable3
from dataset
```
I wish to extract the month and the year from the year\_month variable, but I'm not sure how to do this when *year\_month* is numeric.
**edit**: not a duplicate, different problem, I do not care about dates.<issue_comment>username_1: To extract the date parts from an integer
```
SELECT year_month/100,MOD(year_month,100)
```
To fully convert the integer to a date :
```
SELECT TO_DATE(CHAR(year_month),'YYYYMM')
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Possible with this methods too:
```
select left(cast(year_mont as varchar(6)), 4) as YYYY,
right(cast(year_mont as varchar(6)), 2) as MM from yourtable
```
You can have a timestamp like this:
```
select TIMESTAMP_FORMAT(cast(year_mont as varchar(6)), 'YYYYMM') as YouTimeStamp
from yourtable
```
Or a date too:
```
select Date(TIMESTAMP_FORMAT(cast(year_mont as varchar(6)), 'YYYYMM')) as YouTimeStamp
from yourtable
```
Upvotes: 2
|
2018/03/15
| 423 | 1,928 |
<issue_start>username_0: I have 3 activities: A, B and C. I'd like to launch C from A and send back the result to B using `onActivityResult()`:
* A launch C using `startActivityForResult()`
* C is launched and performs its task
* B received the result of C in `onActivityResult()`
Is it possible?<issue_comment>username_1: Its not directly possible because the result of Activity C will return to Activity A when C finishes.
If you want to open Activity B after Activity C send result to A, start the activity B from onActivityResult (when result comes from C to A), passing the data you received from C to B using A.
But if your Activity B is not related like above, you can store the result from Activity C in SQLite DB and then when activity opens read the result from SQLite and show in activity B
Upvotes: 2 [selected_answer]<issue_comment>username_2: ```
yes it is possible please do like this.
Intent intent=new Intent(MainActivity.this,ActivityC.class);
startActivityForResult(intent, 2);// Activity is started with
requestCode 2
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here
it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
//for here you can start your Activity B with data
whatever you want to send to Activity B.
}
}
```
and form Activity c set the result like
```
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(2,intent);
```
Upvotes: 0
|
2018/03/15
| 435 | 1,877 |
<issue_start>username_0: I have a table like this [like this](https://i.stack.imgur.com/OXus5.png)
I want to find top 2 most frequently occurring device ids with their counts.
```
device_id count
32145678665 3
3214567866555 4
```<issue_comment>username_1: Its not directly possible because the result of Activity C will return to Activity A when C finishes.
If you want to open Activity B after Activity C send result to A, start the activity B from onActivityResult (when result comes from C to A), passing the data you received from C to B using A.
But if your Activity B is not related like above, you can store the result from Activity C in SQLite DB and then when activity opens read the result from SQLite and show in activity B
Upvotes: 2 [selected_answer]<issue_comment>username_2: ```
yes it is possible please do like this.
Intent intent=new Intent(MainActivity.this,ActivityC.class);
startActivityForResult(intent, 2);// Activity is started with
requestCode 2
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here
it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
//for here you can start your Activity B with data
whatever you want to send to Activity B.
}
}
```
and form Activity c set the result like
```
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(2,intent);
```
Upvotes: 0
|
2018/03/15
| 427 | 1,885 |
<issue_start>username_0: How do I code a RADIX SORT in Python for different length of string with space?
For example my input is
```
["THE LORD","HELP", "WHO IS THAT"]
```
I would like to get
```
["HELP", "THE LORD", "WHO IS THAT"]
```
Thank you<issue_comment>username_1: Its not directly possible because the result of Activity C will return to Activity A when C finishes.
If you want to open Activity B after Activity C send result to A, start the activity B from onActivityResult (when result comes from C to A), passing the data you received from C to B using A.
But if your Activity B is not related like above, you can store the result from Activity C in SQLite DB and then when activity opens read the result from SQLite and show in activity B
Upvotes: 2 [selected_answer]<issue_comment>username_2: ```
yes it is possible please do like this.
Intent intent=new Intent(MainActivity.this,ActivityC.class);
startActivityForResult(intent, 2);// Activity is started with
requestCode 2
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here
it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
//for here you can start your Activity B with data
whatever you want to send to Activity B.
}
}
```
and form Activity c set the result like
```
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(2,intent);
```
Upvotes: 0
|
2018/03/15
| 483 | 1,872 |
<issue_start>username_0: I'm currently trying to learn react native. I created a project using create-react-native-app. After the project is created, I started npm start on the folder which shows the QR code. I've installed the expo app on my android phone and scanned the code but I'm getting a **Uncaught Error: Timed out, no manifest in cache** on my expo app and there is no stack trace given.
I've made it work a while ago but somehow its currently not working.
Im using windows 10.
npm 5.6
yarn 1.5.1<issue_comment>username_1: Expo only supports the most recent 6 versions, this is because we have to have all the native code for each version on the client and that gets big fast . As of writing this v26 is almost out, that version of the expo client will not support v19 projects. Please make sure that your app is up-to-date by going to the `app.json` (or `exp.json` depending on how old your project is ) and checking the version number.
Outside of that, I would also recommend you start your project by calling `exp start` in the root folder of your project
Upvotes: 0 <issue_comment>username_2: The problem that causes this is having multiple network connections. In my case, I have a virtual network connection which is used by the packager instead of the wifi connection. So basically what's happening is that my phone and my computer uses different connections. I've found a solution here: <https://github.com/react-community/create-react-native-app/issues/598>
Upvotes: 1 [selected_answer]<issue_comment>username_3: What I've done to fix it using Ubuntu was (I created my app using create-react-native-app):
1. open terminal
2. execute `ifconfig`
3. find network interface (wlp4s0, in my case)
4. execute `export REACT_NATIVE_PACKAGER_HOSTNAME="IP_FOUND_BEFORE"`
5. yarn start
6. SUCCESS! `Finished building JavaScript bundle in 10069ms`
Upvotes: 2
|
2018/03/15
| 680 | 2,587 |
<issue_start>username_0: I have two problem with my app:
1. I don't know how to retrieve the color of the small icon of notification when a notification arrives?
2. Can I edit app name that displayed at top of the notification by programmatically?
I'm using android Nougat .
[](https://i.stack.imgur.com/6GL4S.jpg)<issue_comment>username_1: This API seems to allow custom title and icon: <https://developer.android.com/reference/android/app/Notification.Builder.html>
Upvotes: 0 <issue_comment>username_2: You can use the below code to set smallIcon :(Use Small icon same color as Title Color)
Change color by [this site](https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html#foreground.type=image&foreground.space.trim=0&foreground.space.pad=0&foreColor=rgb(0%2C%200%2C%200)&backColor=rgb(0%2C%200%2C%200)&crop=0&backgroundShape=none&effects=none&name=ic_launcher)
```
.setSmallIcon(R.drawable.ic_launcher_icon)
```
[](https://i.stack.imgur.com/14Pyh.png)
**Reference Code :**
```
private void sendNotification(String messageBody,String message2, Bitmap image, String TrueOrFalse) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("AnotherActivity", TrueOrFalse);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
// .setLargeIcon(image)/*Notification icon image*/
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher_icon))
.setSmallIcon(R.drawable.ic_launcher_icon)
.setContentTitle(messageBody)
.setContentText(message2)
.setColor(getResources().getColor(R.color.colorAccent))
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
```
Upvotes: 1
|
2018/03/15
| 502 | 1,812 |
<issue_start>username_0: I keep on getting ES6 jshint warnings, for example:
''import' is only available in ES6 (use 'esversion: 6'). (W119)'
source: 'jshint'
code: 'W119'
I followed suggestions such as
1. Adding a .jshintrc file in the root with
{
"esversion": 6
}
2. Adding the following to the user and\or workspace settings:
"jshint.options":{
"esversion":6
}
But I still get the warning. Are there other things that I can do?
Thanks<issue_comment>username_1: [jsconfig.json file which defines the JavaScript target to be ES6](https://code.visualstudio.com/docs/languages/javascript)
I create a jsconfig.json file under my project directory and add codes in it:
```
{
"compilerOptions": {
"target": "ES6"
},
"exclude": [
"node_modules",
"**/node_modules/*"
]
}
```
Upvotes: 1 <issue_comment>username_1: Add a file .jshintrc into your project root, the warnings will disappear.
```
{
"esversion": 6
}
```
Upvotes: 5 <issue_comment>username_2: jsHint's ES6 warning can be solved easily by the following JSON code without creating any new file:
Paste the code inside the JSON editor of the "user settings".
`"jshint.options": { "esversion": 6 },`
Upvotes: 3 <issue_comment>username_3: According to the JSHint documentation: <https://jshint.com/docs/> "In addition to using configuration files you can configure JSHint from within your files using special comments. These comments start with a label such as jshint or globals..."
So, a /\* jshint esversion: 6 \*/ comment will work on the top of each file targeting ES6.
This have the advantage of you can switch these directives on and off per file or per function: "These comments are function scoped meaning that if you put them inside a function they will affect only this function's code."
Upvotes: 1
|
2018/03/15
| 508 | 1,878 |
<issue_start>username_0: I have an `angular 5 material checkbox` with a surrounding div and some other elements. I want a click on the `div` to be the same as a `click` directly on the `checkbox`.
Here is my example code:
```
I'm a not working checkbox :'(
I want to be clickable too
```
and a [Stackblitz](https://stackblitz.com/edit/angular-hyvsxv)
At the moment clicking on the checkbox itself is not working, clicking outside the div works. Any ideas?<issue_comment>username_1: Issue here is event of `Click` on `div` and `[(ngModel)]` on checkbox both nullify each other thats the reason its not working.
To make it work you need to `stopPropagation`, when you click on div element. so i did code as below `returning false` from div click event that stop it and you code will work.
[**Working Demo**](https://stackblitz.com/edit/angular-hyvsxv-vltuft)
component.ts
```
export class CheckboxConfigurableExample {
checked = false;
indeterminate = false;
align = 'start';
disabled = false;
onChecked() {
this.checked= !this.checked;
return false;
}
}
```
component.thml
```
Result
------
not working checkbox :'(
I want to be clickable too
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: You can also just do this
```
I'm a not working checkbox :'(
I want to be clickable too
```
Upvotes: 2 <issue_comment>username_3: You could do that:
```
I'm a not working checkbox :'(
I want to be clickable too
```
explanation:
Set a template variable for the checkbox - #myCheckbox, then prevent default behavior when clicking on checkbox so it wont contradict the action made by the div's click event.
On the div's click event just toggle the checkbox's state, and then if you want something to happen when the state is changed use the "someFunctionWhenChecked()" function to pass the new checkbox state.
Upvotes: 0
|
2018/03/15
| 638 | 2,009 |
<issue_start>username_0: I have a data in following JSON sort of format in which I am trying to only get the very last URL which in my following example is `https://lastexample.com/images/I/4162nAIaRCL.jpg` . Is there an easy way I can retrieve this via PHP?
```
{"https://example.com/images/I/4162nAIaRCL._SX425_.jpg":[425,425],
"https://example.com/images/I/4162nAIaRCL._SY355_.jpg":[355,355],
"https://example.com/images/I/4162nAIaRCL._SX466_.jpg":[466,466],
"https://example.com/images/I/4162nAIaRCL._SY450_.jpg":[450,450],
"https://lastexample.com/images/I/4162nAIaRCL.jpg":[500,500]}
```<issue_comment>username_1: Issue here is event of `Click` on `div` and `[(ngModel)]` on checkbox both nullify each other thats the reason its not working.
To make it work you need to `stopPropagation`, when you click on div element. so i did code as below `returning false` from div click event that stop it and you code will work.
[**Working Demo**](https://stackblitz.com/edit/angular-hyvsxv-vltuft)
component.ts
```
export class CheckboxConfigurableExample {
checked = false;
indeterminate = false;
align = 'start';
disabled = false;
onChecked() {
this.checked= !this.checked;
return false;
}
}
```
component.thml
```
Result
------
not working checkbox :'(
I want to be clickable too
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: You can also just do this
```
I'm a not working checkbox :'(
I want to be clickable too
```
Upvotes: 2 <issue_comment>username_3: You could do that:
```
I'm a not working checkbox :'(
I want to be clickable too
```
explanation:
Set a template variable for the checkbox - #myCheckbox, then prevent default behavior when clicking on checkbox so it wont contradict the action made by the div's click event.
On the div's click event just toggle the checkbox's state, and then if you want something to happen when the state is changed use the "someFunctionWhenChecked()" function to pass the new checkbox state.
Upvotes: 0
|
2018/03/15
| 657 | 2,286 |
<issue_start>username_0: I am new to c++ , I want to remove the maximum value in linked list. But I got the error message. Here is the function that removing the max value and return the value removed. While running the line "delete cur", I got the error message. Somebody help me please!
```
int removeMax(Dnode*& list) {
Dnode *p = list->next;
Dnode *cur = list;
int max = list->info;
while (p != NULL) {
if (p->info > max) {
max = p->info;
cur = p;
}
p = p->next;
}
if(cur->back == NULL && cur != NULL){
Dnode *after = cur->next;
after->back = NULL;
delete cur;
}
else if(cur->next == NULL && cur != NULL){
Dnode *pre = cur->back;
pre->next = NULL;
delete cur;
}
else{
Dnode *pre = cur->back;
Dnode *after = cur->next;
pre->next = cur->back;
after->back = pre;
delete cur;
}
return max;
```
}<issue_comment>username_1: Issue here is event of `Click` on `div` and `[(ngModel)]` on checkbox both nullify each other thats the reason its not working.
To make it work you need to `stopPropagation`, when you click on div element. so i did code as below `returning false` from div click event that stop it and you code will work.
[**Working Demo**](https://stackblitz.com/edit/angular-hyvsxv-vltuft)
component.ts
```
export class CheckboxConfigurableExample {
checked = false;
indeterminate = false;
align = 'start';
disabled = false;
onChecked() {
this.checked= !this.checked;
return false;
}
}
```
component.thml
```
Result
------
not working checkbox :'(
I want to be clickable too
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: You can also just do this
```
I'm a not working checkbox :'(
I want to be clickable too
```
Upvotes: 2 <issue_comment>username_3: You could do that:
```
I'm a not working checkbox :'(
I want to be clickable too
```
explanation:
Set a template variable for the checkbox - #myCheckbox, then prevent default behavior when clicking on checkbox so it wont contradict the action made by the div's click event.
On the div's click event just toggle the checkbox's state, and then if you want something to happen when the state is changed use the "someFunctionWhenChecked()" function to pass the new checkbox state.
Upvotes: 0
|
2018/03/15
| 704 | 2,439 |
<issue_start>username_0: I am trying to get this working from a long time now but cannot seem to get it right-
my x.html-
```
[Add Contract](#add)
{% include "a_bs3.html" with form_title="Add :" form_btn="Add" form_id="add" ajax="True" %}
$(document).ready(function() {
var check = location.hash;
if (check == "trigger") {
//button trigger even though you do not click on it
$('#addform').click();
}
});
```
I am trying to trigger this 'Add :' form button whenever the url contains a value "trigger" but the button is not auto-clicking, what am I doing wrong?
If you click 'Add :' manually- the form opens up just fine.<issue_comment>username_1: user jquery `trigger` function. `click` function is used to override the click event. That is not what you want. To trigger an event manually use [trigger](http://api.jquery.com/trigger/).
```
$(document).ready(function() {
var check = location.hash;
if (check == "#trigger") {
//triggering click event on #addform
$('#addform').trigger('click');
}
});
```
**SAMPLE CODE**
```js
$(document).ready(function() {
$("#clickME").click(function(){alert("clicked");});
$("select").change(function(){
if($(this).val() == 3){
$('#clickME').trigger('click');
}
});
});
```
```html
#### Clickable button
clickME
#### Select box.When 3 is selected, the click event will trigger
1
2
3
4
5
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I'd create a modular design that will enable you to update your `handler` object with a DOM ID and get an unlimited amount of buttons without conditionals for each and every one
```js
//key: the button id, value: a callback function
// this enables us the reuse functions outside the button scope.
const handlers = {
foo: () => {
alert("foo")
},
bar: () => {
alert("bar")
},
baz: () => {
alert("baz")
}
}
//bunding all our [data-actionable] buttons automatically
let $buttons = $("[data-actionable]");
$buttons.each((i, button) => {
$(button).on("click", handlers[button.dataset.actionable]);
})
//triggering the handler on change, regardless of the buttons - seperation of concerns.
$(".select").on("change", (e) => {
let target = e.currentTarget;
handlers[target.value].apply(null);
});
```
```css
.button {}
```
```html
foo
bar
baz
choose something...
foo
bar
baz
```
Upvotes: 0
|
2018/03/15
| 486 | 1,437 |
<issue_start>username_0: I have this given dataframe:
```
days classtype scores
1 1 a 49
2 1 b 47
3 2 a 36
4 2 b 41
```
It is produce by this given code:
```
days=c(1,1,2,2)
classtype=c("a","b","a","b")
scores=c(49,47,36,41)
myData=data.frame(days,classtype,scores)
print(myData)
```
What lines do I need to add to the code in order to get calculate the difference in scores of the two classes for each day? I want to get this output:
```
days difference_in_scores
1 1 2
2 2 -5
```<issue_comment>username_1: One approach you could take
```
library(dplyr)
library(reshape2)
days=c(1,1,2,2)
classtype=c("a","b","a","b")
scores=c(49,47,36,41)
myData=data.frame(days,classtype,scores)
myData %>%
# convert the data to wide format
dcast(days ~ classtype,
value.var = "scores") %>%
# calculate differences
mutate(difference_in_scores = a - b) %>%
# remove columns (just to match your desired output)
select(days, difference_in_scores)
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: If the format of your data is consistently as you have shown then you can accomplish this very neatly using `data.table`:
```
setDT(myData)
myData[, diff(scores), by = days]
days V1
1: 1 -2
2: 2 5
```
Or using just **base-R**:
```
aggregate(scores ~ days, myData, FUN = diff)
```
Upvotes: 2
|
2018/03/15
| 723 | 2,368 |
<issue_start>username_0: I have a cpu intensive task in JavaScript that is blocking the VM while executing within a `Promise`:
An example could be the following (try it out in the browser):
```
function task() {
return new Promise((r,s) => {
for(var x=0; x < 1000000*1000000; x++) {
var Y = Math.sqrt(x/2)
}
return r(true)
})
}
```
I would like to avoid the VM main thread to be blocked, so I have tried to detach using a `setTimeout` in the `Promise` passing the `resolve` and `reject` as context like:
```
function task() {
return new Promise((r,s) => {
var self=this;
setTimeout( function(r,s) {
for(var x=0; x < 1000000*1000000; x++) {
var Y = Math.sqrt( Math.sin (x/2) + Math.cos(x/2))
}
return r(true);
},500,r,s);
})
}
```
but with no success. Any idea how to avoid the main thread to be stuck?<issue_comment>username_1: You can use "Web Workers". That way, you stay conform with standard. This will basically be a background thread (for example like BackgroundWorker in older C#).
* [MDN Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
* [Using Web Workers to Speed-Up Your JavaScript Applications](http://blog.teamtreehouse.com/using-web-workers-to-speed-up-your-javascript-applications)
I am not sure if current node.js supports this nativly, so use
[npm web workers package](https://www.npmjs.com/package/webworker-threads)
Upvotes: 1 <issue_comment>username_2: In addition to using web workers or similar, you can also (depending on the task) break up the work into smaller chunks that are worked on and scheduled using `setImmediate`. This example is a little silly, but you get the idea.
```
function brokenUpTask() {
let x = 0; // Keep track of progress here, not in the loop.
const limit = 1000000;
const chunk = 100000;
return new Promise((resolve) => {
function tick() { // Work a single chunk.
let chunkLimit = Math.min(x + chunk, limit);
for(x = 0; x < chunkLimit; x++) {
var Y = Math.sqrt(x/2);
}
if(x === limit) { // All done?
resolve(true);
return;
}
setImmediate(tick); // Still work to do.
}
tick(); // Start work.
});
}
brokenUpTask().then(() => console.log('ok'));
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 527 | 1,864 |
<issue_start>username_0: My client want to use **GMail API** for their existing web application using **their own domain**. So they can send automatic e-mail from their mail server. The code they are using is in plain PHP. Is this possible? Can anyone show me the step-by-step tutorial for this? Thank you very much
[EDIT]
So they want to send e-mail whose sender is like this: <EMAIL><issue_comment>username_1: You can use "Web Workers". That way, you stay conform with standard. This will basically be a background thread (for example like BackgroundWorker in older C#).
* [MDN Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
* [Using Web Workers to Speed-Up Your JavaScript Applications](http://blog.teamtreehouse.com/using-web-workers-to-speed-up-your-javascript-applications)
I am not sure if current node.js supports this nativly, so use
[npm web workers package](https://www.npmjs.com/package/webworker-threads)
Upvotes: 1 <issue_comment>username_2: In addition to using web workers or similar, you can also (depending on the task) break up the work into smaller chunks that are worked on and scheduled using `setImmediate`. This example is a little silly, but you get the idea.
```
function brokenUpTask() {
let x = 0; // Keep track of progress here, not in the loop.
const limit = 1000000;
const chunk = 100000;
return new Promise((resolve) => {
function tick() { // Work a single chunk.
let chunkLimit = Math.min(x + chunk, limit);
for(x = 0; x < chunkLimit; x++) {
var Y = Math.sqrt(x/2);
}
if(x === limit) { // All done?
resolve(true);
return;
}
setImmediate(tick); // Still work to do.
}
tick(); // Start work.
});
}
brokenUpTask().then(() => console.log('ok'));
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 2,496 | 5,224 |
<issue_start>username_0: Sample data
```
dat <- data.table(yr = c(2013,2013,2013,2013,2013,2013,2013,2013,2013,2013,2012,2012,2012,2012,2012,2012,2012,2012,2012,2012,2012),
location = c("Bh","Bh","Bh","Bh","Bh","Go","Go","Go","Go","Go","Bh","Bh","Bh","Bh","Bh","Bh","Go","Go","Go","Go","Go"),
time.period = c("t4","t5","t6","t7","t8","t3","t4","t5","t6","t7","t3","t4","t5","t6","t7","t8","t3","t4","t5","t6","t7"),
period = c(20,21,22,23,24,19,20,21,22,23,19,20,21,22,23,24,19,20,21,22,23),
value = c(runif(21)))
key <- data.table(time.period = c("t1","t2","t3","t4","t5","t6","t7","t8","t9","t10"),
period = c(17,18,19,20,21,22,23,24,25,26))
```
`key` provide for each `time.period` the associated `period`
In the data table `dat`, for each `location` and `yr`, I want to insert additional rows if a pair of `time.period` and `period` is missing
For eg. for location `Bh` and `yr` 2013
```
dat[location == "Bh" & yr == 2013,]
yr location time.period period value
1: 2013 Bh t4 20 0.7167561
2: 2013 Bh t5 21 0.5659722
3: 2013 Bh t6 22 0.8549229
4: 2013 Bh t7 23 0.1046213
5: 2013 Bh t8 24 0.8144670
```
I want to do:
```
yr location time.period period value
1: 2013 Bh t1 17 0
1: 2013 Bh t2 18 0
1: 2013 Bh t3 19 0
1: 2013 Bh t4 20 0.7167561
2: 2013 Bh t5 21 0.5659722
3: 2013 Bh t6 22 0.8549229
4: 2013 Bh t7 23 0.1046213
5: 2013 Bh t8 24 0.8144670
1: 2013 Bh t9 25 0
1: 2013 Bh t10 26 0
```
I tried this:
```
dat %>% group_by(location,yr) %>% complete(period = seq(17, max(26), 1L))
A tibble: 40 x 5
Groups: location, yr [4]
location yr period time.period value
1 Bh 2012 17 NA
2 Bh 2012 18 NA
3 Bh 2012 19 t3 0.46757583
4 Bh 2012 20 t4 0.07041745
5 Bh 2012 21 t5 0.58707367
6 Bh 2012 22 t6 0.83271673
7 Bh 2012 23 t7 0.76918731
8 Bh 2012 24 t8 0.25368225
9 Bh 2012 25 NA
10 Bh 2012 26 NA
# ... with 30 more rows
```
As you can see, the `time.period` is not fill. How do I fill that column as well?<issue_comment>username_1: Do you need something like this?
```
x <- merge(dat, key, by = "time.period", all.y = T)
x[is.na(x)] <- 0
```
Upvotes: 0 <issue_comment>username_2: Since you are using `data.table`, you can do the following:
```
dat_new <- dat[,.SD[key, on='time.period'],.(location, yr)]
dat_new[, period := i.period][, i.period := NULL]
dat_new[is.na(value), value := 0]
print(head(dat_new), 10)
location yr time.period period value
1: Bh 2013 t1 17 0.0000000
2: Bh 2013 t2 18 0.0000000
3: Bh 2013 t3 19 0.0000000
4: Bh 2013 t4 20 0.9255600
5: Bh 2013 t5 21 0.3816035
6: Bh 2013 t6 22 0.5202268
7: Bh 2013 t7 23 0.5326466
8: Bh 2013 t8 24 0.5091590
9: Bh 2013 t9 25 0.0000000
10: Bh 2013 t10 26 0.0000000
```
**Explanation:**
1.First, we join the `key` dataframe with each group of `.(location, yr)` in dat.
2. This adds the column key dataframe as `i.period`.
3. Finally, we set NA as 0 and drop `i.period` column after we set `period := i.period`.
Upvotes: 2 <issue_comment>username_3: `tidyr::complete` can be used to find a solution.
```
library(dplyr)
library(tidyr)
dat %>% complete(yr, location, key, fill = list(value = 0)) )
# # A tibble: 40 x 5
# yr location time.period period value
#
# 1 2012 Bh t1 17.0 0
# 2 2012 Bh t2 18.0 0
# 3 2012 Bh t3 19.0 0.177
# 4 2012 Bh t4 20.0 0.687
# 5 2012 Bh t5 21.0 0.384
# 6 2012 Bh t6 22.0 0.770
# 7 2012 Bh t7 23.0 0.498
# 8 2012 Bh t8 24.0 0.718
# 9 2012 Bh t9 25.0 0
# 10 2012 Bh t10 26.0 0
# # ... with 30 more rows
```
**Data**
```
dat <- data.table(yr = c(2013,2013,2013,2013,2013,2013,2013,2013,2013,2013,2012,2012,2012,2012,2012,2012,2012,2012,2012,2012,2012),
location = c("Bh","Bh","Bh","Bh","Bh","Go","Go","Go","Go","Go","Bh","Bh","Bh","Bh","Bh","Bh","Go","Go","Go","Go","Go"),
time.period = c("t4","t5","t6","t7","t8","t3","t4","t5","t6","t7","t3","t4","t5","t6","t7","t8","t3","t4","t5","t6","t7"),
period = c(20,21,22,23,24,19,20,21,22,23,19,20,21,22,23,24,19,20,21,22,23),
value = c(runif(21)))
key <- data.table(time.period = c("t1","t2","t3","t4","t5","t6","t7","t8","t9","t10"),
period = c(17,18,19,20,21,22,23,24,25,26))
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 294 | 1,198 |
<issue_start>username_0: I want to create a function for a push notification but when I try to upload new function then the previous function which is for different purpose is being deleted . I don't know why currently I have 3 functions. [This is the screenshot of my node js](https://i.stack.imgur.com/FiT9C.png)<issue_comment>username_1: Most likely you renamed the previous function in the index file.
That would show up as a "delete" prompt when deploying.
If that is not the case, please include the index.js / index.ts file.
Upvotes: 0 <issue_comment>username_2: This is the way deployments with the Firebase CLI work by default. Every time you deploy, all the functions you deploy completely replace any other functions you previously deployed.
If you want to deploy only certain functions without replacing everything, you need to specify that on the command line [as described in the documentation](https://firebase.google.com/docs/cli/#partial_deploys):
>
> When deploying functions, you can target specific ones:
>
>
>
> ```
> firebase deploy --only functions:function1
> firebase deploy --only functions:function1,functions:function2
>
> ```
>
>
Upvotes: 3 [selected_answer]
|
2018/03/15
| 290 | 1,160 |
<issue_start>username_0: On crystal report, I've to place logo based on price.
If price > 0 ,logo will not display, otherwise logo will appear.
How Can I do this?
I believe I've to write the formula against image subpress method. any idea?
please note image name picture1 .<issue_comment>username_1: Most likely you renamed the previous function in the index file.
That would show up as a "delete" prompt when deploying.
If that is not the case, please include the index.js / index.ts file.
Upvotes: 0 <issue_comment>username_2: This is the way deployments with the Firebase CLI work by default. Every time you deploy, all the functions you deploy completely replace any other functions you previously deployed.
If you want to deploy only certain functions without replacing everything, you need to specify that on the command line [as described in the documentation](https://firebase.google.com/docs/cli/#partial_deploys):
>
> When deploying functions, you can target specific ones:
>
>
>
> ```
> firebase deploy --only functions:function1
> firebase deploy --only functions:function1,functions:function2
>
> ```
>
>
Upvotes: 3 [selected_answer]
|
2018/03/15
| 424 | 1,521 |
<issue_start>username_0: I want to execute this statement only if all these 3 following conditions are true:
1. flavor is "vanilla" or "chocolate"
2. vessel is "cone" or "bowl"
3. toppings is "sprinkles" or "peanuts"
**my code**
```
if ((flavor == "vanilla" || "chocolate") && (vessel == "cone" || "bowl") && (toppings == "sprinkles" || "peanuts")){
console.log("I'd like two scoops of "+ flavor +" ice cream in a "+ vessel +" with "+toppings);
} else {
console.log("I don't wanna eat ice cream");
}
```
when i run this program it always execute the if statement no matter what flavor, vessel i put in the values. why?<issue_comment>username_1: Most likely you renamed the previous function in the index file.
That would show up as a "delete" prompt when deploying.
If that is not the case, please include the index.js / index.ts file.
Upvotes: 0 <issue_comment>username_2: This is the way deployments with the Firebase CLI work by default. Every time you deploy, all the functions you deploy completely replace any other functions you previously deployed.
If you want to deploy only certain functions without replacing everything, you need to specify that on the command line [as described in the documentation](https://firebase.google.com/docs/cli/#partial_deploys):
>
> When deploying functions, you can target specific ones:
>
>
>
> ```
> firebase deploy --only functions:function1
> firebase deploy --only functions:function1,functions:function2
>
> ```
>
>
Upvotes: 3 [selected_answer]
|
2018/03/15
| 387 | 1,543 |
<issue_start>username_0: Right now I've got two tables `"Category"` and `"Product"`.
I made `'category_id'` in `"Product"` to be equal `'id'` in `Category`, so now in my view it shows all products of that category. But now I need one product to be in several categories.
In controller I use the following data provider:
```
$dataProvider = new ActiveDataProvider([
'query' => $query = Product::find()->where(['category_id' => $cats->id]),
'sort'=>array(
'defaultOrder'=>['id' => SORT_ASC],
),
'pagination' => [
'pageSize' => 9,
],
]);
```
Any suggestions on how to realise this feature?<issue_comment>username_1: Most likely you renamed the previous function in the index file.
That would show up as a "delete" prompt when deploying.
If that is not the case, please include the index.js / index.ts file.
Upvotes: 0 <issue_comment>username_2: This is the way deployments with the Firebase CLI work by default. Every time you deploy, all the functions you deploy completely replace any other functions you previously deployed.
If you want to deploy only certain functions without replacing everything, you need to specify that on the command line [as described in the documentation](https://firebase.google.com/docs/cli/#partial_deploys):
>
> When deploying functions, you can target specific ones:
>
>
>
> ```
> firebase deploy --only functions:function1
> firebase deploy --only functions:function1,functions:function2
>
> ```
>
>
Upvotes: 3 [selected_answer]
|
2018/03/15
| 296 | 1,032 |
<issue_start>username_0: The import `org.hamcrest.Matchers.hasProperty` cannot be resolved in JUnit4.12.
What is the alternative to use `hasProperty`?<issue_comment>username_1: Hamcrest is not embedded in JUnit 4.12, instead you'll need to include the separate Hamcrest library on your classpath.
If you are using Maven you can do this by including the following dependency in your `pom.xml`:
```
org.hamcrest
hamcrest-library
1.3
test
```
Alternatively you can download the JAR from [Maven Central](http://search.maven.org/remotecontent?filepath=org/hamcrest/hamcrest-library/1.3/hamcrest-library-1.3.jar).
Upvotes: 4 [selected_answer]<issue_comment>username_2: In case you only need it for UnitTests you can use following dependency (works with JUnit5 as well):
```
org.hamcrest
hamcrest-junit
2.0.0.0
test
```
Upvotes: 2 <issue_comment>username_3: Use this import if you are not able to use the hamcrest "equalTo" method.
import static org.hamcrest.Matchers.equalTo;
body("scope", equalTo("APP"));
Upvotes: 0
|
2018/03/15
| 2,273 | 6,881 |
<issue_start>username_0: I import data from excel using xlrd. After coverting it to JSON and loading, the data format looks like this:
```
[{'receipt_id': '1', 'service': 'A', 'charge': '2000', 'company': 'Company A'},
{'receipt_id': '1', 'service': 'B', 'charge': '3000', 'company': 'Company A'},
{'receipt_id': '2', 'service': 'C', 'charge': '1000', 'company': 'Company B'}]
```
How can I merge the lines that have same receipt\_id, to make a new list like this:
```
[{'receipt_id': '1', 'service': 'A 2000 B 3000', 'charge': '5000', 'company': 'Company A'},
{'receipt_id': '2', 'service': 'C', 'charge': '1000', 'company': 'Company B'}]
```
I've tried changing this list into dict, but I still got some problems. Any int how to get it done?<issue_comment>username_1: Used Pandas dataframe.
```
aa=[{'receipt_id': '1', 'service': 'A', 'charge': '2000', 'company': 'Company A'},
{'receipt_id': '1', 'service': 'B', 'charge': '3000', 'company': 'Company A'},
{'receipt_id': '2', 'service': 'C', 'charge': '1000', 'company': 'Company B'}]
df = pd.DataFrame(aa)
def add_service(x):
return " ".join(x)
def add_charge(x):
#results = map(int, x) # In py2
results = list(map(int, x)) #In py3:
return sum(results)
def add_comp(x):
a = list(set(x))
return " ".join(a)
grouped = df.groupby(['receipt_id'])
ser = grouped['service'].agg(add_service)
cha = grouped['charge'].agg(add_charge)
com = grouped['company'].agg(add_comp)
df_new = pd.DataFrame({"service": ser, "charge": cha, "company": com})
list(df_new.T.to_dict().values()) # To get json format
```
Upvotes: 1 <issue_comment>username_2: If you don't want to use `pandas`, you can write your own `group_by` function:
```
from collections import defaultdict
def group_by(dicts, key):
out = defaultdict(list)
for d in dicts:
out[d[key]].append(d)
return out
def combine_receipts(receipts):
for receipt_id, receipts in group_by(receipts, 'receipt_id').items():
if len(receipts) > 1:
service = ' '.join(f"{r['service']} {r['charge']}" for r in receipts)
charge = str(sum(float(r['charge']) for r in receipts))
yield {'receipt_id': receipt_id,
'service': service,
'charge': charge,
'company': receipts[0]['company']}
elif len(receipts) == 1:
yield receipts[0]
else:
raise RuntimeError("empty group")
if __name__ == "__main__":
receipts = [{'receipt_id': '1', 'service': 'A', 'charge': '2000', 'company': 'Company A'},
{'receipt_id': '1', 'service': 'B', 'charge': '3000', 'company': 'Company A'},
{'receipt_id': '2', 'service': 'C', 'charge': '1000', 'company': 'Company B'}]
print(list(combine_receipts(receipts)))
# [{'receipt_id': '1', 'service': 'A 2000 B 3000', 'charge': '5000.0', 'company': 'Company A'},
# {'receipt_id': '2', 'service': 'C', 'charge': '1000', 'company': 'Company B'}]
```
Upvotes: 1 [selected_answer]<issue_comment>username_3: You can try something like this.
```
data=[{'receipt_id': '1', 'service': 'A', 'charge': '2000', 'company': 'Company A'},
{'receipt_id': '1', 'service': 'B', 'charge': '3000', 'company': 'Company A'},
{'receipt_id': '2', 'service': 'C', 'charge': '1000', 'company': 'Company B'}]
new_dict={}
for i in data:
if i['receipt_id'] not in new_dict:
new_dict[i['receipt_id']]=[i]
else:
new_dict[i['receipt_id']][0]['charge']=int(new_dict[i['receipt_id']][0]['charge'])+int(i['charge'])
new_dict[i['receipt_id']][0]['service']="{} {} {} {}".format(str(new_dict[i['receipt_id']][0]['service']),str(new_dict[i['receipt_id']][0]['charge']),str(i['service']),str(i['charge']))
print([j[0] for i,j in new_dict.items()])
```
output:
```
[{'company': 'Company A', 'service': 'A 5000 B 3000', 'charge': 5000, 'receipt_id': '1'}, {'company': 'Company B', 'service': 'C', 'charge': '1000', 'receipt_id': '2'}]
```
Upvotes: 0 <issue_comment>username_4: First combine all the `receipt_id` values using a `defaultdict(list)` and then build the output list by combining the necessary items:
```
from collections import defaultdict
combined = defaultdict(list)
data = [
{'receipt_id': '1', 'service': 'A', 'charge': '2000', 'company': 'Company A'},
{'receipt_id': '1', 'service': 'B', 'charge': '3000', 'company': 'Company A'},
{'receipt_id': '2', 'service': 'C', 'charge': '1000', 'company': 'Company B'}]
for d in data:
combined[d['receipt_id']].append(d)
output = []
for id, items in combined.items():
services = [d['service'] for d in items]
charges = [int(d['charge']) for d in items]
companies = {d['company'] for d in items}
service = ' '.join('{} {}'.format(s, c) for s, c in zip(services, charges))
output.append({'receipt_id':id, 'service':service, 'charge':str(sum(charges)), 'company':' '.join(companies)})
print(output)
```
This would give you:
```none
[
{'receipt_id': '1', 'service': 'A 2000 B 3000', 'charge': '5000', 'company': 'Company A'},
{'receipt_id': '2', 'service': 'C 1000', 'charge': '1000', 'company': 'Company B'}
]
```
Note, if the `company` entry also differs, this is also shown.
Upvotes: 0 <issue_comment>username_5: I think this should work. I used defaultdict to group the duplicates and process according to the requirement.
```
from collections import defaultdict
def group_duplicates(data, index):
groups = defaultdict(list)
for obj in data:
groups[obj[index]].append(obj)
return groups.values()
def process_duplicates(duplicate_data):
new_list = []
for objects in duplicate_data:
fist_element = (objects[0])
merged_element = fist_element
service = ''
charge = 0
for obj in objects:
if len(objects) > 1:
service += obj['service'] + ' ' + obj['charge'] + ' '
else:
service = obj['service']
charge += int( obj['charge'])
merged_element['service'] = service.strip()
merged_element['charge'] = str(charge)
new_list.append(merged_element)
return new_list
def main():
receipts = [{'receipt_id': '1', 'service': 'A', 'charge': '2000', 'company': 'Company A'},
{'receipt_id': '1', 'service': 'B', 'charge': '3000', 'company': 'Company A'},
{'receipt_id': '2', 'service': 'C', 'charge': '1000', 'company': 'Company B'}]
grouped_receipts = group_duplicates(receipts, 'receipt_id')
merged_receipts = process_duplicates(grouped_receipts)
print(merged_receipts)
if __name__ == '__main__':
main()
```
output
```
[{'receipt_id': '1', 'service': 'A 2000 B 3000', 'charge': '5000', 'company': 'Company A'}, {'receipt_id': '2', 'service': 'C', 'charge': '1000', 'company': 'Company B'}]
```
Upvotes: 0
|
2018/03/15
| 691 | 2,404 |
<issue_start>username_0: To give some context to the title, let's say I have an array of INTs. So, for example (1,2,3,4,5).
Each number in the array represents a char in a string. So if the string is hello then array[3] is going to represent "l".
What is the most efficient or simplest way to remove a char from a string, replace the char and then add it back into the string?
So using the example above I could change "l" to "d", add it back to the string so my final string is "hedlo".
here is part of my code:
method used for max:
```
public static int getMax(int[] inputArray){
int maxValue = inputArray[0];
for(int i=1;i < inputArray.length;i++){
if(inputArray[i] > maxValue){
maxValue = inputArray[i];
}
}
return maxValue;
}
```
here is the code for using the max value in the array as the position in the string results to edit. The char to edit should be replaced with an "m" in the actual case
```
int max = getMax(array);
results.setCharAt(max, 'm');
String result = results.toString();
```<issue_comment>username_1: Yes, it can easiyl be done. Below I have some code from <https://stackoverflow.com/a/4576556/9354346>
```
StringBuilder str = new StringBuilder("hello");
str.setCharAt(2, 'd');
String result = str.toString();
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Without knowing why you're doing this, I'm not sure exactly what to recommend but here's something to think about. ASCII characters have numerical values associated with them. [Table.](https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html)
If you cast an int to a char, it will convert it to that value. So like,
```
char c = (char) 97;
```
would evaluate to 'a.' If you want 'a' to start at 1, you could just add 96 to everything.
To convert, you could add to an int the difference in the table. So from 'a' to 'd', add 3.
EDIT:
I answered this assuming you were changing an array of ints that was representing a string. Re-reading the question, I'm not sure that's what you're doing! If you need to change a character of a string to a different character, you can use the substring function to grab characters before the change, and after the change and put the new character in the middle.
```
String x = "Hello";
x = x.substring(0,2) + 'd' + x.substring(3);
```
This makes x say "Hedlo."
Upvotes: 0
|
2018/03/15
| 452 | 1,524 |
<issue_start>username_0: I am trying to access the AWS ETL Glue job id from the script of that job. This is the RunID that you can see in the first column in the AWS Glue Console, something like `jr_5fc6d4ecf0248150067f2`. How do I get it programmatically with pyspark?<issue_comment>username_1: You can use [boto3](http://boto3.readthedocs.io/en/latest/reference/services/glue.html) SDK for python to access the AWS services
```
import boto3
def lambda_handler(event, context):
client = boto3.client('glue')
client.start_crawler(Name='test_crawler')
glue = boto3.client(service_name='glue', region_name='us-east-2',
endpoint_url='https://glue.us-east-2.amazonaws.com')
myNewJobRun = client.start_job_run(JobName=myJob['Name'])
print myNewJobRun['JobRunId']
```
Upvotes: -1 <issue_comment>username_2: As it's documented in <https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-extensions-get-resolved-options.html>, it's passed in as a command line argument to the Glue Job. You can access the `JOB_RUN_ID` and other default/reserved or custom job parameters using `getResolvedOptions()` function.
```
import sys
from awsglue.utils import getResolvedOptions
args = getResolvedOptions(sys.argv)
job_run_id = args['JOB_RUN_ID']
```
**NOTE:** `JOB_RUN_ID` is a default identity parameter, we don't need to include it as part of `options` (the second argument to `getResolvedOptions()`) for getting its value during runtime in a Glue Job.
Upvotes: 6 [selected_answer]
|
2018/03/15
| 1,222 | 3,751 |
<issue_start>username_0: I'm trying to deploy a django project with the following Apache configuration:
**Apache virtualhost configuration**
```
DocumentRoot /var/www/project/backend
ErrorLog ${APACHE\_LOG\_DIR}/error.log
CustomLog ${APACHE\_LOG\_DIR}/access.log combined
WSGIDaemonProcess backend python-home=/var/www/project/myenv python-path=/var/www/gestor\_documental/backend
WSGIProcessGroup backend
WSGIScriptAlias / /var/www/project/backend/backend/wsgi.py process-group=backend
Alias /static/ /var/www/project/backend/static/
Require all granted
```
**wsgi.load file**
```
LoadModule wsgi_module "/var/www/project/myenv/lib/python3.5/site-packages/mod_wsgi/server/mod_wsgi-py35.cpython-35m-x86_64-linux-gnu.so"
WSGIPythonHome "/var/www/project/myenv"
```
The wsgi.py is the one django brings by default
**wsgi.py**
```
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")
application = get_wsgi_application()
```
**This is the project tree:**
```
project
|- backend
| |- api (django app)
| |- backend
| |- ...
| |- settings.py
| |- wsgi.py
|-- myenv (virtualenv)
```
**And this is the error log I keep getting when i try to load the web:**
```
mod_wsgi (pid=38953): Failed to exec Python script file '/var/www/project/backend/backend/wsgi.py'.
mod_wsgi (pid=38953): Exception occurred processing WSGI script '/var/www/project/backend/backend/wsgi.py'.
Traceback (most recent call last):
File "/var/www/project/backend/backend/wsgi.py", line 16, in
application = get\_wsgi\_application()
File "/var/www/project/myenv/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get\_wsgi\_application
django.setup(set\_prefix=False)
File "/var/www/project/myenv/lib/python3.5/site-packages/django/\_\_init\_\_.py", line 22, in setup
configure\_logging(settings.LOGGING\_CONFIG, settings.LOGGING)
File "/var/www/project/myenv/lib/python3.5/site-packages/django/conf/\_\_init\_\_.py", line 53, in \_\_getattr\_\_
self.\_setup(name)
File "/var/www/project/myenv/lib/python3.5/site-packages/django/conf/\_\_init\_\_.py", line 41, in \_setup
self.\_wrapped = Settings(settings\_module)
File "/var/www/project/myenv/lib/python3.5/site-packages/django/conf/\_\_init\_\_.py", line 97, in \_\_init\_\_
mod = importlib.import\_module(self.SETTINGS\_MODULE)
File "/var/www/project/myenv/lib/python3.5/importlib/\_\_init\_\_.py", line 126, in import\_module
return \_bootstrap.\_gcd\_import(name[level:], package, level)
File "", line 986, in \_gcd\_import
File "", line 969, in \_find\_and\_load
File "", line 944, in \_find\_and\_load\_unlocked
File "", line 222, in \_call\_with\_frames\_removed
File "", line 986, in \_gcd\_import
File "", line 969, in \_find\_and\_load
File "", line 956, in \_find\_and\_load\_unlocked
ImportError: No module named 'backend'
```
I've followed every single tutorial and try tons of configurations but still getting the same error.
I'm using **python 3.5.2** in a virtualenv and **Apache 2.4.18**
I've installed mod\_wsgi via pip3.
Could someone help me with this and tell me what am i doing wrong?
Thank you.<issue_comment>username_1: Its this line in the `wsgi.py`:
```
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")
```
There's no `backend.settings` in `project/backend/backend`.
It's trying to find a third backend folder, so remove `backend` from that line.
Upvotes: 2 <issue_comment>username_2: I solved it changing the `wsgi.py` file adding the next lines:
```
import sys
sys.path.append('/var/www/project/backend')
```
I don't know if this is the correct answer but it actually worked with this workaround.
Upvotes: 4 [selected_answer]
|
2018/03/15
| 311 | 933 |
<issue_start>username_0: ```
var array= [
{"Name":"Test", "Status":{"Id":100, "Alias":"A"}},
{"Name":"Test2", "Status":{"Id":101, "Alias":"B"}},
{"Name":"Test3", "Status":{"Id":102, "Alias":"C"}}
];
```
How to loop throw value of array of Name and Id in JavaScript?<issue_comment>username_1: You can't use array as variable so replace to `arr` and try following,
```js
var arr = [
{"Name":"Test", "Status":{"Id":100, "Alias":"A"}},
{"Name":"Test2", "Status":{"Id":101, "Alias":"B"}},
{"Name":"Test3", "Status":{"Id":102, "Alias":"C"}}
];
arr.forEach(function(item){
console.log('Name: ' + item.Name);
console.log('Status Id: ' + item.Status.Id);
console.log('Status Alias: ' + item.Status.Alias);
});
```
Upvotes: 0 <issue_comment>username_2: ```
array.forEach(item => console.log(item.Name))
array.forEach(item => console.log(item.Status.Id))
```
Upvotes: 2 [selected_answer]
|
2018/03/15
| 648 | 2,420 |
<issue_start>username_0: My property isLoading is a Boolean on state that I check to determine if the body of my render code is ready to be executed or should wait with a spinning loader. When I examine state in the debugger isLoading is a boolean as it should be but when I further examine just isLoading it is undefined. And this is within the same break point (I have done nothing else other than move my mouse to hover over a different property 1 second away). This is really messing up my code as the isLoading property is then undefined for my if statement right below it, thus it's not waiting on my code to be ready. Can anyone tell me why my isLoading property would be undefined even though when I look at state it's a Boolean??
```
render() {
const {isLoading} = this.state.isLoading;
if (isLoading) {
return ();
}
```
[](https://i.stack.imgur.com/7cOAE.png)
[](https://i.stack.imgur.com/773p6.png)
[](https://i.stack.imgur.com/XjYpN.png)<issue_comment>username_1: use it this way `const {isLoading} = this.state`
that way your putting isLoading of isLoading in cont variable wich is undefined
Upvotes: 0 <issue_comment>username_2: isLoading does not actually exist, you probably ment something like this:
```
if (this.state.isLoading)
```
but you could also do object deconstructing by doing
```
const {isLoading} = this.state
```
then:
```
if(isLoading)
```
Upvotes: 1 <issue_comment>username_3: the issue is with your `const {isLoading} = this.state.isLoading;`
it need to be `const {isLoading} = this.state;`
because according to your code `const {isLoading} = this.state.isLoading;` mean `this.state.isLoading.isLoading` wish return an undefined value
this should work fine
```
render() {
const {isLoading} = this.state;
if (isLoading) {
return ();
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_4: ```
> const {isLoading} = this.state;
```
This should be the syntax. The above is known as destructuring and was introduced in ES6. In the above syntax, the variable is assigned the value of isLoading from component's state.
What you are trying to do will search for another isLoading within `this.state.isLoading`.
Upvotes: 0
|
2018/03/15
| 984 | 3,453 |
<issue_start>username_0: I need to generate a random number between 0 and 1 in C#. It doesn't need to be more accurate than to a single decimal place but it's not a problem if it is.
I can either do `Random.Next(0, 10) / 10.0` or `Random.NextDouble()`.
I could not find any concrete information on the time complexity of either method. I assume `Random.Next()` will be more efficient as in Java, however the addition of the division (the complexity of which would depend on the method used by C#) complicates things.
Is it possible to find out which is more efficient purely from a theoretical standpoint? I realise I can time both over a series of tests, but want to understand why one has better complexity than the other.<issue_comment>username_1: Either way, you'll be able to generate many many millions, if not billions, of random numbers every second. Do you really need that many?
On a more concrete level, both variants have time complexity `O(1)`, meaning that you could measure the time difference between the two methods and that would be it.
```
Random generator = new Random();
int count = 1_000_000;
Stopwatch sw = new Stopwatch();
sw.Start();
double res;
for (int i = 0; i < count; i++)
res = generator.Next(0, 10) / 10.0;
sw.Stop();
Stopwatch sw1 = new Stopwatch();
sw1.Start();
for (int i = 0; i < count; i++)
res = generator.NextDouble();
sw1.Stop();
Console.WriteLine($"{sw.ElapsedMilliseconds} - {sw1.ElapsedMilliseconds}");
```
This code prints 44 msec : 29 msec on my computer. And again - I don't think that you should optimize an operation which takes 44 milliseconds on a million executions.
If 15 nanoseconds per execution still makes the difference, then the second method is one tiny bit faster.
Upvotes: 2 <issue_comment>username_2: Looking at the [implmenentation source code](https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/random.cs), `NextDouble()` will be more efficient.
[`NextDouble()`](https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/random.cs#L195-L197) simply calls the [`Sample()`](https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/random.cs#L94-L119) method:
```
public virtual double NextDouble() {
return Sample();
}
```
[`Next(maxValue)`](https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/random.cs#L181-L187) performs a comparison on maxvalue, calls `Sample()`, multiplies the value by maxvalue, converts it to `int` and returns it:
```
public virtual int Next(int maxValue) {
if (maxValue<0) {
throw new ArgumentOutOfRangeException("maxValue", Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", "maxValue"));
}
Contract.EndContractBlock();
return (int)(Sample()*maxValue);
}
```
So, as you can see, `Next(maxValue)` is doing the same work as `NextDouble()` and then doing some more, so `NextDouble()` will be more efficient in returning a number between 0 and 1.
For Mono users, you can see [`NextDouble()`](https://github.com/mono/mono/blob/master/mcs/class/Mono.C5/C5/Random.cs#L62-L65) and [`Next(maxValue)`](https://github.com/mono/mono/blob/master/mcs/class/Mono.C5/C5/Random.cs#L94-L100) implementations here. Mono does it a little differently, but it basically involves the same steps as the official implementation.
As Zoran says, you would need to be generating a huge amount of random numbers to notice a difference.
Upvotes: 2
|
2018/03/15
| 548 | 1,900 |
<issue_start>username_0: I'm trying to export my data from a ViewController to another with this code:
```
func prepare(for: UIStoryboardSegue, sender: AnyObject?){
let desty : EndViewController = segue.destinationViewController as! EndViewController
desty.totalScore = scoreTotal.text!
}
```
But when I try to do that is turns me the error:
[Use of unresolved identifier 'segue']
But I've already done it as you can see here:[image](https://i.stack.imgur.com/eu1Sm.png)
So how can I solve it.
I will be so grateful if you help me.
Please, help a young programmer to learn.<issue_comment>username_1: You are using the wrong function. It should be...
```
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue" {
}
}
```
Upvotes: 1 <issue_comment>username_2: First, perform your segues as below:
```
self.performSegue(withIdentifier: "YourSegueID", sender: self)
```
Now, call prepareForSegue and change the values in destination accordingly:
```
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "YourSegueID" {
let vc = segue.destination
vc.yourVariable = "Some Value"
}
}
```
Upvotes: 1 <issue_comment>username_3: The internal parameter label `segue` is missing in the first parameter and the type of the second parameter is wrong.
**Please use code completion**
* Comment out your entire method
```
// func prepare(for: UIStoryboardSegue, sender: AnyObject?){
// let desty : EndViewController = segue.destinationViewController as! EndViewController
// desty.totalScore = scoreTotal.text!
// }
```
* Type `prep`, you will see
[](https://i.stack.imgur.com/v1HeW.png)
* Choose the proper line and press `return`.
* Copy the body of the former method into the new one.
Upvotes: 0
|
2018/03/15
| 799 | 2,715 |
<issue_start>username_0: I have written one c++ class which has read and write methods. These methods read and write row from/to csv file.
Currently I have implemented read and write for csv file having five tuples(columns), say - EmpNo, EmpName, Address, Department, Manager.
Class contains these 5 tuples as member variables of class.
So basically, in read(), I am reading row using fstream and putting tuple values in to respective member variable. Similarly, for write I am getting row data from user into class member variable and writing the same in csv file.
Now I want to use same code for reading and writing another csv file having only two tuples out of above five tuples- EmpNo, EmpName.
I can think of maintaining one variable to identify which CSV I am reading/writing and accordingly have if/else in all code. But this doesn't look cleaner approach.
pseudo code for read() with my approach is as below:
```
read()
{
read EmpNo;
read EmpName;
If (csv_with_5_tuple == true)
{
read Address;
read Department;
read Manager;
}
}
//Here, 'csv_with_5_tuple ' will be set when reading/writing from/to csv file of five tuples.
```
With this approach, I need to add 'if' condition everywhere in class.
Can anyone suggest me the best way to do this in c++?<issue_comment>username_1: You can use class inheritance for this. There are pseudo-code demonstrating the idea:
```
class csv2 {
public:
virtual void read()
{
read EmpNo;
read EmpName;
}
};
class csv5 : public csv2
{
public:
virtual void read()
{
csv2::read();
read Address;
read Department;
read Manager;
}
};
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: By using some `vector` and template, you might do:
```
template
std::vector csv\_read(std::istream& is, const std::vector& members)
{
std::vector res;
std::string header;
std::getline(is, header);
while (true) {
T obj;
for (auto m : members) {
is >> obj.\*m;
}
if (!is) {
break;
}
res.push\_back(obj);
}
return res;
}
```
With usage similar to
```
const std::vector members = {&Person2::Name, &Person2::AgeStr};
auto persons = csv\_read(ss, members);
```
[Demo](https://ideone.com/y8ZtG2)
Or simpler if you just use `std::vector>`:
```
std::vector> csv\_read(std::istream& is, std::size\_t rowCount)
{
std::vector> res;
std::string header;
std::getline(is, header);
while (true) {
std::vector row(rowCount);
for (auto& col : row) {
is >> col;
}
if (!is) {
break;
}
res.push\_back(row);
}
return res;
}
```
With usage similar to
```
auto data = csv_read(ss, 2);
```
[Demo](https://ideone.com/ikiq79)
Upvotes: 0
|
2018/03/15
| 949 | 3,531 |
<issue_start>username_0: I am using Google visualization pie chart for showing transaction state.
I want to export to csv, there is functionality ToolBar to export csv,html,iGoogle but I want to specific to csv only without select options.<issue_comment>username_1: Google will provide you u need to pass your API key inside it
```
google.charts.load('current', {packages: ['corechart']});
var visualization;
function draw() {
drawVisualization();
drawToolbar();
}
function drawVisualization() {
var container = document.getElementById('visualization\_div');
visualization = new google.visualization.PieChart(container);
new google.visualization.Query('https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA').
send(queryCallback);
}
function queryCallback(response) {
visualization.draw(response.getDataTable(), {is3D: true});
}
function drawToolbar() {
var components = [{type: 'csv', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA'},
];
var container = document.getElementById('toolbar\_div');
google.visualization.drawToolbar(container, components);
};
google.charts.setOnLoadCallback(draw);
```
fore more :
<https://developers.google.com/chart/interactive/docs/gallery/toolbar>
Upvotes: -1 <issue_comment>username_2: you can use static method --> [dataTableToCsv](https://developers.google.com/chart/interactive/docs/datatables_dataviews#datatabletocsv)
```
google.visualization.dataTableToCsv
```
this will create a csv string of the data in a data table.
it will not export the column headings, but those can be added manually...
see following working snippet...
```js
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['A', 10],
['B', 20],
['C', 30],
['D', 40],
['E', 50],
['F', 60]
]);
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data);
$('.csv-button').on('click', function () {
var browserIsIE;
var csvColumns;
var csvContent;
var downloadLink;
var fileName;
// build column headings
csvColumns = '';
for (var i = 0; i < data.getNumberOfColumns(); i++) {
csvColumns += data.getColumnLabel(i);
if (i < (data.getNumberOfColumns() - 1)) {
csvColumns += ',';
}
}
csvColumns += '\n';
// build data rows
csvContent = csvColumns + google.visualization.dataTableToCsv(data);
// download file
browserIsIE = false || !!document.documentMode;
fileName = 'data.csv';
if (browserIsIE) {
window.navigator.msSaveBlob(new Blob([csvContent], {type: 'data:text/csv'}), fileName);
} else {
downloadLink = document.createElement('a');
downloadLink.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvContent);
downloadLink.download = fileName;
raiseEvent(downloadLink, 'click');
downloadLink = null;
}
});
function raiseEvent(element, eventType) {
var eventRaised;
if (document.createEvent) {
eventRaised = document.createEvent('MouseEvents');
eventRaised.initEvent(eventType, true, false);
element.dispatchEvent(eventRaised);
} else if (document.createEventObject) {
eventRaised = document.createEventObject();
element.fireEvent('on' + eventType, eventRaised);
}
}
});
```
```html
Download CSV
```
Upvotes: 3 [selected_answer]
|
2018/03/15
| 750 | 2,078 |
<issue_start>username_0: I have this email template:
```
title
img { max-width: 600px; -ms-interpolation-mode: bicubic;}
.ReadMsgBody { width: 100%; }
.ExternalClass {width:100%;}
.backgroundTable {margin:0 auto; padding:0; width:100%;!important;}
body {
width: 100%;
height: 100%;
direction: rtl;
}
.force-full-width {
width: 100% !important;
}
@media only screen and (max-width: 599px) {
table[class\*="w320"] {
width: 320px !important;
}
}
| | | |
| --- | --- | --- |
|
| | |
| --- | --- |
|
| |
| --- |
|
Some text
|
|
|
```
It does work on Gmail app in Android, but in desktop version email content overflows .
If I remove `width:100vw;` from `body` tag, desktop works fine but content overflows in mobile version. My Question is How can I make body width 100% in mobile and 600px on desktop? I tried `max-width: 600px;` in body style but it doesn't work. I also tried 100% instead of 100vw (because 100 vw is width of screen) and it does not work either.<issue_comment>username_1: Your email will work just fine if you remove `width:100vw;` from the body tag.
Upvotes: 0 <issue_comment>username_2: I made a few changes, hope this is the outcome you were after. I have done the following:
* removed `width:100vw`from the body
* added the class body you are using on the body tag with the body CSS defined.
* Changed the media query (removed space)
```html
title
img { max-width: 600px; -ms-interpolation-mode: bicubic;}
.ReadMsgBody { width: 100%; }
.ExternalClass {width:100%;}
.backgroundTable {margin:0 auto; padding:0; width:100%;!important;}
body, .body {
width: 100%;
height: 100%;
direction: rtl;
}
.force-full-width {
width: 100% !important;
}
@media only screen and (max-width:599px) {
table.w320 {
width: 320px !important;
}
}
| | | |
| --- | --- | --- |
|
| | |
| --- | --- |
|
| |
| --- |
| Some text |
|
|
```
Above code tested in Outlook 2017 and Gmail app (v8.2.11) works properly now.
If you have any questions let me know.
Upvotes: 2 [selected_answer]
|