text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Combine multiple dataframes by summing certain columns in Pandas
Given three dataframes:
df1 = pd.DataFrame({'A': [5, 0], 'B': [2, 4], 'C': 'dog'})
df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3], 'C': 'dog'})
df3 = pd.DataFrame({'A': [2, 1], 'B': [5, 1], 'C': 'dog'})
how can one combine them into a single dataframe, by adding the values of a subset of given dataframes, such that the result becomes:
pd.DataFrame({'A': [8, 2], 'B': [10, 8], 'C': 'dog'})
for this example? My problem is that I also have columns which are identical, but cannot be summed (like 'C' here).
A:
One possible solution with sum if numeric values and if strings then join unique values per groups in GroupBy.agg after concat list of DataFrames:
f = lambda x: x.sum() if np.issubdtype(x.dtype, np.number) else ','.join(x.unique())
df = pd.concat([df1, df2, df3], keys=range(3)).groupby(level=1).agg(f)
print (df)
A B C
0 8 10 dog
1 2 8 dog
If possible different values like cat and dog:
df1 = pd.DataFrame({'A': [5, 0], 'B': [2, 4], 'C': 'dog'})
df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3], 'C': 'dog'})
df3 = pd.DataFrame({'A': [2, 1], 'B': [5, 1], 'C': ['cat','dog']})
f = lambda x: x.sum() if np.issubdtype(x.dtype, np.number) else ','.join(x.unique())
df = pd.concat([df1, df2, df3], keys=range(3)).groupby(level=1).agg(f)
print (df)
A B C
0 8 10 dog,cat
1 2 8 dog
If need lists:
f = lambda x: x.sum() if np.issubdtype(x.dtype, np.number) else x.unique().tolist()
df = pd.concat([df1, df2, df3], keys=range(3)).groupby(level=1).agg(f)
print (df)
A B C
0 8 10 [dog, cat]
1 2 8 [dog]
And for combination lists with scalars for nonnumeric values use custom function:
def f(x):
if np.issubdtype(x.dtype, np.number):
return x.sum()
else:
u = x.unique().tolist()
if len(u) == 1:
return u[0]
else:
return u
df = pd.concat([df1, df2, df3], keys=range(3)).groupby(level=1).agg(f)
print (df)
A B C
0 8 10 [dog, cat]
1 2 8 dog
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the meaning of "off line"?
The following is a verse from Daniel Powter's song Bad Day:
You stand in the line just to hit a new low
You're faking a smile with the coffee to go
You tell me your life's been way off line
You're falling to pieces every time
And I don't need no carryin' on
What does off line mean in the third line of the verse?
A:
It suggests there is a path that he wants / should follow, and he isn't. It is like not following the best way - he has lost the way.
It is different to meaning they aren't connected to the internet (although not being connected may make some people's lives off line).
| {
"pile_set_name": "StackExchange"
} |
Q:
Nginx returns 401 for subdirectory index.html
I have a website and every time when I try to access the page in a subfolder like 'myDomain.com/privacy-policy', nginx returns me a '401 Authorization Required'.
The website has the following folder structure:
-myDomain.com/
-index.html
-images/
-(images..)
-legal-disclosure/
-index.html
-css/
-(css files..)
-privacy-policy/
-index.html
-css/
-(css files..)
-template/
-templates.min.css
The corresponding nginx configuration:
server {
listen 80;
server_name myDomain.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name myDomain.com;
ssl_certificate /root/ssl-certs/myDomain.com_ssl_certificate.cer;
ssl_certificate_key /root/ssl-certs/_.myDomain.com_private_key.key;
location / {
root /var/www/html/myDomain.com;
index index.html;
}
location /privacy-policy {
root /var/www/html/myDomain.com/privacy-policy;
index index.html;
}
location /legal-disclosure {
root /var/www/html/myDomain.com/legal-disclosure;
index index.html;
}
}
Does anyone knows why?
A:
I solved my problem! I ignored the subdomain 'www.' on my nginx configurations and my links within the website referenced all to 'www.mydomain.com/...'.
Just added two server blocks with 'www.myDomain.com' and redirect them.
Now it works! :D
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the relationship between csrfmiddlewaretoken and csrftoken?
I was working with Django to create a website and got some questions about CSRF. I use django.middleware.csrf.CsrfViewMiddleware and add <form action="" method="post">{% csrf_token %} in my POST form.
And when I test the website:
GET / HTTP/1.1
Host: 123.207.137.168:8000
Then, I got cookies
Set-Cookie:csrftoken=Ev8veOH89vFDnG3a0GJUsMXA1oGZXxqXRw2nFWiKrvZ9UE10niTlZCiOxdnoKfTv; expires=Thu, 27-Dec-2018 06:37:41 GMT; Max-Age=31449600; Path=/
But in the html:
<input type='hidden' name='csrfmiddlewaretoken' value='JswHLk4fNpxHkh0OObD1uKiOxSDUzkMDWtqzcsFR5pRdRfYEbNNs1AD23Hkjm2fb' />
So I was wondering why the csrftoken and csrfmiddlewaretoken is different and how did the server use these two value to valid if the request is from the users or hackers?
A:
There are some answers in the docs, but looking at the code really solves this "mystery"
Basically what django does is the following:
Craft a CSRF secret key
Add a random salt to it and set the salted result as a CSRF cookie (csrftoken)
When user opens a form/request/anything, check if the user has the CSRF cookie set (if they don't have it, craft it as above). If they have it, fetch it, strip the salt and get the real secret, add a random salt and use this as another token (csrfmiddlewaretoken).
Now when you make a POST request for example, the following happens
You send the csrfmiddlewaretoken
Django unsalts the csrf cookie (csrftoken)
Django unsalts the token you sent (csrfmiddlewaretoken)
Django compares them. If the two match, you're ok.
This method with the two tokens is called Double-Submit Cookie. Django's way with the salting allows to keep the same csrf secret for some time without having to renew the key for every request
| {
"pile_set_name": "StackExchange"
} |
Q:
javascript escaping //
how will i escape the slashes // in javascript
var j = /^(ht|f)tp(s?)://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$;/
A:
Use a \ for escaping, like this:
var j = /^(ht|f)tp(s?):\/\/([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$;/
| {
"pile_set_name": "StackExchange"
} |
Q:
Regex to find first comment in a JS file
I am trying to write a regex (in JavaScript) that will match a multi line comment at the beginning of a JS file.
So far, I came up with this: /^(\/\*[^\*\/]*\*\/)/g
It works for a single line comment: http://refiddle.com/24o
But my problem is that it does not work for a multi line comment: http://refiddle.com/24m
Do you have any ideas how to solve it?
A:
Like HTML, JavaScript cannot be parsed by regular expressions. Attempting to do so correctly is futile.
Instead, you must use a parser that will correctly transform JavaScript source code into an AST, which you may inspect programmatically. Fortunately, there's libraries that do the parsing for you.
Here's a working example that outputs the AST of this code:
/* this is a
multi-line
comment */
var test = "this is a string, /* and this is not a comment! */";
// ..but this is
Which gets us:
[
"toplevel",
[
[
{
"name": "var",
"start": {
"type": "keyword",
"value": "var",
"line": 5,
"col": 4,
"pos": 57,
"endpos": 60,
"nlb": true,
"comments_before": [
{
"type": "comment2",
"value": " this is a\n multi-line\n comment ",
"line": 1,
"col": 4,
"pos": 5,
"endpos": 47,
"nlb": true
}
]
},
"end": {
"type": "punc",
"value": ";",
"line": 5,
"col": 67,
"pos": 120,
"endpos": 121,
"nlb": false,
"comments_before": []
}
},
[
[
"test",
[
{
"name": "string",
"start": {
"type": "string",
"value": "this is a string, /* and this is not a comment! */",
"line": 5,
"col": 15,
"pos": 68,
"endpos": 120,
"nlb": false,
"comments_before": []
},
"end": {
"type": "string",
"value": "this is a string, /* and this is not a comment! */",
"line": 5,
"col": 15,
"pos": 68,
"endpos": 120,
"nlb": false,
"comments_before": []
}
},
"this is a string, /* and this is not a comment! */"
]
]
]
]
]
]
Now it's just a matter of looping over the AST and extracting what you need.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find third Sunday of each month occur between given two dates
Find third Sunday of each month occur between given below two dates.
Start Date:- 07-06-2011 // dd-mm-yyyy
End Date:- 07-06-2012 // dd-mm-yyyy
USE C#.NET
A:
This should do the trick:
public List<DateTime> ThirdSundayOfEachMonth( DateTime startdate, DateTime enddate )
{
List<DateTime> result = new List<DateTime>();
int sundaymonthcount = 0;
for( DateTime traverser = new DateTime(startdate.Year, startdate.Month, 1); traverser <= enddate; traverser = traverser.AddDays(1) ){
if( traverser.DayOfWeek == DayOfWeek.Sunday ) sundaymonthcount++;
if( sundaymonthcount == 3 && traverser > startdate ){
result.Add(traverser);
sundaymonthcount = 0;
traverser = new DateTime( traverser.Year, traverser.Month, 1 ).AddMonths(1);
}
}
return result;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating event Flag
I am creating event flag(i.e. first event, last event, other event( between first and last event). The events are occurring at each game (i.e. gsm_id). I have created the record of the first event(First Event) and last event (Last Event) in two different columns. you can look at the following table for more detail.
gsm_id eventdatetime matchdatetime PreviousEventTime First Event Last Event
2462794 8/11/2017 18:46 8/11/2017 18:45 8/11/2017 18:45 8/11/2017 18:46 8/11/2017 20:09
2462794 8/11/2017 18:49 8/11/2017 18:45 8/11/2017 18:46 8/11/2017 18:46 8/11/2017 20:09
2462794 8/11/2017 19:13 8/11/2017 18:45 8/11/2017 18:49 8/11/2017 18:46 8/11/2017 20:09
2462794 8/11/2017 19:31 8/11/2017 18:45 8/11/2017 19:13 8/11/2017 18:46 8/11/2017 20:09
2462794 8/11/2017 19:40 8/11/2017 18:45 8/11/2017 19:31 8/11/2017 18:46 8/11/2017 20:09
2462794 8/11/2017 20:07 8/11/2017 18:45 8/11/2017 19:40 8/11/2017 18:46 8/11/2017 20:09
2462794 8/11/2017 20:09 8/11/2017 18:45 8/11/2017 20:07 8/11/2017 18:46 8/11/2017 20:09
2462795 8/12/2017 17:39 8/12/2017 16:30 8/12/2017 16:30 8/12/2017 17:39 8/12/2017 17:44
2462795 8/12/2017 17:44 8/12/2017 16:30 8/12/2017 17:39 8/12/2017 17:39 8/12/2017 17:44
2462796 8/12/2017 14:23 8/12/2017 14:00 8/12/2017 14:00 8/12/2017 14:23 8/12/2017 15:27
2462796 8/12/2017 14:38 8/12/2017 14:00 8/12/2017 14:23 8/12/2017 14:23 8/12/2017 15:27
2462796 8/12/2017 14:42 8/12/2017 14:00 8/12/2017 14:38 8/12/2017 14:23 8/12/2017 15:27
2462796 8/12/2017 15:08 8/12/2017 14:00 8/12/2017 14:42 8/12/2017 14:23 8/12/2017 15:27
2462796 8/12/2017 15:27 8/12/2017 14:00 8/12/2017 15:08 8/12/2017 14:23 8/12/2017 15:27
2462797 8/12/2017 14:22 8/12/2017 14:00 8/12/2017 14:00 8/12/2017 14:22 8/12/2017 15:17
2462797 8/12/2017 14:25 8/12/2017 14:00 8/12/2017 14:22 8/12/2017 14:22 8/12/2017 15:17
2462797 8/12/2017 15:17 8/12/2017 14:00 8/12/2017 14:25 8/12/2017 14:22 8/12/2017 15:17
Data can be downloaded from google drive as follow:
[https://drive.google.com/open?id=1KPu8MBBd2X9tsV0sjMQQVQq4k9s5BYVs][1]
What i am trying to do is this.
I will create a new column to record the flag (string) (i.e. 'first event' where eventdatetime and First Event are the same, 'Last event' where eventdatetime and Last event are the same, the rest will be assign as 'Other'.
I tried to use np.where method but it could only give me two arguments.
Can any one advise how to handle 3 argument to get abovementioned new column?
Thanks
Zep
A:
I think need numpy.select:
m1 = df['eventdatetime'] == df['First Event']
m2 = df['eventdatetime'] == df['Last Event']
df['flag'] = np.select([m1, m2], ['First event','Last event'], default='Other')
print (df)
gsm_id eventdatetime matchdatetime PreviousEventTime \
0 2462794 8/11/2017 18:46 8/11/2017 18:45 8/11/2017 18:45
1 2462794 8/11/2017 18:49 8/11/2017 18:45 8/11/2017 18:46
2 2462794 8/11/2017 19:13 8/11/2017 18:45 8/11/2017 18:49
3 2462794 8/11/2017 19:31 8/11/2017 18:45 8/11/2017 19:13
4 2462794 8/11/2017 19:40 8/11/2017 18:45 8/11/2017 19:31
5 2462794 8/11/2017 20:07 8/11/2017 18:45 8/11/2017 19:40
6 2462794 8/11/2017 20:09 8/11/2017 18:45 8/11/2017 20:07
7 2462795 8/12/2017 17:39 8/12/2017 16:30 8/12/2017 16:30
8 2462795 8/12/2017 17:44 8/12/2017 16:30 8/12/2017 17:39
9 2462796 8/12/2017 14:23 8/12/2017 14:00 8/12/2017 14:00
10 2462796 8/12/2017 14:38 8/12/2017 14:00 8/12/2017 14:23
11 2462796 8/12/2017 14:42 8/12/2017 14:00 8/12/2017 14:38
12 2462796 8/12/2017 15:08 8/12/2017 14:00 8/12/2017 14:42
13 2462796 8/12/2017 15:27 8/12/2017 14:00 8/12/2017 15:08
14 2462797 8/12/2017 14:22 8/12/2017 14:00 8/12/2017 14:00
15 2462797 8/12/2017 14:25 8/12/2017 14:00 8/12/2017 14:22
16 2462797 8/12/2017 15:17 8/12/2017 14:00 8/12/2017 14:25
First Event Last Event flag
0 8/11/2017 18:46 8/11/2017 20:09 First event
1 8/11/2017 18:46 8/11/2017 20:09 Other
2 8/11/2017 18:46 8/11/2017 20:09 Other
3 8/11/2017 18:46 8/11/2017 20:09 Other
4 8/11/2017 18:46 8/11/2017 20:09 Other
5 8/11/2017 18:46 8/11/2017 20:09 Other
6 8/11/2017 18:46 8/11/2017 20:09 Last event
7 8/12/2017 17:39 8/12/2017 17:44 First event
8 8/12/2017 17:39 8/12/2017 17:44 Last event
9 8/12/2017 14:23 8/12/2017 15:27 First event
10 8/12/2017 14:23 8/12/2017 15:27 Other
11 8/12/2017 14:23 8/12/2017 15:27 Other
12 8/12/2017 14:23 8/12/2017 15:27 Other
13 8/12/2017 14:23 8/12/2017 15:27 Last event
14 8/12/2017 14:22 8/12/2017 15:17 First event
15 8/12/2017 14:22 8/12/2017 15:17 Other
16 8/12/2017 14:22 8/12/2017 15:17 Last event
| {
"pile_set_name": "StackExchange"
} |
Q:
What is common domain of two equal function
I am reading about when to function are equal or identical. As per the source through which i am studying two function f and g are equal and identical if they satisfy following conditions.
1) Domain of f should be equal to Domain of g.
2) Range of f should be equal to Range of g.
3) f(x)=g(x), for every x belonging to their common domain.
I am little confused with third condition, let D denote the Domain of function f , as per the condition 1 if g is equal to f then the domain of g is D itself.
So common domain will be D. So instead of writing Domain of f or Domain g why they have used the word common domain or I am missing some crucial point?
My another question is, are these three condition are necessary but not sufficient for stating to function are equal?
A:
"So instead of writing Domain of f or Domain g why they have used the word common domain?"
You have a point here in the sense that the third condition is given as some enlargement of the first condition. But that does not really harm, does it?
Let me give you a more handsome definition of the statement $f=g$ where $f$ and $g$ are both functions.
$f$ and $g$ have the same domain and for every $x$ that is an element of that domain we have $f(x)=g(x)$.
This definition is equivalent with the one in your question. Actually I put the conditions 1) and 3) together and leave condition 2) out. This because condition 2) is automatically satisfied if the conditions 1) and 3) are satisfied, hence is redundant. This definition is practicized in e.g. set theory.
Another point is that definitions are usually given as "if" statements, but should be read as "if and only if" statements (so necessity and sufficiency).
P.S. In certain areas of mathematics (e.g. categories) more is demanded for functions $f$ and $g$ to be equal. The condition that I gave is then accompanied with the condition that $f$ and $g$ have a common codomain (which is - at least in this context - not the same thing as range). Here by statement "$f$ and $g$ have a common codomain" is meant that the codomain of $f$ is the same as the codomain of $g$. So it is not the (much weaker) statement that the codomains of $f$ and $g$ have a non-empty intersection.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to use touchesBegan and touchesEnded?
I added below codes on ViewController
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("started")
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
print("ended")
}
but it doesn't print any messages at all.
A:
UIResponder class is an abstract interface for responding to and
handling events
Apple API Reference
UIWindow, UIViewController, UIView are subclass of UIResponder
if you want to use touchesBegan and touchesEnded, override it
touch event follow responder chain refer apple docs
some touch event occur and your ViewController's view become next responder and hittest successfully touchesBegan called when touch began and touchesEnded called touch ended
| {
"pile_set_name": "StackExchange"
} |
Q:
How to open local folder in thumbnail view in Chrome or Firefox?
It's quite easy to open local picture files with Chrome or Firefox by right clicking > open with. When I navigate from the address bar into the folder the image is in I get a page like Index of /Users/horst/Documents/pictures_folder/ and see all containing files listed here. Is it possible to display these files in a thumbnail view in the browser?
A:
Found this solution after having similar trouble.
One such extension, Local Image Viewer allows you to view local folders with thumnails, after clicking a button below the file listing.
You need to make some config changes as described here.
Briefly, after installing this extension:
Go to the extension settings page, chrome://extensions/
Open the desired folder in Chrome.
A button labeled Show Thumbnails appears at the bottom of the listing. Clicking this will show thumnails for all images in the folder, below.
Clicking any thumbnail will display the full fiew.
(from the dottech page) Just press the space bar to zoom in/zoom out the photo. If you place your mouse cursor over the left and right side of the photo, you will be able to see the “next” and “previous” buttons. You can also click the arrow up button to go back to your file’s parent directory.
Read more at http://dottech.org/163314/how-to-view-local-images-in-chrome-tip/#S1sgoAKCKhvUYWGT.99
| {
"pile_set_name": "StackExchange"
} |
Q:
private IP address classes
according to some references Class C for example can provide 2^8 hosts (mask /24), according to others it can provide 2^16 hosts (mask /16).?
so what is the real mask of C class ??
A:
from the Protocol IPv4 Specification in RFC 791 publication:
Address Formats:
High Order Bits Format Class
--------------- ------------------------------- -----
0 7 bits of net, 24 bits of host a
10 14 bits of net, 16 bits of host b
110 21 bits of net, 8 bits of host c
111 escape to extended addressing mode
-- RFC 791 - Addressing
so, for class C
address | N.N.N.H (N network bit, H hosts bit)
mask | 11111111.11111111.11111111.0000000 (/24)
# of address | 256 (2^8)
# of hosts | 256 (2^8 – 2)
Update
after rechecking the image that was associated with the OP post, I noticed that his confusion comes from Reserved IP addresses notion, and precisely the 192.168.0.0/16address block. and my accepted answer wasn't explaining that properly ^^"
TL;DR:
192.168.0.0/16 isn't a single C class network number with a /16 host mask, but a set of 256 class C network numbers
Explanation
given the my original answer.
C class addresses form:
110xxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx
+------------------------+.+------+
net host
C class addresses range
net host
+-------------------------+.+------+
from: 110 00000.00000000.00000000.00000000 (192.0.0.0)
to : 110 11111.11111111.11111111.11111111 (223.0.0.0)
+++ -----.--------.--------.--------
form this whole range, there are reserved IP addresses blocks, for various propose. cf. reserved IP addresses blocks
among this reserved blocks there is:
192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
reserved for Private Network according to RFC 1918, and defined as: "a set of 256 contiguous class C network numbers.".So:
192.168/16
192.168.0.0/24 (254 host)
...
192.168.255.0/24 (254 host)
You can visualize it as:
net host
+-------------------------+.+------+
+++ -----.--------.--------.-------- <- C class
from: 110 00000.10101000.00000000.00000000 (192.168.0.0)
to : 110 11111.10101000.11111111.11111111 (192.168.255.255)
+++ +++++.++++++++.--------.-------- <- /16 mask
| {
"pile_set_name": "StackExchange"
} |
Q:
Who wins the race for multiple valid blocks mined at the same time?
From my understanding, a SHA256 hash is generated by a miner and if the hash is less than a specific value, it is passed to its peers. That said, It's possible for multiple hashes to be created at very close to the same time. If this happens, how is the "winner" determined? I see this has happened a lot (multiple orphaned blocks).
What can be done by the miner to see that their block wins the race, either honestly or through an attack? The protocol stipulates that the block shall be recognized by which ever was received first. Is it advantageous to set up peering with other miners?
A:
When there's a fork, part of the network will mine to find the next block in one branch and part in the other branch. Whichever part finds the next block first will determine the winning branch.
A miner who finds a block will want to spread it widely and quickly. This makes sure there are many other miners who saw his block first, and thus a high probability that the next block will be found by one of those.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unity3D Null reference in Instantiate
The "Object reference not set to an instance of an object" error is still showing.
I tried Debug.Log on every variable, no errors.
This is my code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlatformSpawn : MonoBehaviour {
public GameObject platform;
public GameObject life;
private Vector3 platformrotation;
private Vector2 platformpoint, lifepoint;
private float platformrange, liferange;
public List<Vector2> SpawnList = new List<Vector2> ();
void Update () {
float randposition = Random.Range (-10f, 10f); //x-axis
platformrange -= 5; //y-axis
float randrotation = Random.Range(-20f, 20f); //z-axis rotation
liferange = platformrange + 1.56f;
platformpoint = new Vector2 (randposition, platformrange);
platformrotation = new Vector3 (0f, 0f, randrotation);
lifepoint = new Vector2 (randposition, liferange);
SpawnList.Add (platformpoint);
GameObject Tlife = (GameObject)Instantiate (life, life.transform.position, life.transform.rotation);
GameObject Tplatform = (GameObject)Instantiate (platform, platform.transform.position, platform.transform.rotation);
Tlife.transform.position = lifepoint;
Tplatform.transform.position = platformpoint;
if (SpawnList.Count >= 10) {
Tplatform.transform.rotation = Quaternion.Euler (platformrotation);
}
}
}
The error is in
GameObject Tlife = (GameObject)Instantiate (life,
life.transform.position, life.transform.rotation);
Thanks 4 the help ^_^
P.S.
The prefabs are still instantiating without any problems...
A:
life has to be a prefab that you've already created in the Editor and dragged/dropped onto the Inspector window for this object.
Ensure you:
Created a prefab
Selected this object in the Editor, so the Inspector appears
Drag/dropped that prefab onto the "life" field in the Inspector
| {
"pile_set_name": "StackExchange"
} |
Q:
NSURL doesn't work any time
i have the following problem sometimes my openURL-Dialog works perfectly, then i looked at the variable from the url and that is the variable:
www.brehm-gmbh.de
but some other times there are some crazy elements at the end of the variable like this:
www.adamczyk-fenster.de%E2%80%8E
i get this pages from an .asc file and both are in this file normal without this elements,
what can i do to solve this problem?
thank you all for helping beforehand
A:
From Wikipedia:
The left-to-right mark (LRM) is a
control character or non-printing
character, used in the computerized
typesetting of bi-directional text,
containing mixed left-to-right scripts
(such as English and Russian) and
right-to-left scripts (such as Arabic
and Hebrew). It is used to change the
way adjacent characters are grouped
with respect to text direction.
You're getting this because (1) you've got non-English URLs, are composing URLs from non-English strings or you have some other non-English elements and the string encoding is attempting to compensate or (2) it's garbarge being interpreted as an encoding (unlikely if it is consistant.)
Call -[NSString localizedNameOfStringEncoding] on the string before you use it see what encoding it is using. You probably need to explicitly establish an encoding when you read in the strings before you put them in the NSURL.
| {
"pile_set_name": "StackExchange"
} |
Q:
IoC Containers and Domain Driven Design
I've been searching for guidance for using IoC containers in domain driven design. Evan's book unfortunately doesn't touch on the subject. The only substantial guidelines I could find on the internet is here.
Many of Malovic's points are common sense but I'm concerned about a few of them. He suggests that IoC container's should be reserved for resolving services only and that using an IoC container to resolve domain dependencies is a bad idea. However, he doesn't back up this assertion with any examples. He simple states it as a matter of fact.
He then goes on to say that mixing IoC containers and factories doesn't make sense. This appears to contradict his first point. If, in fact, domain dependencies shouldn't be resolved by an IoC container how then should they be resolved? Evan's book clearly points to factories as the logical choice.
I would appreciate any input you have on the matter. I'm a novice when it comes to both DDD and IoC. I'm struggling to grasp how IoC and DDD can work together.
A:
In my opinion he is correct about not using IoC container in domain model. That practice I follow myself as well. Basic idea is that services may contain infrastructure dependencies and therefore its wise to mock them. Domain entities don't have those, so its not important to mock them up (still coding to interfaces is good practice).
Factories for domain entities should not be in IoC container, but factories for services should. Basically you may reference entity factories in your services. It's not very tight coupling.
Good reading about IoC can be found at Billy McCafferty's blog post "Dependency Injection 101"
| {
"pile_set_name": "StackExchange"
} |
Q:
ColdFusion - CFHTTP (https) sending request over port 80
I am using CFHTTP to connect to a server and post some parameters. I have successfully imported the certificate.
<cfhttp url="https://xml.proveid.experian.com/IDSearch.cfc" method="post" result="response" port="443">
<cfhttpparam type="Header" name="Accept-Encoding" value="*">
<cfhttpparam type="header" name="content-length" value="#len(arguments.xml)#" />
<cfhttpparam type="xml" value="#trim(arguments.xml)#" />
</cfhttp>
As you can see the request is for port 443 but the error I got back is:
struct Charset [empty string]
ErrorDetail Connect Exception: Connect to xml.proveid.experian.com:80
[xml.proveid.experian.com/194.60.180.108]
failed: Connection timed out: connect
Filecontent Connection Failure Header [empty string]
Mimetype Unable to determine MIME type of file.
Responseheader struct [empty]
Statuscode Connection Failure. Status code unavailable.
Text YES Connection Failure. Status code unavailable.
Can anyone explain why the request is made on port 80?
A:
It seems that the specific web service doesn't play well with CFHTTP. So this approach solved the problem.
<cfset args.xml = 'xml value'>
<cfinvoke
webservice="https://xml.proveid.experian.com/IDSearch.cfc?wsdl"
method="search"
returnvariable="aTemp"
argumentCollection="#args#">
</cfinvoke>
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting blank page after publishing my WCF service in IIS8
I created WCF services and i published it in IIS8 ,but i am getting blank page only.i dont know the reason why it showing blank page its not showing any errors.how to solve this issue.?
I tried following steps what they followed
http://www.kebabshopblues.co.uk/2013/09/20/hosting-a-wcf-service-library-project-in-iis-8-0-windows-8-0-net-4-5/
A:
The problem could be in hosting and most likely around binding. You may also want to refer to the following link which explains hosting WCF on IIS:
https://jonathanvanderoost.com/2013/11/12/host-a-wcf-service-in-iis-vs2012-framework-4-5/
I am assuming that you would have tested your service in 'WCF test client'. Would also encourage to install SOUP UI from the following link so that you can test the your web service:
https://www.soapui.org/downloads/soapui.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Factor $a^3b-ab^3+a^2+b^2+1$
I am trying to factor $a^3b-ab^3+a^2+b^2+1$.
I have tried factoring out an $a$ in the first two terms and a $b$ in the third and fourth terms, but get $a^2(a+b)-b^2(b-a)+1=a^2(a+b)+b^2(a-b)+1$. I see no obvious way to factor it. Can you give me a hint?
A:
I started with:
$a^3b - b^3a = ab(a-b)(a+b) = (a^2 - ab)(b^2 + ab)$
Then to work in the remaining terms:
$((a^2 - ab)+1)((b^2 + ab) + 1) = a^3b - b^3a + (a^2-ab) + (b^2 + ab) + 1$
It was more about noodling around than any algorithmic approach.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using ggplot to plot line segments and points together
What I am trying to accomplish: manually add shapes (lines and circles for a soccer pitch, in my actual project) to a scatterplot. This is a scaled-down example of my actual project, but illustrates the issue I need help with.
Here is the data I am using for this example:
data <- data.frame("name" = c("A", "A", "B", "B", "C", "C"),
"x" = c(.13, .64, .82, .39, .51, .03),
"y" = c(.62, .94, .10, .24, .20, .84))
I will provide example code, first one way that works (tedious, too long), and then one way that I can't figure out (which seems more efficient/concise, and possilbly... faster?).
library(ggplot2)
ggplot(data, aes(x, y)) +
geom_point() +
geom_segment(aes(x = 0,xend = 1,y = 1,yend = 1)) +
geom_segment(aes(x = 0, xend = 1, y=0,yend=0)) +
geom_segment(aes(x=1, xend=1, y=0, yend=1)) +
geom_segment(aes(x=0, xend=0, y=0, yend=1))
This gets me a nice 1x1 pitch with 6 data points (don't think I can embed the plot, since I don't have enough reputation). Since my actual project has many more data points, and also many more "shapes" (line segments, circles, and circle arcs) that make up the pitch, I thought it would be better to use vectors to define the geom_segment aesthetics - since the full data set plots very slowly. This is what I have:
ggplot(data, aes(x, y)) +
geom_point() +
geom_segment(aes(x = c(0,0,1,0),
xend = c(1,1,1,0),
y = c(1,0,0,0),
yend = c(1,0,1,1)))
I get the following error:
Error: Aesthetics must be either length 1 or the same as the data (16): x, y, xend, yend
I have tried changing the layer where I call aes(), using the inherit.aes = FALSE in geom_segment, but it still gives that error. I'm relatively new to R, and very new to SO, so my apologies if I'm using any incorrect terminology or protocol when posting this question.
The issue is that when listing out each of the shapes that make up the pitch individually (an extra layer for every single line segment or circle), and then adding the x, y data as points, it takes forever for the plot to render.
Any help avoiding that error when using vectors to plot the shape layers, or any other creative solutions would be great. My main goal is to make this plot of many shapes and many data points render more quickly (having more elegant code would be a nice bonus as well).
Thank you!
A:
What Axeman is trying to say is, write and extra data frame with your segments and load this into the geom_segment function via the data parameter. If you do so, it doesn't use the standard data provided to the ggplot function but it will use it's own data.
Something like
data <- data.frame("name" = c("A", "A", "B", "B", "C", "C"),
"x" = c(.13, .64, .82, .39, .51, .03),
"y" = c(.62, .94, .10, .24, .20, .84))
seg_df <- data.frame(x=c(0,0,1,0),
y=c(1,0,0,0),
xend=c(1,1,1,0),
yend=c(1,0,1,1))
ggplot(data, aes(x, y)) +
geom_point() +
geom_segment(data=seg_df, aes(x, y, xend=xend, yend=yend))
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get the right KEY and IV in Rinjdael encryption equivalent in JAVA
I have a code in VB.Net with a Rijndael encryption algorithm:
Public Function DesencriptarCertificado(ByVal pCertificado As String, ByVal pClave As String) As Byte()
Dim byteCertificadoDescencriptado As Byte() = Nothing
Dim Algoritmo As SymmetricAlgorithm = New RijndaelManaged()
Dim CertClaveDesencriptada As String = ""
CertClaveDesencriptada = DesencriptarString(pClave, "")
Transform(CertClaveDesencriptada, Algoritmo)
Dim ICryptoTransform As ICryptoTransform = Algoritmo.CreateDecryptor()
byteCertificadoDescencriptado = HexToByte(pCertificado)
byteCertificadoDescencriptado = ICryptoTransform.TransformFinalBlock(byteCertificadoDescencriptado, 0, byteCertificadoDescencriptado.Length)
Return byteCertificadoDescencriptado
End Function
Public Sub Transform(ByVal pClave As String, ByRef pAlgoritmo As SymmetricAlgorithm)
Dim bytes As Byte() = New Byte(7) {}
Dim BytesClave As Byte() = Encoding.ASCII.GetBytes(pClave)
Dim length As Integer = Math.Min(BytesClave.Length, bytes.Length)
For i As Integer = 0 To length - 1
bytes(i) = BytesClave(i)
Next
Dim key As New Rfc2898DeriveBytes(pClave, bytes)
//ASIGNO BYTES A KEY E IV
pAlgoritmo.Key = key.GetBytes(pAlgoritmo.KeySize \ 8)
pAlgoritmo.IV = key.GetBytes(pAlgoritmo.BlockSize \ 8)
End Sub
The problem is the IV and KEY in JAVA do not get the same bytes, so signature is not the same, it works perfectly if I initialize the KEY and IV manually with the same bytes that are generated in VB.Net, but it is not feasible of course because it would only work for a specific certificate, and the idea is that it works generically, after a search I tried some variants but without success, I could not get the KEY And IV, I would appreciate any help with the subject.
Java Code
public byte[] DesencriptarCertificado(String pCertificado, String pClave) throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException, NoSuchPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException, ShortBufferException, IOException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
try {
String CertClaveDesencriptada = DesencriptarString(pClave, "");
////////////Transform//////////////
byte[] bytes = new byte[8];
byte[] BytesClave = CertClaveDesencriptada.getBytes();
int length = Math.min(BytesClave.length, bytes.length);
for (int i = 0; i < length; i++) {
bytes[i] = BytesClave[i];
}
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec pbeKeySpec = new PBEKeySpec(CertClaveDesencriptada.toCharArray(), bytes, 12, 1000);
Key secretKey = factory.generateSecret(pbeKeySpec);
byte[] encoded = secretKey.getEncoded();
byte[] KEY = new byte[32];
byte[] IV = new byte[16];
//ASIGNO BYTES A KEY E IV
System.arraycopy(encoded, 0, KEY, 0, 32);
System.arraycopy(encoded, 32, IV, 0, 16);
SecretKeySpec secret = new SecretKeySpec(key, "Rijndael");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(IV);
_cipherDecrypEncrypt = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
_cipherDecrypEncrypt.init(Cipher.DECRYPT_MODE, secret, ivSpec);
///////////////DESENCRIPTAR CERTIFICADO/////////////////////
byte[] beforeEncrypt = HexToByte(pCertificado);
byte[] byteCertificadoDescencriptado = _cipherDecrypEncrypt.doFinal(beforeEncrypt);
return byteCertificadoDescencriptado;
} catch (InvalidKeyException e) {
throw new TAFACE2ApiEntidad.TAException(e.getMessage());
} catch (IllegalBlockSizeException e) {
System.out.println(e);
throw new TAFACE2ApiEntidad.TAException(e.getMessage());
} catch (BadPaddingException e) {
System.out.println(e);
throw new TAFACE2ApiEntidad.TAException(e.getMessage());
}
}
A:
If your salt is supposed to be 7 bytes long, as seen in your VB.NET code Dim bytes As Byte() = New Byte(7) {}, you should declare it as such:
byte[] bytes = new byte[7];
The constructor for PBEKeySpec that you're trying to use is PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength) where you use request 12 iterations for an output length of 1000.
You need to use
new PBEKeySpec(CertClaveDesencriptada.toCharArray(), bytes, 1000, 384);
where 384 means 32 + 16 bytes in bits.
| {
"pile_set_name": "StackExchange"
} |
Q:
Stream protected media (located outside of httpdocs) with jPlayer
I have uploaded some sample mp3 files to a directory outside of httpdocs, I have ensured that this is accessible to PHP by configuring open_basedir correctly and tested that this directory is working.
What I would like to do is stream these files via a PHP file as non-authenticated users should never have access to these files. I am currently using jPlayer and expect the setMedia function should look similar to this:
$("#jquery_jplayer").jPlayer("setMedia", { mp3: "stream.php?track=" + id + ".mp3" });
I have tried setting content headers etc in stream.php and it currently looks like this:
$filePath = "../song_files/mp3/";
$fileName = "$_GET[track].mp3";
header("Content-Type: audio/mpeg");
header('Content-Disposition: attachment; filename="'.$fileName.'"');
getFile($filePath + $fileName);
If I load this page directly, the mp3 file downloads and plays fine, but when I use the above javascript, jPlayer doesn't play the track.
I have had a look at this post ( Streaming an MP3 on stdout to Jplayer using PHP ) and it appears the user was trying to achieve exactly what I want, but upon testing the solution I keep running into a problem, all I get is "CURL Failed".
Are there any different methods I can use to achieve this. Pointing me in the right direction would be greatly appreciated.
A:
After searching around some more I have found a solution that is working fine. I used the code from a similar topic ( PHP to protect PDF and DOC )
I will place the code I used here to help answer the question correctly:
//check users is loged in and valid for download if not redirect them out
// YOU NEED TO ADD CODE HERE FOR THAT CHECK
// array of support file types for download script and there mimetype
$mimeTypes = array(
'doc' => 'application/msword',
'pdf' => 'application/pdf',
);
// set the file here (best of using a $_GET[])
$file = "../documents/file.doc";
// gets the extension of the file to be loaded for searching array above
$ext = explode('.', $file);
$ext = end($ext);
// gets the file name to send to the browser to force download of file
$fileName = explode("/", $file);
$fileName = end($fileName);
// opens the file for reading and sends headers to browser
$fp = fopen($file,"r") ;
header("Content-Type: ".$mimeTypes[$ext]);
header('Content-Disposition: attachment; filename="'.$fileName.'"');
// reads file and send the raw code to browser
while (! feof($fp)) {
$buff = fread($fp,4096);
echo $buff;
}
// closes file after whe have finished reading it
fclose($fp);
</code></pre>
| {
"pile_set_name": "StackExchange"
} |
Q:
django update usage within for loop
Within Django, I can't update the database even though all is correct.(I assume :) )
Should I proceed with query "get" instead of "filter" and use "save"
instead of "update" ?
In my database I have P_350 and P_450 columns.
I am getting no error and also nothing is updated
for thing_id, values_dict in groups.items():
for value_id, value_value in values_dict.items():
qs = RFP.objects.filter(id__in=thing_id)
updates = {}
if value_id == '350':
if len(value_value) > 1:
updates['P_350'] = value_value
if value_id == '450':
if len(value_value) > 1:
updates['P_450'] = value_value
if updates:
qs.update(**updates)
Here is the prints for the groups.items:
397 350 try_3
397 450 try_4
370 350 try_1
370 450 try_2
A:
you should try qs = RFP.objects.filter(id=thing_id) instead of qs = RFP.objects.filter(id__in=thing_id). the __in is looking for list of ids and you are providing a string and it will treat the string as a list instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS: How to specify DNS to be used to resolve hostname to IP address?
As the title says I have hostname (eg www.example.com) that I want to resolve using specified DNS server. For example in one case I want to use google's IPv4 DNS and in other case google's IPv6 DNS.
I have browsed SO for something like this on iOS, and found questions like this one (Swift - Get device's IP Address), so I am sure it can be done, but I am unclear how?
How can I do this?
EDIT 06/07/2018
@mdeora suggested solution from http://www.software7.com/blog/programmatically-query-specific-dns-servers-on-ios/
This solution works but only if I use IPv4 DNS, for example google's "8.8.8.8". If I try to use IPv6 DNS 2001:4860:4860::8888, i get nothing.
I have managed to change conversion:
void setup_dns_server(res_state res, const char *dns_server)
{
res_ninit(res);
struct in_addr addr;
// int returnValue = inet_aton(dns_server, &addr);
inet_pton(AF_INET6, dns_server, &addr); // for IPv6 conversion
res->nsaddr_list[0].sin_addr = addr;
res->nsaddr_list[0].sin_family = AF_INET;
res->nsaddr_list[0].sin_port = htons(NS_DEFAULTPORT);
res->nscount = 1;
};
But still have trouble with this:
void query_ip(res_state res, const char *host, char ip[])
{
u_char answer[NS_PACKETSZ];//NS_IN6ADDRSZ NS_PACKETSZ
int len = res_nquery(res, host, ns_c_in, ns_t_a, answer, sizeof(answer));
ns_msg handle;
ns_initparse(answer, len, &handle);
if(ns_msg_count(handle, ns_s_an) > 0) {
ns_rr rr;
if(ns_parserr(&handle, ns_s_an, 0, &rr) == 0) {
strcpy(ip, inet_ntoa(*(struct in_addr *)ns_rr_rdata(rr)));
}
}
}
I get -1 for len. From what I gather it seems I need to configure res_state for IPv6.
A:
Here the code from my blogpost, that was already mentioned above, just slightly adapted to use IPv6.
Adapt setup_dns_server
First we could start with the changes to setup_dns_server:
void setup_dns_server(res_state res, const char *dns_server) {
struct in6_addr addr;
inet_pton(AF_INET6, dns_server, &addr);
res->_u._ext.ext->nsaddrs[0].sin6.sin6_addr = addr;
res->_u._ext.ext->nsaddrs[0].sin6.sin6_family = AF_INET6;
res->_u._ext.ext->nsaddrs[0].sin6.sin6_port = htons(NS_DEFAULTPORT);
res->nscount = 1;
}
Add __res_state_ext
This wouldn't compile because of a missing struct __res_state_ext. This structure is unfortunately in a private header file.
But the definition of that one can be take from here:
https://opensource.apple.com/source/libresolv/libresolv-65/res_private.h.auto.html :
struct __res_state_ext {
union res_sockaddr_union nsaddrs[MAXNS];
struct sort_list {
int af;
union {
struct in_addr ina;
struct in6_addr in6a;
} addr, mask;
} sort_list[MAXRESOLVSORT];
char nsuffix[64];
char bsuffix[64];
char nsuffix2[64];
};
The struct can be added e.g. at the top of the file.
Adapt resolveHost
The changes here include the longer buffer for ip (INET6_ADDRSTRLEN). res_ninit moved from setup_dns_server into this method and is matched now with a res_ndestroy.
+ (NSString *)resolveHost:(NSString *)host usingDNSServer:(NSString *)dnsServer {
struct __res_state res;
char ip[INET6_ADDRSTRLEN];
memset(ip, '\0', sizeof(ip));
res_ninit(&res);
setup_dns_server(&res, [dnsServer cStringUsingEncoding:NSASCIIStringEncoding]);
query_ip(&res, [host cStringUsingEncoding:NSUTF8StringEncoding], ip);
res_ndestroy(&res);
return [[NSString alloc] initWithCString:ip encoding:NSASCIIStringEncoding];
}
Retrieving IPv6 addresses
The changes above are already sufficient if you just want to use a IPv6 address for your DNS server. So in query_ip there are no changes necessary if you still want to retrieve the IPv4 addresses.
In case you would like to retrieve IPv6 addresses from the DNS server also, you can do this:
void query_ip(res_state res, const char *host, char ip[]) {
u_char answer[NS_PACKETSZ];
int len = res_nquery(res, host, ns_c_in, ns_t_aaaa, answer, sizeof(answer));
ns_msg handle;
ns_initparse(answer, len, &handle);
if(ns_msg_count(handle, ns_s_an) > 0) {
ns_rr rr;
if(ns_parserr(&handle, ns_s_an, 0, &rr) == 0) {
inet_ntop(AF_INET6, ns_rr_rdata(rr), ip, INET6_ADDRSTRLEN);
}
}
}
Please note: we use here ns_t_aaaa to get AAAA resource records (quad-A record), because in DNS this specifies the mapping between IPv6 address and hostname. For many hosts, there is no such quad-A record, meaning you can just reach them via IPv4.
Call
You would call it e.g. like so:
NSString *resolved = [ResolveUtil resolveHost:@"www.google.com" usingDNSServer:@"2001:4860:4860::8888"];
NSLog(@"%@", resolved);
The result would the look like this:
Disclaimer
These are just simple example calls, that demonstrate the basic usage of the functions. There is no error handling.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is the title considered part of the question?
A question on SO was recently closed by 5 members of the community as "not a real question". If you look strictly at the body of the question, that's true, but if you consider the question's title, it was a straightforward question, albeit a rather simple one.
I'm wondering if the title is largely ignored for question-adequacy evaluation purposes or whether there is something else at work here.
Update: For easy reference, the title of the question was
How do I dry up this Ruby array of hashes?
and the code was:
def get_parts(row) [
@@line_parts[row][@time[0]].values[0],
@@line_parts[row][@time[1]].values[0],
@@line_parts[row][@time[2]].values[0],
@@line_parts[row][@time[3]].values[0] ]
end
Update: Since the question has been deleted, I figured I'd document the single, upvoted (8) answer, which was (I believe):
def get_parts(row)
(0..3).collect {|i| @@line_parts[row][@time[i]].values[0]}
end
which I thought did a nice job of demonstrating the power/elegance of Ruby's range, map and lambda features for someone who might only be familiar with more primitive languages.
A:
That the post contains a sentence that is grammatically a question doesn't mean that it's not appropriate to use the "not a real question" close reason. That said, the confusion over this has resulted in a dramatic change to the close reason text (largely just in what the close reasons are called, not so much what does and doesn't get closed).
In this case, the question that's being asked is overly broad; it's not a specific question.
Also note that SO isn't here for doing code reviews. It's not a place where you just dump a bunch of code an say "make it better". (That's what Code Review is for.)
Having said all of that, yes, the title matters. It should not be ignored when determining if a post should be closed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Handling multiple interrupts dsPIC
I have been thinking about my design for a while but couldn't figure out a better way to deal with buffer overrun in multiple interrupts.
A dsPIC33EP chip is connected to a TFT display, a UART sensor, a micro-SD card and a UART camera. The baudrate of the UART sensor is 921600 and the camera (50k per pic) is 57600. The SD card sector write (512 bytes) time is a little bit less than 2ms. The screen (EVE FT800) takes 20ms to update.
The goal is to respond to the UART sensor (at least every 30ms) and update screen accordingly (update labels) and at the same time write pictures into the SD card.
To break down the task, I have successfully saved multiple pictures to the SD card using interrupts when only camera and SD card are running.
The interrupt routine:
volatile unsigned char buff[512];
volatile unsigned int ptr=0;
volatile unsigned char EOF=0;
volatile unsigned char buffReady=0;
void ISR(){
static unsigned char temp;
temp=UART_Read();
buff[ptr++]=temp;
if(ptr==512){ptr=0;buffReady=1;}
if(...){EOF=1;}
}
While the program is stuck in a loop to check EOF flag
while(1){
if(buffReady){SD_Write_Sector(buff);buffReady=0;}//write 512 bytes of image to SD card
if(EOF){break;}//jump out if the image has been finished
}
My concern is, how do I incorporate the routines to update the screen while receiving data from the UART sensor? It looks like the buffReady flag must be checked constantly. Any delay between each check may lose couple bytes since they are overwritten with new bytes.
Since the picture size is around 50K and the baudrate is 57600, there will be six bytes coming from the camera every millisecond. If the screen introduces a 20ms delay in between, the picture will sure be corrupted.
I thought about using a larger buffer to store pictures but larger buffer needs more time to be written to the SD card.
How should I arrange update screen and write image to SD card?
A:
The dsPIC33EP provides a DMA interface to the UART (see chapter 8 of the datasheet). If you configure a buffer large enough for 20ms of data, you can configure the DMA to write into that buffer and then read the results between screen updates. Note that:
$$
57,600~bps \cdot 0.02~sec = 1152~bits = 144~bytes
$$
If you are using SPI to write to the SD card, DMA can also be used there to limit the CPU load during the larger writes (the driver might already have built-in DMA support).
Alternatively, you could perform the actual buffer read in the interrupt (instead of polling for a flag). This is a bad idea in most cases, however, for multiple reasons:
As little code as possible should be placed in interrupts, to reduce system latency;
It depends on the method being used to drive the display, but it is likely that read interrupts received during a screen refresh will result in visual glitches;
Function calls from within interrupts are rarely a good idea--they typically increase the pre- and post-interrupt code written by the compiler (to save off registers, etc.), and introduce opportunities for deadlock that would be more obvious with inline code.
In short, DMA is made for the situation you describe. It is usually a painful process to set up and debug multiple DMA transfers, but it will allow clean display refreshes due to the longer reads and writes without CPU intervention.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQLite to MS SQL DateTime
I am using SQLite to store some date times.
My SQLite database has the following to create the table
String CREATE_METERREADS_TABLE = "CREATE TABLE " + TABLE_METERREADS + " ("
+ KEY_MYID + " INTEGER,"
+ KEY_MYNUMBER + " FLOAT,"
+ KEY_MYDATE + " TEXT" + ")";
sqLiteDatabase.execSQL((CREATE_METERREADS_TABLE));
I am creating the date using the following and saving it in a class with a variable of type String:
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateRead = dateFormat.format(date);
I am then sending this through to SQL Server using a stored procedure as:
INSERT INTO MyData(ID, MYNumber, MYdate)
VALUES (@MYID, @MYNUMBER, cast(@MYDATE as datetime))
For some reason the day and month are getting switched so when my date is created you can see the format above but when it is put into SQL server it is showing as 2019-07-05 08:51:07.000 It is 7th of May when I am doing the insert.
A:
Instead of using the generic cast function to convert from string, use the convert function that allows you to set the exact date format that you want to use for that conversion.
INSERT INTO MyData(ID, MYNumber, MYdate)
VALUES (@MYID, @MYNUMBER, convert(datetime, @MYDATE, 120)
In your case, the format is the 120 (ODBC canonical) : yyyy-mm-dd hh:mi:ss
Here you have a complete list :
https://www.w3schools.com/sql/func_sqlserver_convert.asp
| {
"pile_set_name": "StackExchange"
} |
Q:
AngularJS: Is there a better way to achieve this than the one specified?
I use a template that generates a Bootstrap tab layout. Like below:
<div class="a">
<ul class="nav nav-bar nav-stacked" role="tabs">
<li><a href="#home"></a></li>
...
</ul>
<div class="tab-content">
<div id="home">abc</div>
...
</div>
</div>
Now this is pretty simple and straightforward tab navigation that can be hardcoded and achieved.
I have a dynamic ng-repeat on the ul's li and the tab-content's divs.
The JSON that I get from the REST service is something that contains the data for the tabs and the content to be displayed inside the tab-content within a single object. For eg:
{
"0": "a": [{ // a- tab data
"0": "abc", // abc - data to be displayed inside the tab-content
"1": "xyz"
}]
...
}
With such a JSON hierarchy, I basically need to ng-repeat twice. Once for the ul li and once for the tab-content as each object of the tab contains the data related to it.
So what I have done so far is:
<div class="a">
<ul class="nav nav-bar nav-stacked" role="tabs">
<li ng-repeat="foo in data"><a href="#home">{{foo.name}}</a></li>
...
</ul>
<div class="tab-content">
<div id="home" ng-repeat="foo in data">
<p ng-repeat="f in foo.desc">{{f}}</p>
</div>
...
</div>
</div>
EDIT:
So my question is, is there a smarter way to achieve this using a single ng-repeat rather than doing "foo in data" twice?
Sorry if my question isn't clear.
A:
Use ng-include with $templateCache rather than ng-repeat. For example:
var app = angular.module('foo', []);
function foo($templateCache)
{
var model =
{"data":
[
{"name": "Stack",
"desc": ["Exchange", "Overflow"]
}
]
},
cursor, i, bar = baz = "";
for (i = 0; i < model.data.length; i++)
{
bar = bar.concat("<li>", model.data[i].name,"</li>");
baz = baz.concat("<li>", model.data[i].desc.join().replace(/,/g,"</li><li>") );
}
$templateCache.put('name', bar);
$templateCache.put('desc', baz);
}
app.run(foo);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="foo">
<ul ng-include="'name'"></ul>
<ul ng-include="'desc'"></ul>
</div>
References
Tweak the Angular Test by Controlling the Template
AngularJS in a Groovy World
AngularJS Source: templateRequestSpec.js
AngularJS Source: ngIncludeSpec.js
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel Request::all() Should Not Be Called Statically
In Laravel, I'm trying to call $input = Request::all(); on a store() method in my controller, but I'm getting the following error:
Non-static method Illuminate\Http\Request::all() should not be called statically, assuming $this from incompatible context
Any help figuring out the best way to correct this? (I'm following a Laracast)
A:
The error message is due to the call not going through the Request facade.
Change
use Illuminate\Http\Request;
To
use Request;
and it should start working.
In the config/app.php file, you can find a list of the class aliases. There, you will see that the base class Request has been aliased to the Illuminate\Support\Facades\Request class. Because of this, to use the Request facade in a namespaced file, you need to specify to use the base class: use Request;.
Edit
Since this question seems to get some traffic, I wanted to update the answer a little bit since Laravel 5 was officially released.
While the above is still technically correct and will work, the use Illuminate\Http\Request; statement is included in the new Controller template to help push developers in the direction of using dependency injection versus relying on the Facade.
When injecting the Request object into the constructor (or methods, as available in Laravel 5), it is the Illuminate\Http\Request object that should be injected, and not the Request facade.
So, instead of changing the Controller template to work with the Request facade, it is better recommended to work with the given Controller template and move towards using dependency injection (via constructor or methods).
Example via method
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class UserController extends Controller {
/**
* Store a newly created resource in storage.
*
* @param Illuminate\Http\Request $request
* @return Response
*/
public function store(Request $request) {
$name = $request->input('name');
}
}
Example via constructor
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class UserController extends Controller {
protected $request;
public function __construct(Request $request) {
$this->request = $request;
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store() {
$name = $this->request->input('name');
}
}
A:
Inject the request object into the controller using Laravel's magic injection and then access the function non-statically. Laravel will automatically inject concrete dependencies into autoloaded classes
class MyController()
{
protected $request;
public function __construct(\Illuminate\Http\Request $request)
{
$this->request = $request;
}
public function myFunc()
{
$input = $this->request->all();
}
}
A:
use the request() helper instead. You don't have to worry about use statements and thus this sort of problem wont happen again.
$input = request()->all();
simple
| {
"pile_set_name": "StackExchange"
} |
Q:
excel SUMIFS with 3 criteria in two rows
I'm having trouble making SUMIFS to work for my sheets.
I have Sheet1 and Sheet2.
Sheet1 is a payment plan detail for accounts:
Row A is the ID of accounts.
Row D is accounts' payment terms.
Row H is what I want to sum depending on the following conditions:
1, Match the account ID in Sheet2
2, Only sum terms from P to Q in Sheet2.(>=P, <=Q)
I'm hoping to add this code at the end of each row in Sheet2
For example,
For Row 2 in Sheet2: account no. 180723540400645 needs to sum term 4-24.
We look at Sheet1, and for all rows in column A that equals "180723540400645", sum column H when column D is between 4 and 24.
My code is =SUMIFS(Sheet1!H:H,Sheet1!A:A,"=Sheet2!C2",Sheet1!D:D,">=P2",Sheet1!D:D,"<=Q2")But it keeps getting 0.
Sheet1
Sheet2
Thanks!
EDITS: I tried to just get the sum of all matching account ID in Sheet1, according to a comment. But it's still zero somehow... =SUMIFS(Sheet1!H:H,Sheet1!A:A,"=Sheet2!C3")
A:
Your formula should read:
=SUMIFS(Sheet1!H:H,Sheet1!A:A,Sheet2!C2,Sheet1!D:D,">="&P2,Sheet1!D:D,"<="&Q2)
| {
"pile_set_name": "StackExchange"
} |
Q:
trigger jQuery on load
I would like to have a fade between back ground images on my site.
I've found out how to trigger a fade with a click but I don't know how I can launch it automatically. I came up with this (JavaScript code):
$('div').click(function (e) {
$(this).parent().append('<div style="position:absolute; top: 25px; left: 25px; z-index: 1;" class="google"></div>');
$(this).fadeOut('slow');
});
function fade() {
$(this).parent().append('<div style="position:absolute; top: 25px; left: 25px; z-index: 1;" class="google"></div>');
$(this).fadeOut('slow');
};
see at: http://jsfiddle.net/bbqunfhu/1/ the first function is triggered on click and the second one should be called in the "onload" event of the page.
I would like to trigger the fade when the page gets loaded after let's say 10 seconds, I will want to have multiple images it goes through, how can I achieve that effect?
A:
You need make correct your jQuery reference/selector in a less relative terms. For example, you can call this in the load instead:
function fade() {
$('div.jquery').parent().append('<div style="position:absolute; top: 25px; left: 25px; z-index: 1;" class="google"></div>');
$('div.jquery').fadeOut('slow');
};
fade();
js.fiddle here.
You original code defined the fade() function but didn't call it. That's why the fade did not happen. You need to somehow call it.
In addition $(this).parent() could mean different things inside div is click callback and in a function.
| {
"pile_set_name": "StackExchange"
} |
Q:
Or Reduce An Array of Vectors
Needs to be placed on a real board, so will have to synthesize.
Using an old VHDL, libraries included:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use ieee.numeric_std.all;
use ieee.std_logic_misc.all;
Some signals:
type my_array is array (N-1 downto 0) of std_logic_vector(31 downto 0);
signal enable : my_array;
signal ored_enable: std_logic_vector(31 downto 0);
Signals get joined up in a generator:
my_gen: for i in 0 to (N-1) generate
woah: entity work.my_entity
port map(
clk => clk,
enable => enable(i)
);
end generate;
ored_enable <= or_reduce(enable); -- this fails
I'm just trying to create a std_logic_vector which holds the ored signals from the array. Any ideas how I can simply achieve this?
A:
First, I expect your last line to be a typo and read
ored_enable <= or_reduce(enable);
But this wouldn't work since or_reduce is only defined for std_logic_vector, not array of std_logic_vector. You can create your own reduce function:
function or_reduce(a : my_array) return std_logic_vector is
variable ret : std_logic_vector(31 downto 0) := (others => '0');
begin
for i in a'range loop
ret := ret or a(i);
end loop;
return ret;
end function or_reduce;
Just put it in your architecture's declarations and it should work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Css sticky menu height re sizing incorrectly
Why when I do scroll, height of the navigation is resizing and becoming bigger than it should be. How can I fix this problem?
Full code: https://jsfiddle.net/9Leq24dq/
$(function() {
var navOffset = $('nav').offset().top;
$("nav").wrap('<div class="nav-placeholder"></div>');
$(".nav-placeholder").height($("nav").outerHeight());
$(window).scroll(function() {
var scrollPos = $(window).scrollTop();
if (scrollPos >= navOffset) {
$("nav").addClass("fixed");
} else {
$("nav").removeClass("fixed");
}
});
});
body {
background-color: #eee;
}
#menu {
text-align: center;
}
header {
width: 950px;
height: 120px;
background-color: #1B78EA;
margin: 0 auto;
color: #fff;
text-align: center;
line-height: 80px;
}
header h1 {
line-height: 120px;
font-family: sans-serif;
}
nav {
background-color: #7B7B7B;
width: 950px;
margin: 0 auto;
}
.nav-palceholder {
margin: 0 0 20px 0;
}
.menu {
text-align: center;
}
.menu li {
list-style-type: none;
display: inline-block;
line-height: 49px;
cursor: pointer;
padding: 8px 15px 8px 15px;
}
nav li:hover {
background-color: #999999;
}
.menu a {
text-decoration: none;
font-size: 18px;
font-family: sans-serif;
text-align: center;
position: relative;
color: #eee;
font-weight: bold;
}
.content {
margin-top: 80px;
}
.content h1 {
text-align: center;
margin-top: 20px;
font-family: sans-serif;
margin-bottom: 40px;
}
.fixed {
position: fixed;
top: 0;
left: 0;
width: 100%;
text-align: center;
box-shadow: 0 6px 2px #646464;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<header>
<h1>Header</h1>
</header>
<nav class="menu">
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
<li><a href="#">Link 5</a></li>
</ul>
</nav>
</div>
<div class="content">
<h1>Content</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum
dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum
dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum
dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum
dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!</p>
<hr>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum
dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum
dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum
dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!</p>
<hr>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum
dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum
dolor sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor
sit amet, consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Id optio blanditiis, beatae voluptatem enim consequuntur, in inventore necessitatibus laborum, amet ab? Consequuntur fugiat dolorem dolore, amet dolores repudiandae, voluptates dicta!</p>
</div>
A:
Your browser is adding a margin to the ul when it is fixed. You could add this rule to remove that margin and keep the nav the same height:
.fixed ul{
margin:0px;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
HTTPS site perform ajax calls to native http desktop aplication
I'm working on web app that communicates with a locally installed desktop application to get certificate information from the user machine and perform digital signatures.
Currently it's possible to auto generate keys and perform digital signatures with these auto generated keys in javascript using window.crypto. However there is no way to through javascript or html to access the user keys issued by a vendor CA installed on OS or Firefox keystore to perform digital signatures, this is why we relay on installed native application.
This native application is a porting of an old java applet because - hopefully - soon this technology will be not supported for all major browsers (currently it's not already supported in Chrome since September 2015, and also is not supported in Edge), besides the java plugin itself it'll be deprecated in Java 9. Currently we've a Java Web Start working but it's a requeriment to have an alternative way to perform the signatures, since JNLP is not very user frendly way to do so: it requires to download each time a JNLP on a user machine with the signature configuration, there is no communication from browser to JNLP and it's necessary to perform AJAX polling to the backend to check if the signature is finished...
The native application is basically a local http server which exposes the business methods through a REST API, this way it's easy to use from our web app with simply making some AJAX calls an dealing with the result.
It works flawlessly when the web app is deployed in HTTP, the problem is that our web app is secured under HTTPS, but our native application is an HTTP server, so evidently for security reasons by default the major browsers block our AJAX calls from the web app to our native application due to mixed content.
Any CA vendors will issue a server certificate for a localhost domain, and furthermore since the native application is installed on client, the private key will be available on every client machine, so for sure a certificate issued by a official CA it's not a possibility. Also note that our native application must work on a heterogeneous environments: different OS, different browser, different networks so a proxy solution for the SSL is also not an option.
A possible solution which come to my mind is to generate a self-signing certificate and configure our native application to work as an HTTPS server. However I see a flaw in this solution: the native application automatically or the client manually must install this certificate in the client SO trust store or in the firefox trust store, this is a security concern because you're adding a self-signed certificate in a trust store.
My question are:
Installing a self-signed server certificate for localhost directly in the trust store it's a security concern, but how is it really dangerous/exploitable? If you issue the cert for CN=127.0.0.1 if there is no proxy on the network or hosts edited it's not possible to a third party server serves content for you there, isn't? Is this solution as bad as it sounds?
There is an alternative way to communicate between web app in HTTPS with a native application in a easy manner, user-friendly way and supported for all major browsers?
A:
THE ORIGINAL SOLUTION IS NOT VALID ANYMORE!
Updated Solution
Everyone doing this (github, spotify, blizzard, dropbox, etc) have all seen their certificate revoked last year because the private key was stored locally and considered compromised.
There are 2 workarounds:
create, locally, an ssl certificate binded to localhost/127.0.0.1 and install it in the OS trusted keystore.
In the Secure Contexts Spec, localhost/127.0.0.1 is now considered a potentially trustworthy origin. This means that an HTTPS page calling 127.0.0.1 over http is NOT blocked by Mixed Content. Tested in Edge, Chrome and Firefox. Unfortunatly, Microsoft team has not backported this fix to IE.
If origin’s host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return "Potentially Trustworthy".
Original Solution
You get a standard certificate from a CA for a domain like local.myapp.com and you associate this host with 127.0.0.1 in your dns.
This will enable https calls from your web page to your installed app.
Please note that there may be security issues with this. In fact Chromium intend to block these calls to localhost (or add an option to opt-in --> https://bugs.chromium.org/p/chromium/issues/detail?id=378566). But multiple sites are doing this:
Spotify (web player - desktop app) : *.spotilocal.com
Github (open file in Github for Mac) : ghconduit.com
Dropbox : www.dropboxlocalhost.com
Explanation of how Spotify does it: http://cgbystrom.com/articles/deconstructing-spotifys-builtin-http-server/
With the requirement to use HTTPS, a valid SSL certificate is needed
to avoid browsers complaining. Spotify has worked around this problem
by registering a domain (*.spotilocal.com) that merely points to
127.0.0.1. But rather than connecting to the top domain, they use a wildcard domain and connect to a random subdomain each time (for
example abcrjdknsa.spotilocal.com). The reason for this is to avoid
the browser’s max connection limit per domain, enabling more tabs in
the browser to concurrently use their API at the cost of an extra DNS
lookup.
| {
"pile_set_name": "StackExchange"
} |
Q:
Easiest way to write overloads
Whats the easiest way to write overloads for methods where I dont really care in what order the user inputs the paramaters and where the type is always differently?
For example:
public void DoSomething(String str, int i, bool b, DateTime d)
{
//do something...
}
Now I would like to have the possibility that you can call the method in any possible way, for example:
DoSomething(1, DateTime.Now, "HelloWorld", false);
DoSomething(DateTime.Now, 1, "HelloWorld", false);
DoSomething("HelloWorld", DateTime.Now, 1, false);
DoSomething(false, DateTime.Now, "HelloWorld", 1);
//and so on...
Is there really no other way, than to duplicate the method over and over again and rearrange the parameters?
I specially think its annoying when you specify default values for parameters and either need to specify the name when calling the method, or set the defaults.
A:
First of all, if your methods grow in parameters count you should seriously begin thinking about creating a specific class that can hold all this data:
public class MyData
{
public string Str {get;set;}
public int I {get;set;}
public bool B {get;set;}
public DateTime D {get;set;}
}
and have a single method signature:
public void DoSomething(MyData data)
{
//...
}
and you may use it like this:
DoSomething(new MyData {I = 1, Str = "Hello", D = DateTime.Today, B = false});
This approach has the additional advantage that it provides much more scalability, since you can add any amount of new properties into that class without having to change your method signatures at all.
Other than that, see Named Parameters.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unknow option javacomplete#complete when using vim to edit java files
I have set omnifuc in my .vimrc file :
setlocal omnifunc = javacomplete#complete
Then the exception comes out when i editing any file :
E518: Unknown option: javacomplete#complete
A:
Remove the space after the =. With this space vim is interpreting the javacomplete#complete as a vim option.
Here is an excerpt from vim's help on :set-args:
:se[t] {option}={value}
...
White space between {option} and '=' is allowed and
will be ignored. White space between '=' and {value}
is not allowed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add a method jQuery Validation
how can I write a new method using the addMethod() method? I want to validate a phone number that it starts with a 0 and its length is 10. What i've tried so far:
function cell(element, value){
if (!/^[0]\d{9}$/.test(element).val()) {
return false;
}
else {
return true;
}
}
$.validator.addMethod("cell", cell, "This phone number is incorrect");
and:
$("#signupForm").validate({
rules: {
cell: {
required: true,
digits: true,
cell: true
}
}
})
And in the messages am I supposed to write a message for 'cell' to? Thanks!
A:
add custom method this way-
$.validator.addMethod("cell", function (value, element) {
if (!/^[0]\d{9}$/.test(element).val()) {
return false;
}
else {
return true;
}
}, 'This phone number is incorrect');
and your validation method-
$("#signupForm").validate({
rules: {
cell: {
required: true,
digits: true,
cell: true
}
}
});
it should work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Missing ";" before 'namespace' and ";" before 'using'
So I am working on a program that is due tomorrow and for some reason I keep getting this 2 errors, if I click on the first one it takes me to the iostream file and right before the _STD_BEGIN it wants me to put ";" but if I do that it messes up the file in the library so I am pretty sure I do not have to do that, the second error is in my main.cpp and it points to using namespace std; and it wants me to put a ";" before it =, if I do so the error disappears and it keeps pointing at the iostream error....
I have no idea what to do and my deadline is tomorrow.
This is my main.cpp include section with the modification to using namespace std
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <stdio.h>
#include "Package.h"
;using namespace std;
A:
Look for a class or struct definition in Package.h that's missing its semicolon. ie.
class act
{
// yadda
} // no semicolon here
Then add the missing semicolon.
A:
When you get a "missing ;type error on a line that follows closeley behind a bunch of#includestatements, the likely culprit is a missing;` in one of the header files. To find out which, start at the last include file, Package.h. You'll surely find a missing semicolon there. It's probably missing after a class declaration, as if you had written:
class Foo
{
}
instead of
class Foo
{
};
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql ORDER BY and CASE casts INT to CHAR?
For a stored procedure with configurable sort order (_Sort parameter), i use code like this:
SELECT * FROM distances
ORDER BY
CASE _Sort
WHEN 1 THEN uid
WHEN 2 THEN NULL
WHEN 3 THEN name
WHEN 4 THEN NULL
WHEN 5 THEN distance
WHEN 6 THEN NULL
ELSE distance
END ASC,
CASE _Sort
WHEN 2 THEN uid
WHEN 4 THEN name
WHEN 6 THEN distance
ELSE NULL
END DESC
in which uid is INT and distance is DOUBLE.
But if _Sort = 1, uid is ordered like it was a CHAR e.g.
200
207
25
4
Same thing for distance.
Casting to unsigned and decimal did not help.
ORDER BY uid ASC does the right thing, i.e. 4, 25, 200, 207
Any idea?
A:
Try this solution (edited) -
SELECT * FROM distances
ORDER BY
IF(_Sort = 1, uid, 0),
IF(_Sort = 2, NULL, 0),
IF(_Sort = 3, name, 0),
IF(_Sort = 4, NULL, 0),
...
| {
"pile_set_name": "StackExchange"
} |
Q:
Why can't Haskell infer Tree type?
I followed the book to define Tree data type, but show doesn't work correctly. Why?
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show)
test = show EmptyTree
gives the error message:
No instance for (Show a0) arising from a use of ???show???
The type variable ???a0??? is ambiguous
Note: there are several potential instances:
instance Show a => Show (Tree a)
-- Defined at /Users/gzhao/Documents/workspace/hsTest2/src/Tree.hs:3:62
instance Show Double -- Defined in ???GHC.Float???
instance Show Float -- Defined in ???GHC.Float???
...plus 25 others
In the expression: show EmptyTree
In an equation for ???test???: test = show EmptyTree
A:
The problem is that EmptyTree has type Tree a for any type a. Even though it won't actually affect the final output, the compiler wants to know which a you mean.
The simplest fix is to pick a specific type, e.g. with show (EmptyTree :: Tree ()). This uses the unit type (), which is in some sense the simplest possible type, but you can also use any other type that has a Show instance, like Int, String etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I add methods to a Groovy base Script dynamically, from Java?
Although it's not standard practice, I'm curious if it's possible to inject methods into a GroovyShell compilation context.
The idea is to have something like (in Java):
GroovyShell shell = new GroovyShell();
Script script = shell.parse("test()");
script.run();
Where I'd like to dynamically add methods that are invokable, where test() has been listed.
I've experimented a bit with messing with the Script metaClass, but I don't see a way to actually manipulate the metaClass from Java. In particular, calling script.getMetaClass().getMethods().add(...) throws an UnsupportedOperationException.
In essence, I'd like to define DSL call-points that invoke Java methods rather than Groovy-based ones. I'm willing to write this part in Groovy (and am aware of how to do this), but I'm genuinely curious if this is a viable alternative approach, or if it's not, what the pitfalls are.
In short: how can I dynamically define a method that GroovyShell knows about?
A:
There are two very simple solutions to this:
a) the typical "scripting" approach
b) the more groovy-ish approach
a) is simply prepending your script-String with a String that defines your methods.
b) is putting a reference into the binding, e.g. under the name "test". The value of that reference is a Closure object or any other object that has a "call(args)" method.
When while executing the Script, Groovy sees "test()", it will first try to find such a method and if no such method is there it tries to resolve "test" as a property and will find it in the binding. Then it will call the so resolved reference (closure) with the provided arguments (if any).
There are even more advanced options like providing a CompilerConfiguration, which are all listed in the DSL chapter of "Groovy in Action, 2nd edition" (shameless plug).
| {
"pile_set_name": "StackExchange"
} |
Q:
populate primefaces datatable from a nativeQuery
im learning jsf enviroment, sry if this is kind of easy case for you ,
Im trying to populate a primefaces datatable from a native query , this is what i got at the moment
//My native query is defined in my entity
@NamedNativeQueries({@NamedNativeQuery(name="Tallt089.bandejaCitas",
query ="select bandeja.ep_id_tallt089 idBandeja ...)})
...
...
I call this nativeQuery this way
public List**<TablaBandejaCitas>** bandejaCitas(String cia, String agencia, String division) {
Query query = em.createNamedQuery("Tallt089.bandejaCitas");
query.setParameter(1,cia);
query.setParameter(2,agencia);
query.setParameter(3,division);
return query.getResultList();
//this works fine retrieves correctly my query
}
And use it on my managedBean
public List**<TablaBandejaCitas>** bandejaCitas(String compania,
String agencia,String division){
return agendamientoSession.bandejaCitas(compania,agencia,division);
}
then referenced this on my jsf page like this
<p:dataTable id="bandeja_citas"
value="#{AgendamientoMBean.bandejaCitas(UsuarioMBean.compania,UsuarioMBean.agencia,
UsuarioMBean.divisionPK.diDivision)}"
var="bandeja"
paginator="true" rows="15" >
<f:facet name="header">
Bandeja Citas por confirmar/Llamadas por realizar
</f:facet>
<p:column headerText="Id Bandeja" >
<h:outputText value ="#{bandeja.idBandeja}"/>
</p:column>
<p:column headerText="Cliente" sortBy="#{bandeja.cliente}"
filterBy="#{bandeja.cliente}">
<h:outputText value ="#{bandeja.cliente}"/>
</p:column>
...
...
...
</p:dataTable>
I realized that the var property needs something like mapped of the fields of the query because the warnings on the jsf page tell me that this is an unkwon property
<h:outputText value ="#{bandeja.**cliente**}"/>
I dont know how to store the query in that variable so the data can be displayed
right now i got a for input string exception like the component its reading raw data instead of formmatted list with the correct variable filled with the query fields ..
hope you can understandme
apreciatte your comments in advance :D
A:
Ok, I solved this little problem. I did it by creating an entity class (even is not a table in the DB) with the columns that I select in the nativeQuery and then using this class as the resultClass option in the native:
resultClass=com.talleresZeusWeb.entidades.BandejaCitas.class
I was trying to make that sqlresultsetmapping annotation but don't know to use it in this case.
Hope someone finds this useful at some point, thank you for your responses @Rich
| {
"pile_set_name": "StackExchange"
} |
Q:
Can .Net be used to deal with PDF files natively?
Does .Net have any facilities to work with PDF files natively (such as return a page count) or must an external library be used?
A:
No, there is no built-in support for working with PDFs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Server in Mvc.Controller
I have my own inherited App.Controller from Mvc.Controller which then all of my controllers inherit from. I wrote a provider utilizing an interface and implemented it as MyService and the constructor takes the Server property of Mvc.Controller which is of HttpServerUtilityBase.
However, I instantiate MyService in App.Controller's constructor. The problem is that the Server property of the Controller is null when constructing MyService. I have used public Controller () : base() { } to get the base to be constructed. However, Server remains null.
I would like to avoid Web.HttpContext.Current.Server if possible.
Has any one have a work around for this problem?
Edit: Well, I have implemented tvanfosson's suggestion, and when my app constructs MyService in the property get method, Server is still null.
Edit 2: Nevermind, I was a goof. I had another Controller using Server aswell and did not change that. Case closed.
A:
Use delayed initialization to construct your service.
private MyService service;
public MyService Service
{
get
{
if (this.service == null)
{
this.service = new MyService(this.Server);
}
return this.service;
}
}
Then, your service isn't actually instantiated until it is used in the controller action and by that time the Server property has been set.
| {
"pile_set_name": "StackExchange"
} |
Q:
Drawing a line in Opengl not displaying C++
I am trying to draw a line straight across my window The screen colour is working but the line doesn't seem to draw. I am fairly certain this is because I might of set the position wrong and the line is being clipped from the window but I'm not sure how to fix this.
my full code
#include <GL\glew.h>
#include <GLFW/glfw3.h>
#include <GL\glut.h>
#include <glm.hpp>
#include <GL\freeglut.h>
#include <GL\GL.h>
#include <IL/il.h>
using namespace std;
int main() {
int windowWidth = 1024, windowHeight = 1024;
if (!glfwInit())
return -1;
GLFWwindow* window;
window = glfwCreateWindow(windowWidth, windowHeight, "electroCraft", NULL, NULL);
glfwMakeContextCurrent(window); // stes the specified window as active INACTIVE SCREEN IF WINDOW NOT CURRENT!!!!
if (!window) {
glfwTerminate();
printf("Screen failed to start. ABORTING...\n");
return -1;
}
glViewport(0, 0, windowWidth, windowHeight);
glOrtho(0, windowWidth, 0, windowHeight, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_DEPTH_TEST);
while (!glfwWindowShouldClose(window)) {
glClearColor(62.0f / 255.0f, 85.9f / 255.0f, 255.0 / 255.0, 0.0);
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
//begin drawing
glBegin(GL_LINE);
glVertex2f(20, 100);
glVertex2f(600, 100);
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
A:
As mentioned in the comment you've to use GL_LINES rather than GL_LINE, because GL_LINE is not a valid Primitive type.
glBegin(GL_LINES); // <----
glVertex2f(20, 100);
glVertex2f(600, 100);
glEnd();
But there is another issue. The default matrix mode is GL_MODELVIEW (see glMatrixMode), so the orthographic projection is set to the model view matrix and is overwritten by the identity matrix (glLoadIdentity). You've to set the matrix mode GL_PROJECTION, before glOrtho:
glMatrixMode(GL_PROJECTION); // <----
glOrtho(0, windowWidth, 0, windowHeight, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
| {
"pile_set_name": "StackExchange"
} |
Q:
Cache AND display images php
I am using a php script to display images stored as blobs in my database.
I used to display them with the following script.
<?php
if(!empty($_GET['user_id'])){//script to display an image from the database you basicly just get the id from the picture in matter and fucking acess it
include_once "DBH.php";
//Get image data from database
$id = mysqli_real_escape_string($conn, $_GET['user_id']);
$result = $conn->query("SELECT image FROM profilePictures WHERE user_id = $id");
if($result->num_rows > 0){
$imgData = $result->fetch_assoc();
header("Content-type: image");
echo $imgData['image'];
}else{
echo 'Image not found...';
}
}
?>
In the context where
<img src = 'displayProfilePicture.php?user_id=n'>
The div containing the divs are updated frequently and to update the users image seems like alot of unnecessary processing. I want to cache the profilepictures in the webpage so that i dont have to query them from the database every time. I started reading alot about how you could cache the images but could not find any content on how to display the cached images.
This is a problem for me as the images flicker for a bit every time the img is updated with the php script. In an optimal world i see that the img load one time and then after that it does not have to load.
The context wich i use the display img script is in a chat that is updated with a timer-interval within an ajax-request
$("#chatlogs").load("logs.php");
logs.php
if(isset($_SESSION['chatRoomId'])){
while ($extract = mysqli_fetch_array($result1))
{
$from = $extract['from'];
//make an object to echo.
if($from == $id){
echo "<div class='chatContainer self'>
<div class = 'imgContainer'>
<img src='displayProfilePicture.php?user_id=$selfId'>
</div>
<div class='content'>
<div class = 'message'>
". $extract['msg'] ."
</div>
</div>
</div>";
}else{
echo "<div class='chatContainer friend'>
<div class = 'imgContainer'>
<img src='displayProfilePicture.php?user_id=$guestId'>
</div>
<div class='content'>
<div class = 'message'>
". $extract['msg'] ."
</div>
</div>
</div>";
}
}
}
A:
I think this is what you looking for:
<?php
if(empty($_GET['user_id']) || !preg_match( '/^[0-9]+$/' , $_GET['user_id'])){
header( '400 Bad Request' );
exit(1);
}
include_once "DBH.php";
$user_id = intval( $_GET['user_id'] );
$result = $conn->query("SELECT image FROM profilePictures WHERE user_id = $user_id");
if($result->num_rows == 0){
// Not Found
header('404 Not Found');
exit(1);
}
$imgData = $result->fetch_assoc();
header("Content-type: image");
$cache_for = 3600; // One hour in seconds
$cache_until = gmdate("D, d M Y H:i:s", time() + $cache_for) . " GMT";
header("Expires: $cache_until");
header("Pragma: cache");
header("Cache-Control: max-age=$cache_for");
echo $imgData['image'];
exit(0);
Comments
First I checked if the user_id is supplied in the request, if so then check if it was a valid number if it doesn't then respond with a 400 error.
And also I have removed a SQLi in your code src='displayProfilePicture.php?user_id=-1 or 1=1.
And I have set the caching headers, so the browser will cache the image for an hour.
| {
"pile_set_name": "StackExchange"
} |
Q:
Select random node and add to label
i'm new to c# and trying to make a little randomizer.
I want to select a random node where mystatus = 1 and show series_title and series_image in label.
Xml :
<?xml version="1.0" encoding="UTF-8"?>
<myanimelist>
<myinfo>
<user_id>5144371</user_id>
<user_name>berefin</user_name>
<user_watching>116</user_watching>
<user_completed>100</user_completed>
<user_onhold>3</user_onhold>
<user_dropped>0</user_dropped>
<user_plantowatch>52</user_plantowatch>
<user_days_spent_watching>18.65</user_days_spent_watching>
</myinfo>
<anime>
<series_title>Cowboy Bebop</series_title>
<series_image>https://myanimelist.cdn- dena.com/images/anime/4/19644.jpg</series_image>
<my_status>1</my_status>
</anime>
<anime>
<series_title>Naruto</series_title>
<series_image>https://myanimelist.cdn-dena.com/images/anime/13/17405.jpg</series_image>
<my_status>1</my_status>
</anime>
<anime>
<series_title>One Piece</series_title>
<series_image>https://myanimelist.cdn-dena.com/images/anime/6/73245.jpg</series_image>
<my_status>2</my_status>
</anime>
The Code so far :
private void btnRandom_MouseClick(object sender, MouseEventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load("https://myanimelist.net/malappinfo.php?u=berefin&status=all&type=anime");
XmlNodeList list = doc.SelectNodes("/myanimelist/anime");
//string content = doc.InnerXml;
foreach (XmlNode node in list)
{
// Not sure what to do here
Random random = new Random();
string my_status = node["my_status"].InnerText;
if (my_status == "1")
{
string series_title = node["series_title"].InnerText;
string series_image = node["series_image"].InnerText;
}
}
}
How can i use random with xml node ?
A:
There exists 2 approaches, I will describe the one I like more. The other one would work the way that You will get numbers of elements that fit and then during reading You would just find the one with the number You've get from Random.
Like:
Random r = new Random();
//some code to get counted elements
int myOpt = r.Next( CountOfElements );
// some code to run through elemenets
if (myOpt == iterator)
{
//get the details about Anime
}
Fill (materialize) into an array(list) and then randomly pick one
This one is ideal, if You want to do some work with the array later on, e.g. modify it or do any work. The best is to created class with the definition of Your objects, create array of this objects and then fill it up. Last thin is to find random entity from the array.
Class definition:
public class Anime
{
public string series_title { get; set; }
public string series_image { get; set; }
public int my_status { get; set; }
}
Filling the list:
private void btnRandom_MouseClick(object sender, MouseEventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load("https://myanimelist.net/malappinfo.php?u=berefin&status=all&type=anime");
XmlNodeList list = doc.SelectNodes("/myanimelist/anime");
var arr = new List<Anime>();
foreach (XmlNode node in list)
{
arr.Add(new Anime()
{
series_title = node["series_title"].InnerText;
series_image = node["series_image"].InnerText;
my_status = Convert.ToInt32(node["my_status"].InnerText);
}
}
//here is all Your animes in list -> arr
}
In the end You can randomly pick one:
public Anime PickRandom(List<Anime> list)
{
Random random = new Random();
return list[random.Next(list.Count)];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Bell Inequalities - Expectation Values
I'm currently reading Loopholes in Bell Inequality Tests of Local Realism by Jan-Ake Larsson
https://arxiv.org/abs/1407.0363
On Page 6, Equation 7, he has a short proof, where I am having a hard time seeing through the math. I'll re-state here for convenience:
$ \lvert E(A_{2}B_{1}) - E(A_{2}B_{2}) \rvert = \lvert E(A_{2}B_{1} + A_{2}B_{1}A_{1}B_{2}) \rvert \leq E(\lvert A_{2}B_{1}(1 + A_{1}B_{2}) \rvert ) = 1 + E(A_{1}B_{2}) $
where
$ A_{1}B_{1} = -1 $
and
$E(A) = \int A( \lambda ) \rho ( \lambda) d \lambda $
I'm not seeing how he goes from the 2nd expression on the LHS of the less-than-or-equal sign to the third expression on the RHS of the less-than-or-equal sign. I suspect I am missing something on the properties of expectation values. Mainly, I think the absolute signs (|) moving from outside of the E()'s to the inside of the E()'s have me the most confused. Further, I don't see how he goes from the 3rd expression to the 4th, either.
Can anyone offer any clarification here?
A:
From 2nd to 3rd expression:
It is well known that:
$$\left|\int f(x)dx\right| \leq \int \left|f(x)\right| dx.$$
Here you can find the reference for this fact.
Now, you have that:
$$\lvert E(A_{2}B_{1} + A_{2}B_{1}A_{1}B_{2}) \rvert = \left|\int (A_{2}B_{1} + A_{2}B_{1}A_{1}B_{2})\rho(\lambda)d\lambda \right| \leq \\
\leq \int \left|(A_{2}B_{1} + A_{2}B_{1}A_{1}B_{2})\rho(\lambda)\right|d\lambda = \int \left|A_{2}B_{1}(1 + A_{1}B_{2})\rho(\lambda)\right|d\lambda.$$
Since $\rho(\lambda) \geq 0$ by definition (it is a distribution), then $\rho(\lambda) = |\rho(\lambda)|$, and hence:
$$\int \left|A_{2}B_{1}(1 + A_{1}B_{2})\rho(\lambda)\right|d\lambda = \\
\int \left|A_{2}B_{1}(1 + A_{1}B_{2})\right|\rho(\lambda)d\lambda = E(|A_{2}B_{1}(1 + A_{1}B_{2})|).$$
From 3rd to 4th expression:
Suppose that $B_1=1$. Then:
$$E(|A_{2}B_{1}(1 + A_{1}B_{2})|) = E(|A_{2}(1 + A_{1}B_{2})|) = E(|A_{2}||1 + A_{1}B_{2}|).$$
Since $A_2 \in \{-1, +1\}$, then $|A_2| = 1$, and hence:
$$E(|A_{2}B_{1}(1 + A_{1}B_{2})|) = E(|1 + A_{1}B_{2}|).$$
Since $B_1 = 1$, then $A_1 = -1$, and the term $1 + A_{1}B_{2}$ can be equal to $0$ or to $2$. In each case, it is positive, so we can drop the modulus:
$$E(|A_{2}B_{1}(1 + A_{1}B_{2})|) = E(1 + A_{1}B_{2}).$$
Last steps are easy...
$$E(|A_{2}B_{1}(1 + A_{1}B_{2})|) = E(1 + A_{1}B_{2}) = E(1) + E(A_1 B_2) = 1 +E(A_1 B_2).$$
Now suppose that $B_1 = -1$. Then:
$$E(|-A_{2}(1 + A_{1}B_{2})|) = E(|A_{2}(1 + A_{1}B_{2})|).$$
Using the same reasonings of above, we get that:
$$E(|-A_{2}(1 + A_{1}B_{2})|) = E(|1 + A_{1}B_{2}|).$$
$A_1$ is $1$, and $1 + A_{1}B_{2}$ can be $0$ or $2$. We can drop the modulus... etc... etc... Even in this case, we get that $E(|A_{2}B_{1}(1 + A_{1}B_{2})|) = 1 + E(A_{1}B_{2})$.
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql_real_escape_string not being used with given regex
I am using a dataHandler library to handle all of my db inserts / updates, etc.
The library has the following functions:
function prepareValue($value, $connection){
$preparedValue = $value;
if(is_null($value)){
$preparedValue = 'NULL';
}
else{
$preparedValue = '\''.mysql_real_escape_string($value, $connection).'\'';
}
return $preparedValue;
}
function parseParams($params, $type, $connection){
$fields = "";
$values = "";
if ($type == "UPDATE"){
$return = "";
foreach ($params as $key => $value){
if ($return == ""){
if (preg_match("/\)$/", $value)){
$return = $key."=".$value;
}
else{
$return = $key."=".$this->prepareValue($value, $connection);
}
}
else{
if (preg_match("/\)$/", $value)){
$return = $return.", ".$key."=".$value;
}
else{
$return = $return.", ".$key."=".$this->prepareValue($value,
$connection);
}
}
}
return $return;
/* rest of function contains similar but for "INSERT", etc.
}
These functions are then used to build queries using sprintf, as in:
$query = sprintf("UPDATE table SET " .
$this->parseParams($params, "UPDATE", $conn) .
" WHERE fieldValue = %s;", $this->prepareValue($thesis_id, $conn));
$params is an associative array: array("db_field_name"=>$value, "db_field_name2"=>$value2, etc.)
I am now running into problems when I want to do an update or insert of a string that ends in ")" because the parseParams function does not put these values in quotes.
My question is this:
Why would this library NOT call prepareValue on strings that end in a closed parenthesis? Would calling mysql_real_escape_string() on this value cause any problems? I could easily modify the library, but I am assuming there is a reason the author handled this particular regex this way. I just can't figure out what that reason is! And I'm hesitant to make any modifications until I understand the reasoning behind what is here.
Thanks for your help!
A:
Please note that inside prepareValue not only mysql_real_escape_string is applied to the value but it is also put inside '. With this in mind, we could suspect that author assumed all strings ending with ) to be mysql function calls, ie:
$params = array(
'field1' => "John Doe",
'field2' => "CONCAT('John',' ','Doe')",
'field3' => "NOW()"
);
Thats the only reasonable answer that comes to mind.
| {
"pile_set_name": "StackExchange"
} |
Q:
NSFetchedResultsController ignores fetchLimit after performFetch
I have a tabbed application, that has 2 tabs with 2 UITableView.
I also have 2 NSFetchedResultsController type objects, but both of them are on the same entity with different ordering and different fetch limit.
When I download more objects from the internet and insert them to the database, my NSFetchedResultsController type objects will ignore the fetchLimit. For the first one I set a fetchLimit of 10 and for the second I set a fetchLimit of 50. Initially I have 10 objects in the database. Everything is fine. After I download more 40 objects the first one also loads the more 40 objects, but it has a fetchLimit of 10.
What's wrong with this?
A:
NSFetchedResultsController ignoring fetchLimit in case if it observers context changes.
I think that it's not so simple operation to correctly update table via momc observation, when you're restricted to fetchlimit.
SOLUTION #1
So, in case if big update has been occured, you should re-fetch data.
So you should do something like this in FRC delegate:
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
[self.tableView endUpdates];
if (bigChangesPeformed) {
NSError * error;
// Re-fetching to get correct fetch limit
[self.fetchedResultsController performFetch:&error];
if (error) {
// bla-bla-bla
}
[self.tableView reloadData];
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to connect to a bigtable emulator using cbt command line
I ran the command gcloud beta emulators bigtable start but when i ran the command cbt listinstances, i got the error below
Getting list of instances: rpc error: code = Unimplemented desc = unknown service google.bigtable.admin.v2.BigtableInstanceAdmin
How can i use cbt command to connect my local bigtable emulator?
The emulator command https://cloud.google.com/sdk/gcloud/reference/beta/emulators/bigtable/start
The cbt command
https://cloud.google.com/bigtable/docs/go/cbt-reference
A:
The Cloud Bigtable emulator doesn't support any instance-level operations (CRUD for instances). You can use any arbitrary instance name when connecting to it and start by creating a table.
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS - Unwanted Border-Bottom
Just doing a little touch up before finishing a conversion project and I have an unwanted border-bottom that needs to be removed.
The base code is:
a:link, a:visited { color: #000000; text-decoration: none; border-bottom: 1px dotted #c6132e; }
However, I don't want it to show up on all links, particularly the main navigation. When you click on any of the links there it shows up.
On line 56 of the css I placed this code to remove the border-bottom, but it doesn't seem to be working:
ul#main_nav li a:link,
ul#main_nav li a:visited
ul#main_nav li a:hover,
ul#main_nav li a:active { border-bottom: none; }
Would appreciate a second set of eyes to look this over and help me find the solution.
Thanks!
BTW: here is the link: http://www.rouviere.com/aav/index.html just click on any of the main navigation buttons.
A:
You missed a comma. Should be:
ul#main_nav li a:link,
ul#main_nav li a:visited,
ul#main_nav li a:hover,
ul#main_nav li a:active { border-bottom: none; }
Your rule is not applying to visited links.
A:
As Timhessel said, it's your focus outline... although this isn't recommended you could add this to get rid of it:
ul#main_nav li a { outline-color: transparent; }
| {
"pile_set_name": "StackExchange"
} |
Q:
UI library less override
I need to override a less file in /lib/web/css/source/lib/ because _navigation.less contains a mixin .lib-main-navigation-desktop() which use some !important rules that brooke the submenu positioning.
What is the "right" way to do it?
A:
The solution is to add
app/design/frontend/{Vendor}/{Theme}/web/css/source/lib/_navigation.less
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular select and ng-model
I'm trying to populate a select field with content from an array. I'm confused as to what exactly my "model" is.
I'm looking to access content from ctrl.contents which is an array of objects. I assume this is my "model".
ViewPage.html
<div>
<select ng-model="ctrl.contents"
ng-options="content.title.name in content.title.name as content in contents">
</select>
</div>
var ctrl = this from ViewPage.controller.js
If I was to console.log(ctrl.contents) from ViewPage.controller.js the array of objects would be returned:
[
> 0: ContentViewModel
> title: Object // Each numbered array object has similar contents
name: "Thomas"
...
> 1: ContentViewModel
> 2: ContentViewModel
> 3: ContentViewModel
]
I can't seem to get the select field populated with anything. Am I getting the ng-model wrong?
A:
Your 'model' is a separate variable that will contain the selected value of your select menu - set it to something like ctrl.selectedItem.
Your ng-options parameters should look like this:
ng-options="content.title.name for content in ctrl.contents"
For more info, refer to this example - checkout both the html and js in app.js.
| {
"pile_set_name": "StackExchange"
} |
Q:
API for network
I have to write a program with c# to find the printers which have same logos over netbios protocol
The printers are in different subnets and they are netbios enabled
They have been connected with each other by workgroup network
Is there any special API for this aim?
A:
This sounds like a project that needs WMI.
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating an ImmutableMap> stream Collector
I am frequently running into situations where I need a map of multi-maps for the sake of efficiency. I'd prefer to use Guava's ImmutableMap and ImmutableMultimap to accomplish this.
I have borrowed and created several Collector implementations for Guava so I can leverage Java 8 streams. For example, here is a collector for an ImmutableListMultimap.
public static <T, K, V> Collector<T, ?, ImmutableListMultimap<K, V>> toImmutableListMultimap(
Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends V> valueMapper) {
Supplier<ImmutableListMultimap.Builder<K, V>> supplier = ImmutableListMultimap.Builder::new;
BiConsumer<ImmutableListMultimap.Builder<K, V>, T> accumulator = (b, t) -> b
.put(keyMapper.apply(t), valueMapper.apply(t));
BinaryOperator<ImmutableListMultimap.Builder<K, V>> combiner = (l, r) -> l.putAll(r.build());
Function<ImmutableListMultimap.Builder<K, V>, ImmutableListMultimap<K, V>> finisher = ImmutableListMultimap.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
I would like to create a very similar Collector for my current problem. I want my collector to create an ImmutableMap<P,ImmutableMultimap<C,V>>, where P is the parent key of the main map and C is the child key of the child map. Two Function lambdas would be provided to map these keys for each T item.
This is much easier said than done. All I did productive so far is create the method stub.
public static <T, P, C, V> Collector<T, ?, ImmutableMap<P, ImmutableMultimap<C,V>>> toPartitionedImmutableMultimap(
Function<? super T, ? extends P> parentKeyMapper,
Function<? super T, ? extends C> childKeyMapper,
Function<? super T, ? extends V> valueMapper) {
}
Because the Guava immutable collection builders do not allow lookups, I found myself using mutable hashmaps to be able to look up previously captured values so I would only create a new ImmutableMultimap when the P key was absent. But this process became dizzying very quickly.
Is there an efficient way to do this?
A:
Have you tried the straightforward approach?
collectingAndThen(
groupingBy(
parentKeyMapper,
toImmutableListMultimap(childKeyMapper, valueMapper)
),
ImmutableMap::copyOf
);
Update: Above code works fine with JDK but Eclipse compiler is complaining about it. Here's a version that Eclipse will accept:
public static <T, P, C, V> Collector<T, ?, ImmutableMap<P, ImmutableMultimap<C, V>>> toPartitionedImmutableMultimap(
Function<? super T, ? extends P> parentKeyMapper,
Function<? super T, ? extends C> childKeyMapper,
Function<? super T, ? extends V> valueMapper) {
return Collectors.collectingAndThen(
Collectors.groupingBy(
parentKeyMapper,
SO29417692.<T,C,V>toImmutableListMultimap(childKeyMapper, valueMapper)
),
ImmutableMap::<P,ImmutableMultimap<C,V>>copyOf
);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Single trace partition function
I would be glad if someone can help me understand the argument in appendix B.1 and B.2 (page 76 to 80) of this paper.
The argument in B.1 supposedly helps understand how the authors in that paper got from equation 3.6 to 3.8 on page 18 of the same paper. These 3 equations form the crux of the calculation done in this paper and unfortunately I am unable to see this.
In the appendix B.2 they calculate certain rational functions which are completely mysterious to me. Like I can't understand what it means to say that $\frac{1}{1-x}$ is the partition function of the operator $\partial$. Similarly one can see such functions in the equations B.7, B.8 and B.10 of that paper.
Curiously these polynomials had also appeared on page 6 and 7 in this paper long before the above paper. I am completely unable to understand how the series of polynomials between equation 15 to 20 of this paper were gotten and what they mean.
I haven't seen any book ever discuss the methods being used here. I would be glad to hear of some pedagogic and expository references on the background of all this.
A:
Their convention for the partition function is explained in the second paragraph before the equation (B.7) of the paper by Shiraz et al. It is
$$z(x) = \sum_{operators} x^{\Delta_{operator}}$$
Note that this is just a different way of writing the usual $\mbox{Tr }\exp(-\beta H)$ if you identify $\exp(-\beta)\equiv x$ and $\Delta\equiv H$. Yes, the dimension is the same thing as the Hamiltonian (of the radial quantization) and it is often helpful to avoid exponentials and write powers of $x$ only, so therefore the exponential redefinition of $\beta$ vs $x$. The trace is the summation over the basis.
They're calculating the partition function of a whole theory, not the $\partial$ operator itself. So the partition function is the sum over operators, as described above. In this simple case, the operators are $\partial_i \partial_j \dots \phi$, i.e. arbitrary derivatives of $\phi$ by $d$ different partial derivative symbols.
The derivatives with respect to different directions commute with each other and are completely independent. So imagine $d=1$ for a while, only one direction. In that case, you have operators
$$\phi, \partial \phi, \partial^2 \phi, \dots$$
and their dimensions are
$$\Delta=0,1,2,\dots$$
plus the dimension of $\phi$ if it were nonzero. The partition sum is the sum of $x^\Delta$ over these operators which means
$$1+x+x^2+\dots = \frac{1}{1-x}.$$
The sum is obtained as geometric series. Note that the coefficients of the Taylor expansion are simply equal to one: there is no source where you could have gotten something else.
Now, the operators in the $d$-dimensional space may be obtained by acting with some derivatives in the 1st direction; some in 2nd, and so forth, on $\phi$. So the space of operators is a tensor product of spaces from each of the $d$ directions, and the partition sum is therefore the product of the partition sums from the individual directions, i.e. the $d$-th power of $1/(1-x)$.
There are other factors multiplying the total partition function but you haven't asked about it, and I can't explain every detail in a 50-page paper you haven't asked about. But yes, the other paper you mentioned almost certainly uses the same basic insight about the geometric series.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does miner voting work?
I always here people talk about miners being able to "vote" on certain things using the block chain. So here are my questions:
1) who gets to ask the questions?
2) what type of questions are being asked?
3) do they "vote" by selectively solving one block?
4) how is it even possible for even the biggest miners to selectively solve a block when the hash rate is so high?
5) does question #4 propose a vulnerability in the network?
Thanks. I never really understood this aspect of mining regarding big time mining farms
A:
I'll try to answer your questions specifically, but here's a good read on how Bitcoin votes on upgrades.
1) The questions are really all the same question: which BIPs do you support? These proposals make their way through the Bitcoin development community, and once implemented, can be voted on by miners. So basically, anyone can make a proposal.
2) See the answer to question 1
3) No
4) Since the answer to question 3 is "No", this question makes no sense.
5) See questions 3 and 4
EDIT: I changed the link explaining BIP voting to one with less bias and opinion, and is much more concise an explanation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Flask: receiving asynchronous POST requests?
On the python end, I'm envisioning an HTTP end point written in flask to accept data sent from the javascript (asynchronous POST request).
On receiving the POST request, it will write to an sqlite3 database.
The problem I have is that Flask is not asynchronous so how will it handle many POST requests being fired at it and not run into problems?
A:
One option is to use uWSGI in conjunction with the gevent loop in order to avoid blocking.
Check out the docs: http://uwsgi-docs.readthedocs.org/en/latest/Gevent.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding sql queries fired by ActiveRecord
I have two tables one trip and one txns having one to many relationship in oracle db.
When i fire the below query
Trip.where("upper(trips.domain) = 'FOOBAR.COM' and txns.user_id = 50001 and txns.txn_type = '1'").includes([:txns]).order('trips.created_at desc').limit(10).offset(0)
For this there were two queries in the sql log.
Trip Load (4920.4ms) SELECT * FROM (
SELECT raw_sql_.*, rownum raw_rnum_
FROM (SELECT DISTINCT "TM"."TRIPS".id, FIRST_VALUE(trips.created_at)
OVER (PARTITION BY "TM"."TRIPS".id ORDER BY trips.created_at desc) AS alias_0__ FROM "TM"."TRIPS" LEFT OUTER JOIN "TXNS" ON "TXNS"."TRIP_ID" = "TM"."TRIPS"."ID"
WHERE (upper(trips.domain) = 'FOOBAR.COM' and txns.txn_type = '1')
ORDER BY alias_0__ DESC) raw_sql_
)
WHERE raw_rnum_ between 1 and 10
SQL (186.2ms) SELECT "TM"."TRIPS"."ID" AS t0_r0, "TM"."TRIPS"."TRIP_REF" AS t0_r1, "TM"."TRIPS"."TRIP_NAME" AS t0_r2,
"TM"."TRIPS"."START_DATE_TIME" AS t0_r3, "TM"."TRIPS"."END_DATE_TIME" AS t0_r4, "TM"."TRIPS"."AMOUNT" AS t0_r5, "TM"."TRIPS"."CREATED_AT" AS t0_r6,
"TM"."TRIPS"."UPDATED_AT" AS t0_r7, "TM"."TRIPS"."USER_ID" AS t0_r8,
"TM"."TRIPS"."BOOKING_STATUS" AS t0_r9, "TM"."TRIPS"."TRAVELLERS" AS t0_r10,
"TM"."TRIPS"."USER_TRIP_NAME" AS t0_r11, "TM"."TRIPS"."CONTACT_DETAIL_ID" AS t0_r12,
"TM"."TRIPS"."AIR" AS t0_r13, "TM"."TRIPS"."HOTEL" AS t0_r14, "TM"."TRIPS"."DOMAIN" AS t0_r15, "TM"."TRIPS"."TRAIN" AS t0_r16, "TM"."TRIPS"."TAGS" AS t0_r17, "TM"."TRIPS"."CURRENCY" AS t0_r18, "TM"."TRIPS"."CUR_INR_VALUE" AS t0_r19,
"TM"."TRIPS"."COMPANY_ID" AS t0_r20, "TXNS"."ID" AS t1_r0, "TXNS"."TRIP_ID" AS t1_r1,
"TXNS"."USER_ID" AS t1_r2, "TXNS"."TXN_TYPE" AS t1_r3, "TXNS"."STATUS" AS t1_r4, "TXNS"."SOURCE_TYPE" AS t1_r5, "TXNS"."SOURCE_ID" AS t1_r6, "TXNS"."EXTERNAL_REFS" AS t1_r7, "TXNS"."CREATED_AT" AS t1_r8, "TXNS"."IP_NUMBER" AS t1_r9, "TXNS"."MISC" AS t1_r10 FROM "TM"."TRIPS" LEFT OUTER JOIN "TXNS" ON "TXNS"."TRIP_ID" = "TM"."TRIPS"."ID" WHERE "TM"."TRIPS"."ID" IN (11620660, 11620651, 11620649, 11620647, 11620646, 11620645, 11620644, 11620642, 11620641, 11620636) AND (upper(trips.domain) = 'FOOBAR.COM' and txns.txn_type = '1') ORDER BY trips.created_at desc
I want to know why does active record fire two queries
A:
The reason you've got two queries are that you're using a joins based include (because your where clauses references columns from the txns association) and because you've got a limit.
Because you're joining a has many rails can't just stick a limit 10 on your query - to take an extreme example if you had 1 trip with 10 associated txns then adding limit 10 to the query rails would normally run could return only that 1 trip (joined with each of the 10 matching txns) rather than 10 distinct trips
To get around this, rails first finds what the top 10 Trip rows matching your criteria are and then fires a second query to load those trip rows with the associations you want included.
| {
"pile_set_name": "StackExchange"
} |
Q:
why is this not working (js)
can someone tell why this does not work?
the code does print "generating fish" but than not printing enything...
function fish(x, y, degree, genes, Snumber) {
this.x = x;
this.y = y;
this.dgree = degree;
this.energy = 50;
this.genes = genes;
this.Snumber = Snumber;
}
fishs = new Array(10);
Snumber = 0;
document.writeln("generating fish");
for (i = 0; i < 10; i++) {
x = Math.round(Math.random * 600);
y = Math.round(Math.random * 600);
degree = Math.round(Math.random * 360);
genes + new Array(12);
for (j = 0; j < 12; j++) {
genes[j] = Math.random * 2 - 1;
}
fishs[i] = new fish(x, y, degree, genes, Snumber);
Snumber++;
document.writeln("genarating fish num" + i);
}
A:
You have couple of errors and warnings in your code:
1.) You don't user the var keyword, so you automatically put the variables on the global scope.
2.) You use a + operator instead of an = in the line:
genes + new Array(12);
3.) You use Math.random (wich returns the random function, not a random number) instead of the function in 3 places.
4.) You use document.write(ln), which is deprecated. Use console.log instead (which prints to the console, hit F12 to see it)
| {
"pile_set_name": "StackExchange"
} |
Q:
Fluid Flux field for multible key:value
I search a flux field for multible key:value entrys that are editable in the backend. For a single line I use a normal input field:
<flux:field.input name="Title" label="Title" />
But now I would like to be able to add dynamicly values like:
Email [email protected]
Phone ++12344556
OtherContat value
OtherKey otherValue
And then use this in a loop in fluid for the output.
What could I use for this?
A:
You can use the ViewHelpers flux:section and flux:object. It looks like this:
<flux:form.section name="contacts" label="Contacts">
<flux:form.object name="contact" label="Contact">
<flux:field.input name="email" label="Email"/>
<flux:field.input name="phone" label="Phone"/>
</flux:form.object>
</flux:form.section>
You can then render the data using something like this:
<ol>
<f:for each="{contacts}" as="contactlistelement">
<li>
Phone: {contactlistelement.contact.phone}<br />
Email: {contactlistelement.contact.email}
</li>
</f:for>
</ol>
There is a limit to this: Inside the flux:object, you cannot have a FAL field, like an image.
| {
"pile_set_name": "StackExchange"
} |
Q:
Downvoting repetitive questions by the same person
Suppose a person asks a question that is not valid, and repeats it many times with some changes. If I always downvote that question, is that serial downvoting or not? I think it should not be considered serial downvoting.
A:
If you deliver many downvotes to many different questions in a short time period, the serial downvoting detection algorithm is likely to fire and unwind them. If you think that someone is posting many duplicate copies of a question, vote to close as duplicate, or flag for a moderator, or both.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: Importing class from another file and implementing function
I'm trying to import a class from another file and then implement the member function in my main function. I'm really just trying to understand the syntax of Python, as I am still really new to the language. My program is simple, and isn't really meant to do much. I'm more or less just trying to get a grasp on how Python goes about this. My class file is called Parser.py and here's is the code:
class Parser:
def hasMoreCommands(self):
if not c:
return false
else:
return true
and my main function is in a file called jacklex.py The main function only opens an input file and copies the text to an output file. Here's the code:
import Parser
from Parser import *
f = open('/Python27/JackLex.txt' , 'r+')
fout = open('/Python27/output.txt' , 'w')
while Parser.hasMoreCommands:
c = f.read(1)
fout.write(c)
print "All Done"
f.close()
fout.close()
My issue is that my program runs, but it seems to be getting stuck in an infinite loop. There's never any text printed to the ouput file, and "All Done" is never printed in the Python Shell. Am I missing something essential that's causing my program not to work properly?
A:
Parser.hasMoreCommands refers to the (unbound) method, not the output. It'll always evaluate to True.
You need to create an instance of your parser and then call the method:
parser = Parser()
while parser.hasMoreCommands():
...
| {
"pile_set_name": "StackExchange"
} |
Q:
Firebase Cloud Functions: Get user property values
I am trying to store some data from the 'app_remove' event in the database.
It works for the standard information like appInfo.appInstanceId.
But how do I get the userProperty values, since they are objects?
exports.appremoved = functions.analytics.event('app_remove').onLog(event => {
console.log(event.data);
console.log(event.data.user.Selected_Games);
const user = event.data.user;
if (user != null) {
if(user.userId != null){
admin.database().ref('/user_events/'+user.appInfo.appInstanceId + "/" + "deviceId").set(user.userId);
}
admin.database().ref('/user_events/'+user.appInfo.appInstanceId + "/" + "app_remove").set(event.data.logTime);
admin.database().ref('/user_events/'+user.appInfo.appInstanceId + "/" + "app_install").set(user.firstOpenTime);
}
});
This is the result of the console.log of event.data
AnalyticsEvent {
params: { firebase_conversion: 1, firebase_event_origin: 'auto' },
name: 'app_remove',
reportingDate: '20170719',
logTime: '2017-07-19T10:57:12.920Z',
user:
UserDimensions {
deviceInfo:
{ deviceCategory: 'mobile',
deviceModel: 'WAS-LX1A',
deviceTimeZoneOffsetSeconds: 7200,
platformVersion: '7.0',
userDefaultLanguage: 'it-it' },
geoInfo:
{ city: 'Milan',
continent: '039',
country: 'Italy',
region: 'Lombardy' },
appInfo:
{ appId: 'com.example.example',
appInstanceId: '000000',
appPlatform: 'ANDROID',
appStore: 'com.android.vending',
appVersion: '1.12' },
firstOpenTime: '2017-07-17T12:37:01.320Z',
userProperties:
{ Active_Notification: [Object],
Referrer: [Object],
Selected_Games: [Object],
Selected_Sources: [Object],
Selected_Topics: [Object],
first_open_time: [Object],
user_id: [Object] },
bundleInfo: ExportBundleInfo { bundleSequenceId: 10, serverTimestampOffset: 693 } } }
A:
I found the solution.
I did a console.log of that object (event.data.user.Selected_Games)
UserPropertyValue { value: '4', setTime: '2017-06-27T01:22:25.375Z' }
So to get the value
event.data.user.userProperties.Selected_Games.value
| {
"pile_set_name": "StackExchange"
} |
Q:
Tabulator PUT via Ajax to Django REST Endpoint - Reduces Table to Last Edited Record
I am using Tabulator with Django to edit a model. After any change to a cell, I use setData to make an Ajax call to a REST endpoint created using Django REST Framework. The database updates ok. The problem is that the response from the server contains only the single record that was updated, and this is making the Tabulator data reduce to only that record.
My question is, how can I get Tabulator to disregard the response, or otherwise have the data be left alone following the edit?
I am pretty new at this stuff (both Django and especially JavaScript) so apologies if I've missed something basic.
My tabulator code is below.
The function getCookie is to generate a CSRF_TOKEN as per the instructions in the Django documentation here. This is then included in the header as 'X-CSRFTOKEN': CSRF_TOKEN.
The variable ajaxConfigPut is used to set the method to PUT and to include the CSRF_TOKEN as noted above. This is then used in the table.setData call later on (table.setData(updateurl, updateData, ajaxConfigPut);).
The function ajaxResponse at the end just checks if the response is an array or not (because Tabulator expects an array which is fine for GET, but the PUT response was only a single {} object. So this function forces the PUT response into an array consisting of one object [{}].
<div id="example-table"></div>
<script type="text/javascript">
// get CSRF token
// https://docs.djangoproject.com/en/dev/ref/csrf/#acquiring-the-token-if-csrf-use-sessions-and-csrf-cookie-httponly-are-false
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var CSRF_TOKEN = getCookie('csrftoken');
// set variable to customise ajaxConfig for use in the setData call
var ajaxConfigPut = {
method:"PUT", //set request type to Position
headers: {
// "Content-type": 'application/json; charset=utf-8', //set specific content type
'X-CSRFTOKEN': CSRF_TOKEN,
},
};
//create Tabulator on DOM element with id "example-table"
var table = new Tabulator("#example-table", {
ajaxURL:"{% url 'cust_listapi' %}", // reverse pick up the url since in a django template (?)
height:205, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
layout:"fitColumns", //fit columns to width of table (optional)
columns:[ //Define Table Columns
{title:"Name", field:"name", width:150, editor:true},
{title:"Age", field:"age", hozAlign:"center",editor:true},
{title:"Age_Bar", field:"age", hozAlign:"left", formatter:"progress"},
{title:"Customer Status", field:"is_customer", hozAlign:"left"},
// {title:"Favourite Color", field:"col"},
// {title:"Date Of Birth", field:"dob", sorter:"date", hozAlign:"center"},
],
// see http://tabulator.info/docs/4.6/components#component-cell
cellEdited:function(cell){ //trigger an alert message when the row is clicked
console.log("Cell edited in row " + cell.getData().id
+ " and column " + cell.getField()
+ " from " + cell.getOldValue() + " to "
+ cell.getValue()
+ ". The row pk=" + cell.getData().id
);
console.log(cell.getData());
var updateurl = "{% url 'cust_listapi' %}" + cell.getData().id + "/"
console.log('URL is: ' + updateurl)
// Create variable from full row data but drop the id;
console.log('About to create updateData')
var updateData = {};
updateData[cell.getField()] = cell.getValue();
console.log(updateData);
console.log('About to setData');
table.setData(updateurl, updateData, ajaxConfigPut);
console.log('Finished setData');
//cell.restoreOldValue();
},
ajaxResponse:function(url, params, response){
console.log('Beginning ajaxResponse')
console.log('The type is:', typeof(response));
console.log(Array.isArray(response))
console.log(response)
result = response;
if(Array.isArray(response) === false){
result = [response];
};
return result;
}
});
</script>
Here's a screenshot of the table before editing:
Table Before Editing
And here's a screenshot after editing the top row (changing 'Mabel' to 'Jemima'):
Screenshot after editing
And here's the console log:
Console Log
I tried amending the response from the endpoint so that all records from the database are returned, but the problem with that is it doesn't include the edit, so the Tabulator table data is overwritten. Here's the code I used in the Django views.py. Maybe there's a way to return the data that has been changed?
views.py
from rest_framework import generics, mixins
from apps.app_mymodel.models import Customer
from .serializers import CustomerSerializer
class CustomerListAPIView(generics.ListAPIView):
serializer_class = CustomerSerializer
queryset = Customer.objects.all()
class CustomerUpdateAPIView(generics.GenericAPIView,
mixins.ListModelMixin,
mixins.UpdateModelMixin):
serializer_class = CustomerSerializer
queryset = Customer.objects.all()
# Override the put function here to return all records
def put(self, request, *args, **kwargs):
# return self.update(request, *args, **kwargs)
return self.list(request, *args, **kwargs)
Here's the serializer:
serializers.py
from rest_framework import serializers
from apps.app_mymodel.models import Customer
class CustomerSerializer(serializers.ModelSerializer):
class Meta:
model = Customer
fields = '__all__'
Can someone please point me in the right direction?
A:
None of the Mixins used by your CustomerUpdateAPIView have a method called put. I don't think that function is called. Instead, you can try to override the update method of your viewset. It could look like this:
def update(self, request, *args, **kwargs):
obj = super().update(request, *args, **kwargs) # performs the update operation
return self.list(request, *args, **kwargs)
You can check out this URL to understand the classes you are using: http://www.cdrf.co/
There you will see all the methods of the classes you are using to better understand the flow of your request.
| {
"pile_set_name": "StackExchange"
} |
Q:
Use sed to find and replace a number following by its successor in bash
I have a string that contains multiple occurrences of number ranges, which are separated by a comma, e.g.,
2-12,59-89,90-102,103-492,593-3990,3991-4930
Now I would like to remove all directly neighbouring ranges and remove them from the string, i.e., remove anything that is of the form -(x),(x+1), to get something like this:
2-12,59-492,593-4930
Can anyone think of a method to accomplish this? I can honestly not post anything that I have tried, because all my tries were highly unsuccessful. To me it seems like it is not possible to actually find anything of the form -(x),(x+1) using sed, since that would require doing operations or comparisons of a found number by another number that has to be part of the command that is currently searching for numbers.
If everybody agrees that sed is NOT the correct tool for doing this, I will do it another way, but I am still interested if it's possible.
A:
with awk
awk -F, -v RS="-" -v ORS="-" '$2!=$1+1' file
with appropriate separator setting, print the record when second field is not +1.
RS is the record separator and ORS is the outpout record separator.
test:
> awk -F, -v RS="-" -v ORS="-"
'$2!=$1+1' <<< "2-12,59-89,90-102,103-492,593-3990,3991-4930"
2-12,59-492,593-4930
| {
"pile_set_name": "StackExchange"
} |
Q:
Gravitational field of thin 2D ring - numerical simulation
I'm aware of Newton's Shell Theorem, which states that inside of a thin ring of uniform density, the gravitational force exerted on a point mass should be zero.
I wrote a quick field simulation to demonstrate this, but am getting a force inside the ring. The potential (-GM/r) is zero, but the force on a test mass (-GM/r^2) is non-zero.
I'll post the relevant segments of my code below and a few screenshots. Any ideas what's going on?
Each point in the field accumulates the felt gravitational force from all masses comprising the ring (which is a large set of very closely spaced point masses):
void accumulateForce(Mass m){
//Vector from test point towards individual ring mass
double dx = m.x-x;
double dy = m.y-y;
double lenSqd = dx*dx + dy*dy;
double len = Math.sqrt(lenSqd);
//Normalized direction of gravitational force
double nx = dx/len;
double ny = dy/len;
//These variables accumulate the force from all ring masses
fxAccum += nx*bigG*m.m/lenSqd;
fyAccum += ny*bigG*m.m/lenSqd;
}
After this function has been executed for each point mass in the ring, the felt force at that location in the gravitational field is visualized.
Here's what the above code looks like:
When I change the last 2 lines of code to:
fxAccum += nx*bigG*m.m/len;
fyAccum += ny*bigG*m.m/len;
The result is zero potential inside the ring, as expected:
Am I misinterpreting something here? A test mass inside of the ring will be pulled towards the edge. I thought Newton's shell method described zero gravitational force inside of the ring.
A:
Newton's shell theorem relies on Gauss's law, which in $d$ spatial dimensions implies a $r^{1-d}$ force law. Since $d=2$, the force should fall off as $1/r$.
This explains why OP's first plot (with an $1/r^2$ code) fails to produce a vanishing interior force, while OP's second plot (with an $1/r$ code) produces a vanishing interior force.
(Btw, the second plot should not be interpreted as potential energy. For starters, recall that potential energy is a scalar, not a vector.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Geomesa bounding box query Accuracy
Geomesa is a spatial temporal database, more details are available here:
http://www.geomesa.org/
I am trying the example tutorial, by setting up Hbase database with it. I am running the Hbase QuickStart tutorial http://www.geomesa.org/documentation/tutorials/geomesa-quickstart-hbase.html
The tutorial runs fine, below are some of the problems which I notice in the bounding box query.
Say the bounding box query is like (30,60) to (31,61). Which means I want to do spatial query between latitute 30 to 31 and longitude 60 to 61. The results which I get from geomesa include the some of the points whose locations are like:
(29.5,61.5)
(29.6,61.3) and so-on.
Clearly, these points are not within the bounding box. I want to ask, is there some way to solve this problem. Below are some of my questions to the Geomesa team:
1. What is the bounding box query accuracy by default ?
2. Is there any way to specify somewhere the accuracy of boundung box query, so that it leave the points which are outside of bounding box.
I tried searching through the documentation, and settings but couldn't find anything working for me yet.
A:
I've seen this with Accumulo backed GeoMesa. There is a geotools Hint on the query or datastore called looseBoundingBox.
It is by design turning your query bounding box into an approximate and always larger bounding box, based on the space filling curve used. The looseBoundingBox set to true says it is fine to use these approximate results. For false, it evaluates each returned result according to the Filter, thus trimming those extra results.
Depending on use case looseBoundingBox may be fine, like for making a map, extra features will be clipped out anyway.
So to answer number 2, try adding looseBoundingBox hint to your query with false. See the GeoTools query docs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding nearest number between two lists
I have a list of dataframes (df1) and another list of dataframes (df2) which hold values required to find the 'nearest value' in the first list.
df1<-list(d1=data.frame(y=1:10), d2=data.frame(y=3:20))
df2<-list(d3=data.frame(y=2),d4=data.frame(y=4))
Say I have this function:
df1[[1]]$y[which(abs(df1[[1]]$y-df2[[1]])== min(abs(df1[[1]]$y-df2[[1]])))]
This function works perfectly in finding the closest value of df2 value 1 in df1. What I can't achieve is getting to work with lapply as in something like:
lapply(df1, function(x){
f<-x$y[which(abs(x$y-df2) == min(abs(x$y - df2)))]
})
I would like to return a dataframe with all f values which show the nearest number for each item in df1.
Thanks,
M
A:
I assume you're trying to compare the first data.frames in df1 and df2 to each other, and the second data.frames in df1 and df2 to each other. It would also be useful to use the which.min function (check out help(which.min)).
edit
In response to your comment, you could use mapply instead:
> mapply(function(x,z) x$y[which.min(abs(x$y - z$y))], df1, df2)
d1 d2
2 4
| {
"pile_set_name": "StackExchange"
} |
Q:
How does the iPhone know it's not using an Apple cable?
Sometimes when I plug a cable in to charge, the iPhone says it may not work with this device. How does it know it's not an Apple cable?
A:
Apple has a program called MFi and detects if the cable has a certified chip inside. The chip just says that it's been officially 'Made For iOS.'
| {
"pile_set_name": "StackExchange"
} |
Q:
An explicit construction of reals added after some forcing notions
Consider the forcing notion(s) introduced by Friedman (or Mitchell or Neeman) for adding a club subset of $\omega_2$ by finite conditions. In the generic extension CH fails, but I can't see the reals added by the forcing. Would you please give an explicit construction of $\aleph_2$-many reals in the generic extension by these forcings. Can we determine if the added reals are Cohen, Random, or ....
Remark. The question applies to many similar forcing constructions, in particular to the forcings introduced in Neeman's paper.
References.
1) Friedman, Forcing with finite conditions. Set theory, 285–295, Trends Math., Birkhäuser, Basel, 2006.
2) Mitchell, Adding closed unbounded subsets of $\omega_2$ with finite forcing. Notre Dame J. Formal Logic 46 (2005), no. 3, 357–371.
3) Neeman, Forcing with sequences of models of two types.
A:
Each of the posets you mention adds $\omega_2$ many Cohen reals. Let $G$ be generic for any of the 3 posets you mentioned. The point is that any collection of $\omega_1$-many reals in $V[G]$ can be captured by an intermediate extension of the form $V[G \cap M]$ where $M$ is a sufficiently elementary substructure of $V$ containing $\omega_1$ as a subset and $G$ contains a strong master condition (in the sense of Mitchell) for the model $M$. Then one can show that the quotient forcing $\mathbb{P}/(G \cap M)$ is strongly proper with respect to all countable models of the form $N[G \cap M]$, where $N$ is a countable model from $V$. This is a general phenomenon, but in the case of these forcings it can be shown rather directly; Neeman's preprint gives the details. The fact that the quotient is strongly proper with respect to stationarily many countable models abstractly implies that the quotient adds lots of Cohen reals; Mitchell discusses this in his paper "On the Hamkins Approximation Property".
| {
"pile_set_name": "StackExchange"
} |
Q:
( New formulation) Are parts of speech syntactic categories? ( A question on generative grammer)
I only have a rudimentary ( or even less than rudimentary) knowledge of generative grammar.
But what strikes me is that the sentence formation rules are coinded using parts of speech. For example ( the most basic one ) :
Sentence --> Noun Phrase + verb Phrase
What is the motivation for this?
Is there behind this a hypothesis as to cognitive processes involved in speaking. I mean is there a hypothesis such as " subject, object, complement are artificial categories invented by linguists; the real syntactic categories mentally present in the mind of every speaker, the real natural syntactic categories are parts of speech: noun phrase, verb, adverb, preposition, etc. "
Does generative grammar reject traditional syntactic categories such as subject, object, circumstantial complement, agent complement, etc. ?
Why does generative grammar use parts of speech to formulate syntactic formation rules?
PS : I am french, maybe the labels I use are not traditional in english grammar.
A:
To my understanding, it's the other way around.
According to generativists, syntactic categories are a fundamental part of the mental grammar of a language. When you learn a new lemma, like "purple", you also have to learn how it acts syntactically: in this case, it basically combines with an NP to make a new NP. (In practice it's a bit more complicated, but that's not important here.)
Ancient grammarians noticed that a lot of words tended to pattern in the same way, and gave these patterns arbitrary names. The terms "noun" and "verb", for instance, come from the Latin words for "name" and "word" (and are cognate with those two English words, actually).
But parts of speech describe syntactic categories, not the other way around. In many languages (Japanese, Swahili, Lingála, etc) there are two or more syntactic categories that English-speakers would group together as "adjectives". In other languages "adjectives" don't have a syntactic category at all, they're the same as stative verbs. So in these instances, the word "adjective" isn't useful, and we make up new terms and symbols instead.
TL;DR: The symbols like "NP" and "VP" are arbitrary and made up by syntacticians, representing mental structures we can't observe directly. In the distant past, ancient grammarians made up words to describe these same mental structures, so it's traditional for modern syntacticians to use these same words. But the names are less important than the structures they describe: you could replace "NP" with "Ξ" and "VP" with "Ш" and the model would still work just fine.
A:
Generative grammar emerged most directly from formalism (and see formalism in mathematics). I'm not saying that Noam Chomsky is a formalist, but in his early work from the 50s, it is clear that in establishing the Chomsky hierarchy, he uses formal methods. In a formal system, what identifies a system and its parts is its form alone. That's what makes it a formal system.
You may wish. for your own purposes, to supply histories and interpretations for the terms of the system. You're free to do that, but the system itself doesn't depend on any such specific
interpretation, and the various users of the system need not agree about the interpretations of the symbols used in the system. Typically, actually, they don't agree. This can give formal systems great generality, because the parts are not tethered to specific interpretations.
The example rules given in the question resemble the productions (rules) of type-2 grammars in the Chomsky hierarchy, so let's assume that is what they are. I'll use CFG, standing for Context Free Grammar, as a synonym of type-2 grammar. You want to know about the history and interpretation of the non-terminal symbols that are typical in applications of CFG to the description of natural language and other similar systems (like computer language).
That's a natural question, but it really isn't possible to answer it, because those who have used CFG have had various ideas in mind when they used the symbols, and sometimes, presumably, haven't had anything in mind at all. Perhaps the symbols are derived from traditional antecedents, or perhaps they are not. In one offshoot of CFG, Generalized Phrase Structure Grammar, the symbols are interpreted in accordance with their names, which are finite sets of features and attributes of various sorts.
| {
"pile_set_name": "StackExchange"
} |
Q:
Elasticsearch multiple search terms
I've set an elastic index. I have 100,000 documents all with the following fields
{
"Make": "NISSAN",
"Model": "FUGA",
"Body Type": "SEDAN",
"Year of Manufacture": 2012,
"Country": "JAPAN",
"Fuel Type": "PETROL"
}
I need to create a search based on four possible terms
Make
Model
Year of Manufacture
Fuel Type
Below are four possible combinations for a search query
2012 nissan fuga petrol
nissan fuga 2012 petrol
petrol 2012 nissan fuga
nissan fuga petrol 2012
Assuming we have correct spelling on the search query, below is how i tried searching based on the search query
curl -X GET "localhost:9200/vehicles/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"simple_query_string" : {
"query": "2012 NISSAN FUGA PETROL",
"fields": ["Make","Model","Year of Manufacture","Fuel Type"]
}
}
}
Out of surprise, the search returns an error below
{
"error": {
"root_cause": [
{
"type": "query_shard_exception",
"reason": "failed to create query: {\n \"simple_query_string\" : {\n \"query\" : \"2012 NISSAN FUGA PETROL\",\n \"fields\" : [\n \"Model^1.0\",\n \"Make^1.0\",\n \"Year of Manufacture^1.0\",\n \"Fuel Type^1.0\"\n ],\n \"flags\" : -1,\n \"default_operator\" : \"or\",\n \"analyze_wildcard\" : false,\n \"auto_generate_synonyms_phrase_query\" : true,\n \"fuzzy_prefix_length\" : 0,\n \"fuzzy_max_expansions\" : 50,\n \"fuzzy_transpositions\" : true,\n \"boost\" : 1.0\n }\n}",
"index_uuid": "3vd2zOgHRIq3BUAJ_EATVQ",
"index": "vehicles"
}
],
"type": "search_phase_execution_exception",
"reason": "all shards failed",
"phase": "query",
"grouped": true,
"failed_shards": [
{
"shard": 0,
"index": "vehicles",
"node": "Xl_WpfXyTcuAi2uadgB4oA",
"reason": {
"type": "query_shard_exception",
"reason": "failed to create query: {\n \"simple_query_string\" : {\n \"query\" : \"2012 NISSAN FUGA PETROL\",\n \"fields\" : [\n \"Model^1.0\",\n \"Make^1.0\",\n \"Year of Manufacture^1.0\",\n \"Fuel Type^1.0\"\n ],\n \"flags\" : -1,\n \"default_operator\" : \"or\",\n \"analyze_wildcard\" : false,\n \"auto_generate_synonyms_phrase_query\" : true,\n \"fuzzy_prefix_length\" : 0,\n \"fuzzy_max_expansions\" : 50,\n \"fuzzy_transpositions\" : true,\n \"boost\" : 1.0\n }\n}",
"index_uuid": "3vd2zOgHRIq3BUAJ_EATVQ",
"index": "vehicles",
"caused_by": {
"type": "number_format_exception",
"reason": "For input string: \"NISSAN\""
}
}
}
]
},
"status": 400
}
Below is more information on my version of elastic
{
"name": "salim-HP-EliteBook-840-G5",
"cluster_name": "elasticsearch",
"cluster_uuid": "mSWKP4G1TSSq9rI3Hc0f6w",
"version": {
"number": "7.5.1",
"build_flavor": "default",
"build_type": "tar",
"build_hash": "3ae9ac9a93c95bd0cdc054951cf95d88e1e18d96",
"build_date": "2019-12-16T22:57:37.835892Z",
"build_snapshot": false,
"lucene_version": "8.3.0",
"minimum_wire_compatibility_version": "6.8.0",
"minimum_index_compatibility_version": "6.0.0-beta1"
},
"tagline": "You Know, for Search"
}
Below is the index mapping for the vehicles index
{
"vehicles": {
"mappings": {
"_meta": {
"created_by": "ml-file-data-visualizer"
},
"properties": {
"Body Type": {
"type": "keyword"
},
"Country": {
"type": "keyword"
},
"Fuel Type": {
"type": "keyword"
},
"Make": {
"type": "keyword"
},
"Model": {
"type": "text"
},
"Year of Manufacture": {
"type": "long"
}
}
}
}
}
How can i make a successful search based on my search criteria ?
A:
UPDATE
cross_fields with synonym token filter.
A working example:
Mappings (Updated)
PUT my_index
{
"mappings": {
"properties": {
"Make": {
"type": "text"
},
"Model": {
"type": "text"
},
"Body Type": {
"type": "text"
},
"Year of Manufacture": {
"type": "text",
"fields": {
"long": {
"type": "long"
}
}
},
"Country": {
"type": "text"
},
"Fuel Type": {
"type": "text"
}
}
},
"settings": {
"index": {
"analysis": {
"filter": {
"my_syn_filt": {
"type": "synonym",
"synonyms": [
"nisson,nissen => nissan",
"foga => fuga"
]
}
},
"analyzer": {
"my_synonyms": {
"filter": [
"lowercase",
"my_syn_filt"
],
"tokenizer": "standard"
}
}
}
}
}
}
Index few documents
PUT my_index/_doc/1
{
"Make": "NISSAN",
"Model": "FUGA",
"Body Type": "SEDAN",
"Year of Manufacture": 2012,
"Country": "JAPAN",
"Fuel Type": "PETROL"
}
PUT my_index/_doc/2
{
"Make": "NISSAN",
"Model": "FUGA",
"Body Type": "SEDAN",
"Year of Manufacture": 2013,
"Country": "JAPAN",
"Fuel Type": "PETROL"
}
PUT my_index/_doc/3
{
"Make": "FIAT",
"Model": "FUGA",
"Body Type": "SEDAN",
"Year of Manufacture": 2014,
"Country": "JAPAN",
"Fuel Type": "PETROL"
}
Search Query (Updated)
GET my_index/_search
{
"query": {
"multi_match": {
"query": "NISSON FOGA 2012 PETROL", ---> nisson and foga
"fields": ["Make","Model","Year of Manufacture","Fuel Type"],
"type": "cross_fields",
"operator": "and",
"analyzer": "my_synonyms"
}
}
}
Results
"hits" : [
{
"_index" : "my_index",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.2605431,
"_source" : {
"Make" : "NISSAN",
"Model" : "FUGA",
"Body Type" : "SEDAN",
"Year of Manufacture" : 2012,
"Country" : "JAPAN",
"Fuel Type" : "PETROL"
}
}
]
Hope this helps
| {
"pile_set_name": "StackExchange"
} |
Q:
multiple internet connection at office
We have been using two separate Internet connections in our office. People will share internet connection by setting their gateways to either of these. Gateway is one of our local server through which internet is shared. So, we are using two local servers for two connections. Now problem is, if any connection is down, people have to manually change their gateways to the working connection.
How we can have multiple internet connection at office without people having to manually change their gateway settings? One of our server is windows XP and another is red hat.
Thanks in advance
EDIT
One requirement is that we need to have a server accessible via static ip
A:
Use a router that connects to both ISPs and can handle the fail-over between ISPs when one goes down.
A:
Use a dual-WAN router. On the low-end, the TP-LINK TL-R470T+ is around $60. On the higher end, consider the Cisco RV042.
Update: Some of the other answers suggest using a PC as a router. This is a more powerful and flexible solution. But it requires a lot more knowledge and effort on your part. If you don't have anyone available who is familiar with IP routing and NAT, it might not be the best idea. (I don't know of any easy-to-use, plug and play, PC solution.)
A:
As Shane Madden advised, you need a router that can handle multiple Internet connections and failover (and usually load-balance) between the two connections.
One such firewall/router is pfSense. It's based on BSD's pf, is open source, and is highly stable (I have dozens in production, including load balancing/failover for several).
You only need a modestly-powered workstation (an old Pentium 4 with 512 to 1GB of RAM will be plenty) and three NICs (I'd avoid older Realteks and stick with Intel).
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does GMail login go through youtube.com?
For a while I've noticed that Google logins (or, at least, GMail logins) always redirect through to "youtube.com" Is Google handling all logins from youtube.com? If so, why?
(wasn't sure if I should post this on webapps or superuser, so feel free to move this or tell me to move this to the appropriate site if necessary)
A:
When you log into a Google site like GMail, Google also logs you into all your various accounts Google accounts - such as YouTube. In order to be logged into a site, Google sets a cookie in your browser.
This is fine for most of their properties which are on the *.google.com domain (mail.google.com, docs.google.com, etc). However a website can only set and read a cookie for it's own domain - google.com can't set a cookie for youtube.com. To get around this, as part of the login process Google will redirect you through accounts.youtube.com to log you into YouTube - and typically your country specific domain if you are outside the US (e.g. I get logged into google.com.au as well).
The full login process is described in this SO answer, it dates from 2009 but most of it should still hold true.
| {
"pile_set_name": "StackExchange"
} |
Q:
RSA Algorithm For Numbers and Char values
I'm not a programming expert. I'm new to cryptography and I had gone through the security algorithm RSA. I wrote the code like this:
#include<math.h>
#include<iostream>
#include<cmath>
#include<Windows.h>
using namespace std;
class rsacrypto
{
long publickey;
long privatekey;
long modl; //Modulus
public :
rsacrypto(); //To be used to just generate private and public keys.
rsacrypto(long &,long &,long &);//To be used just to generate private and public keys.
rsacrypto(long key,long modulus) // Should be used when a data is to be encrypted or decrypted using a key.
{
publickey = privatekey = key;
modl = modulus;
}
long ret_publickey()
{
return publickey;
}
long ret_privatekey()
{
return privatekey;
}
long ret_modulus()
{
return modl;
}
void encrypt(char *);
void decrypt(char *);
int genrndprimes(int, int);
int genrndnum(int, int);
int totient(int);
int gcd (int, int);
int mulinv(int, int);
boolean isPrime(long);
};
rsacrypto::rsacrypto()
{
long p1,p2; //Prime numbers
long n = 0; //Modulus
long phi =0; //Totient value.
long e = 0; //Public key exponent.
long d = 0; //Private key exponent.
p1 = genrndprimes(1,10);
Sleep(1000);
p2 = genrndprimes(1,10);
n = p1*p2;
phi = (p1-1)*(p2-1);
e = genrndnum(2,(phi-1));
while(gcd(e,phi)!=1)
{
e = genrndnum(2,(phi-1));
}
d = mulinv(e, phi);
cout<<"Public Key=("<<e<<","<<n<<")"<<"\n";
cout<<"Private Key=("<<d<<","<<n<<")"<<"\n";
privatekey = e;
publickey = d;
modl = n;
int m=11;
int en=0, decr=0;
//Encryption
en=(long)pow((double)m,d)%n;
cout<<en<<"\n";
//Decryption
decr=(long)pow((double)en,e)%n;
cout<<decr;
}
/*
void rsacrypto::encrypt(char *dat)
{
long siz = strlen(dat);
for(long i=0;i<siz;i++)
{
dat[i]=(long)pow((double)dat[i],publickey)%modl;
cout<<i<<"="<<dat[i]<<"\n";
}
}
void rsacrypto::decrypt(char *datn)
{
long sizz = strlen(datn);
for(long i=0;i<sizz;i++)
{
datn[i]=(long)pow((double)datn[i],privatekey)%modl;
}
cout<<datn;
}*/
int rsacrypto::mulinv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int rsacrypto::genrndprimes(int a, int b){
long pivot;
do{
pivot= rand() % b + a;
if (isPrime(pivot))
return pivot;
} while (1==1);
}
boolean rsacrypto::isPrime(long pivot) {
if(pivot <= 1)
return false;
int root = sqrt((double)pivot);
//start at 2 because all numbers are divisible by 1
for(int x = 2; x <= root; x++) //You only need to check up to and including the root
{
if(pivot % x == 0)
return false;
}
return true;
}
int rsacrypto::genrndnum(int a, int b){
long pivot;
pivot= rand() % b + a;
return pivot;
}
int rsacrypto::gcd ( int a, int b )
{
int c;
while ( a != 0 ) {
c = a; a = b%a; b = c;
}
return b;
}
void main()
{
rsacrypto m;
system("pause");
}
But I would like to make this code work for hexa decimal values. I don't know how to do that. I'm not a programming expert. Any help would be sinscierly appreciated. Thankyou.
A:
I guess your problem is to transfer the double values (hex decimal values) into char values first. Then you can use the existing code to encrypt/decrypt the char values.
There are two ways to convert the double values into char values:
Convert each double into two char's as its printable/readable form, e.g., 123.455 -> "123.456";
I refer some code from this discussion:
#include <sstream>
stringstream ss;
ss << myDouble;
const char* str = ss.str().c_str();
ss >> myOtherDouble;
Convert each double into two char's as its byte form;
Please see this discussion:
Use a union:
union {
double d[2];
char b[sizeof(double) * 2];
};
Or reinterpret_cast:
char* b = reinterpret_cast<double*>(d);
Now, after converting your double values into char values, we can directly utilize the existing code to encrypt our data.
| {
"pile_set_name": "StackExchange"
} |
Q:
Access camera from a browser
Is it possible to access the camera (built-in on Apples) from a browser?
Optimal solution would be client-side javascript. Looking to avoid using Java or Flash.
A:
The HTML5 spec does allow accessing the webcamera, but last I checked, it is far from finalized, and has very, very little browser support.
This is a link to get you started:
http://www.html5rocks.com/en/tutorials/getusermedia/intro/
You'll probably have to use flash if you want it to work cross-browser.
W3 draft
A:
As of 2017, WebKit announces support for WebRTC on Safari
Now you can access them with video and standard javascript WebRTC
E.g.
var video = document.createElement('video');
video.setAttribute('playsinline', '');
video.setAttribute('autoplay', '');
video.setAttribute('muted', '');
video.style.width = '200px';
video.style.height = '200px';
/* Setting up the constraint */
var facingMode = "user"; // Can be 'user' or 'environment' to access back or front camera (NEAT!)
var constraints = {
audio: false,
video: {
facingMode: facingMode
}
};
/* Stream it to video element */
navigator.mediaDevices.getUserMedia(constraints).then(function success(stream) {
video.srcObject = stream;
});
Have a play with it.
A:
There is a really cool solution from Danny Markov for that. It uses navigator.getUserMedia method and should work in modern browsers. I have tested it successfully with Firefox and Chrome. IE didn't work:
Here is a demo:
https://tutorialzine.github.io/pwa-photobooth/
Link to Danny Markovs description page:
http://tutorialzine.com/2016/09/everything-you-should-know-about-progressive-web-apps/
Link to GitHub:
https://github.com/tutorialzine/pwa-photobooth/
| {
"pile_set_name": "StackExchange"
} |
Q:
Place to get software for embedded components?
I'm wondering if anyone knows of a place on the web that I can purchase or download software modules, written in C or C++, for the interaction between microprocessors and other components, like DACs, ADCs, or UARTs. Sort of like a git-hub for embedded C software. Does this place exist?
A:
You're possibly looking for something called a 'board support package' or BSP. For a given operating system it will have a collection of drivers / libraries to help you communicate with the hardware component.
Saying that, some standard hardware interfaces for e.g. 16550 Uart might have drivers that come with the OS.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cordova Custom Android Layout Plugin
I am developing an android cordova custom layout plugin. When user click on a button, application will call the android plugin and display custom layout. User can move the object in the custom layout of android cordova plugin. However, I have problem with my plugin when I call my xml file in my java code. The following is my code.
src/android/CustomLayout.java
public class CustomLayout extends CordovaPlugin {
private static final String LOG_TAG = "CustomNotification";
public CallbackContext callbackContext;
Context context;
Resources resources;
String packageName;
public CustomLayout(){
}
@Override
public boolean execute(String action, String rawArgs, CallbackContext callbackContext) throws JSONException {
this.callbackContext = callbackContext;
context = cordova.getActivity().getApplicationContext();
resources = context.getResources();
packageName = context.getPackageName();
if (action.equals("layout")) {
customLayout();
return true;
}
return false;
}
private void customLayout() {
Log.e(TAG, "show");
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
cordova.getActivity().setContentView(resources.getIdentifier("custom_layout", "layout", packageName));
ImageView motion = (ImageView) cordova.getActivity().findViewById(resources.getIdentifier("tvDragMe","id",packageName));
motion.setOnTouchListener(new MyTouchListener());
}
});
}
}
class MyTouchListener implements View.OnTouchListener {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, shadowBuilder, view, 0);
view.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
}
www/customlayout.js
var exec = require('cordova/exec');
var platform = require('cordova/platform');
module.exports = {
alert: function(completeCallback) {
exec(completeCallback, null, "CustomLayout", "layout", []);
}
};
res/layout/custom_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<ImageView
android:id="@+id/tvDragMe"
android:src="@drawable/smiles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_light"
android:padding="10dp"
android:textColor="#ffffff"
android:layout_marginTop="35dp"
android:text="Drag Me" />
</RelativeLayout>
XML file
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
id="cordova-plugin-custom_layout" version="1.0.0">
<name>Custom Layout</name>
<description>Cordova Custom Layout Plugin</description>
<keywords>cordova,layout</keywords>
<js-module src="www/customlayout.js" name="customlayout">
<merges target="customlayout" />
</js-module>
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="CustomLayout">
<param name="android-package" value="org.apache.cordova.dialogs.CustomLayout"/>
</feature>
</config-file>
<source-file src="res/layout/custom_layout.xml" target-dir="res/layout/custom_layout.xml" />
</platform>
</plugin>
A:
The following is the source code my question because I don't set view and setViewByID in my Java file. The following source code is the answer.
src/android/CustomLayout.java
public class CustomLayout extends CordovaPlugin {
private static final String LOG_TAG = "CustomLayout";
public CustomLayout() {
}
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("alert")) {
this.alert();
return true;
}
return false;
}
public synchronized void alert() {
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
Application app = cordova.getActivity().getApplication();
String package_name = app.getPackageName();
Resources resources = app.getResources();
int layout = resources.getIdentifier("customlayout", "layout", package_name);
int image = resources.getIdentifier("tvDragMe", "id", package_name);
LayoutInflater inflater = cordova.getActivity().getLayoutInflater();
View customview = inflater.inflate(layout, null);
dlg.setView(customview);
ImageView motion = (ImageView) customview.findViewById(image);
motion.setOnTouchListener(new MyTouchListener());
dlg.create();
dlg.show();
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
private class MyTouchListener implements View.OnTouchListener {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, shadowBuilder, view, 0);
view.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
}
XML file
<name>Layout</name>
<description>Cordova Custom Dialog Layout Plugin</description>
<keywords>cordova,layout</keywords>
<js-module src="www/customlayout.js" name="customlayout">
<merges target="customlayout" />
</js-module>
<!-- android -->
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="CustomLayout">
<param name="android-package" value="org.apache.cordova.dialogs.CustomLayout"/>
</feature>
</config-file>
<source-file src="src/android/CustomLayout.java" target-dir="src/org/apache/cordova/dialogs" />
<source-file src="src/android/res/drawable/smiles.jpg" target-dir="res/drawable" />
<source-file src="src/android/res/layout/customlayout.xml" target-dir="res/layout" />
</platform>
| {
"pile_set_name": "StackExchange"
} |
Q:
Conceptual question about uniformly picking vertices in graphs
The precise question is the following: consider a bipartite Graph $G=A \cup B$. If I pick a vertex $v$ in $A$ uniformly at random, what is the probability that a given vertex $w \in B$ is a neighbour of $v$?
My thoughts: first I note that $v$ is a neighbour of $w$ iff $w$ is a neighbour of v. So the probability that $w$ is a neighbour of $v$ is equal to the probability that $v$ is a neighbour of $w$ (right?). But then since $v$ is picked uniformly at random this probability is given by $|N(w)|/|A|$ where $N(w)$ denotes the neighbourhood of $w$.
Please help me clearify my thoughts.
Also: If my reasoning is correct, why is the following computation wrong.
Porbability is given by $2e(G)/(n(n-1))$ i.e number of edges of $G$ divided by number of total possible edges in $G$? It makes sense to me since we are not picking edges uniformly at random but vertices. But how would you explain this formally?
A:
Your reasoning is correct, this is just the usual "success cases divided by total cases" thing.
If one wanted to make this overly formal (and at the same time presumably less comprehensible):
We consider uniform choice from $A$, i.e., our probability space $(\Omega,\mathcal F,P)$ is given by the sample space $\Omega=A$, the set of events $\mathcal F=\mathcal P(A)$, and the probability function given by $P(E)=\frac{|E|}{|A|}$ for $E\in\mathcal P(A)$ (where we sometimes also write $P(v\in E)$ instead of $P(E)$).
We are asking for the event "the chosen vertex $v$ is neighbour of the given vertex $w$" or $$P(v\in N(w))=P(N(w)\cap A)=P(N(w))=\frac{|N(w)|}{|A|}$$
where the second equality uses the fact that $G$ is bipartite and $w\in B$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create weekly composite from 5-consecutive day
I have a NetCDF file of salinity in Indonesia water with 4 dimensions (lon, lat, depth and time). How to create create weekly composite from my data
download data here: https://onedrive.live.com/redir?resid=6FFDD661570C7D0A%21177
output map here: https://onedrive.live.com/redir?resid=6FFDD661570C7D0A%21176
I would like to convert the raster into vector and the use apply to get the mean, but I have problem to plot the vector data using rasterVis
A:
With your example, nor really complicated:
# load needed librairies
library(rasterVis)
# open the data
salinity <- brick("data.nc", varname = "salinity")
salinity
# class : RasterBrick
# dimensions : 61, 61, 3721, 5 (nrow, ncol, ncell, nlayers)
# resolution : 0.08333333, 0.08333333 (x, y)
# extent : 104.9583, 110.0417, -5.041667, 0.04166667 (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84
# data source : data.nc
# names : X252331200, X252417600, X252504000, X252590400, X252676800
# z-value : 252331200, 252417600, 252504000, 252590400, 252676800
# varname : salinity
# level : 1
# Calculate the mean
m.salinity <- mean(salinity)
m.salinity
# class : RasterLayer
# dimensions : 61, 61, 3721 (nrow, ncol, ncell)
# resolution : 0.08333333, 0.08333333 (x, y)
# extent : 104.9583, 110.0417, -5.041667, 0.04166667 (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84
# data source : in memory
# names : layer
# values : 18.85652, 31.84299 (min, max)
| {
"pile_set_name": "StackExchange"
} |
Q:
Per-file (ideally per-section) clang-format style override
I would like to mark part of a file with something like:
// clang-format -style="{ SomeSetting: NewValue }"
...
// clang-format -style="{ SomeSetting: OldValue }"
that would override the global settings in the root .clang-format file. If not possible, specific formatting a single file would also do as I could work around by isolating the section that requires the specific formatting in its own file. I have a git pre-commit hook that does the formatting on staged files as well as IDE plugins that run clang-format on their own, but I don't want to have to mark specific files and specific settings in either of these places.
The best I can do now is to format the file with the custom settings, put // clang-format off, // clang-format on guards around the section and revert the settings back, which is not sustainable in the long term. Is there a better solution?
A:
What you want is currently (clang 11) not possible, but is certainly a nice feature to add to clang-format.
Current documentation on Clang-Format Style Options states nothing about entering style options in code. As you said, the closest we can get is using // clang-format off and // clang-format on hints.
| {
"pile_set_name": "StackExchange"
} |
Q:
R: loop through one column of data frame and output
I have a data frame df in R like this. I want to loop through df according to different value of hee_provn1
npi_one npi_two hee_provn1
1 2 175221
3 4 175221
5 6 175221
7 8 175221
9 10 576546
11 12 576546
13 14 576546
15 16 789535
17 18 789535
19 20 789535
Now my R code is:
library(dplyr)
library(igraph)
df2 <- filter(df, hee_provn1 == '175221')
df3 <- df2 [,c("npi_one","npi_two")]
l = c(apply(df3,1,c))
G <- graph(l,directed = FALSE )
degree(G) -> d
closeness(G) -> c
betweenness(G) -> b
eigen_centrality(G)$vector -> e
cent_df = data.frame(d,c,b,e)
colnames(cent_df) <- c('degree', 'closeness','betweenness','eigen')
cbind(hee_provn1 = 175221,cent_df)
The result table cent_df of the first loop (hee_provn1 = 175221) is
hee_provn1 degree closeness betweenness eigen
1 175221 1 0.02040816 0 0.3227867
2 175221 1 0.02040816 0 0.3227867
3 175221 1 0.02040816 0 0.0000000
4 175221 1 0.02040816 0 0.0000000
5 175221 1 0.02040816 0 1.0000000
6 175221 1 0.02040816 0 1.0000000
7 175221 1 0.02040816 0 0.0000000
8 175221 1 0.02040816 0 0.0000000
The result table cent_df of the second loop (hee_provn1 = 576546) is
hee_provn1 degree closeness betweenness eigen
1 576546 0 0.005494505 0 0
2 576546 0 0.005494505 0 0
3 576546 0 0.005494505 0 0
4 576546 0 0.005494505 0 0
5 576546 0 0.005494505 0 0
6 576546 0 0.005494505 0 0
7 576546 0 0.005494505 0 0
8 576546 0 0.005494505 0 0
9 576546 1 0.005917160 0 1
10 576546 1 0.005917160 0 1
11 576546 1 0.005917160 0 0
12 576546 1 0.005917160 0 0
13 576546 1 0.005917160 0 0
14 576546 1 0.005917160 0 0
My idea result is troughing a loop, I can put all the result table together in one big table like
hee_provn1 degree closeness betweenness eigen
1 175221 1 0.02040816 0 0.3227867
2 175221 1 0.02040816 0 0.3227867
3 175221 1 0.02040816 0 0.0000000
4 175221 1 0.02040816 0 0.0000000
5 175221 1 0.02040816 0 1.0000000
6 175221 1 0.02040816 0 1.0000000
7 175221 1 0.02040816 0 0.0000000
8 175221 1 0.02040816 0 0.0000000
9 576546 0 0.005494505 0 0
10 576546 0 0.005494505 0 0
11 576546 0 0.005494505 0 0
12 576546 0 0.005494505 0 0
13 576546 0 0.005494505 0 0
14 576546 0 0.005494505 0 0
15 576546 0 0.005494505 0 0
16 576546 0 0.005494505 0 0
17 576546 1 0.005917160 0 1
18 576546 1 0.005917160 0 1
19 576546 1 0.005917160 0 0
20 576546 1 0.005917160 0 0
21 576546 1 0.005917160 0 0
22 576546 1 0.005917160 0 0
And I really hope it can be as efficient as possible.
A:
Your example data
df <- data.frame(npi_one=seq(1,19,2),
npi_two=seq(2,20,2),
hee_provn1=c(rep(175221,4),rep(576546,3),rep(789535,3)))
In addition to igraph you will need tidyverse
library(tidyverse)
library(igraph)
I have annotated the following code to match that of your original code
final <- df %>%
group_by(hee_provn1) %>% # similar to filter(df, hee_provn1 == '175221')
nest() %>% # similar to df2 [,c("npi_one","npi_two")]
mutate(data=map(data,~c(apply(.x,1,c)))) %>% # similar to c(apply(df3,1,c))
mutate(data=map(data,~graph(.x,directed=F))) %>% # similar to graph(l,directed = FALSE )
mutate(data=map(data,~ data.frame( degree = degree(.x),
closeness = closeness(.x),
betweenness = betweenness(.x),
eigen_centrality = eigen_centrality(.x)$vector ) ) ) %>% # similar to making b, c, d, e individually
unnest(data) # revert to normal data frame
Output head(final)
hee_provn1 degree closeness betweenness eigen_centrality
1 175221 1 0.020408163 0 1.000000e+00
2 175221 1 0.020408163 0 1.000000e+00
3 175221 1 0.020408163 0 0.000000e+00
4 175221 1 0.020408163 0 0.000000e+00
NOTE Each time I run eigen_centrality I get different values, so make sure that this returns the values you expect
| {
"pile_set_name": "StackExchange"
} |
Q:
Detectar si una app está instalada en Android
Quisiera detectar si una app está instalada o no en el dispositivo, por ejemplo Google Earth.
Y si está instalada ejecutarla des de la app.
A:
Para detectar si esta instalada una aplicacion, necesitas conocer el paquete, y puedes detectar si esta instalada en el dispositivo por medio de la clase PackageManager , este es un metodo que podrias utilizar:
private boolean estaInstaladaAplicacion(String nombrePaquete, Context context) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(nombrePaquete, PackageManager.GET_ACTIVITIES);
return true;
} catch (NameNotFoundException e) {
return false;
}
}
y lo puedes usar de esta forma:
if(estaInstaladaAplicacion("com.google.earth", getApplicationContext())){
//esta instalada.
}else{
//no esta instalada.
}
Para abrir la aplicacion, lo puedes realizar mediante un intent al comprobar que tienes instalada la aplicacion por medio del paquete:
String nombrePaquete = "com.google.earth";
Intent intent = getPackageManager().getLaunchIntentForPackage(nombrePaquete );
if(intent == null) {
//No se puede abrir aplicacion.
}
startActivity(intent); //Abre aplicacion.
A:
Proba esto:
private boolean isPackageInstalled(String packagename, Context context) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
return true;
} catch (NameNotFoundException e) {
return false;
}
}
aca te dejo un ejemplo:
public void someMethod() {
// ...
PackageManager pm = context.getPackageManager();
boolean isInstalled = isPackageInstalled("com.somepackage.name", pm);
// ...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Delete Persistent Object when app is Deleted in Blackberry
I am using persistent object in blackberry to store config details specific to the app. Here is how I am implementing the class
public class Preferences implements Persistable
{
private static PersistentObject persistentObject = PersistentStore.getPersistentObject(0x2759d6ff72264bdbL);
private static Hashtable tbl = new Hashtable();
public static void storeLoginToken(String token)
{
token = removeCharAt(token,0);
token = removeCharAt(token,token.length()-1);
tbl.put("token", token);
persistentObject.setContents(tbl);
persistentObject.commit();
}
public static String getLoginToken()
{
Hashtable tbl = (Hashtable)persistentObject.getContents();
try
{
String token = tbl.get("token").toString();
System.out.println("Token = "+token);
return token;
}
catch(Exception e)
{
return null;
}
}
}
But if I uninstall/delete the app these stored values are not getting deleted. When I installs the app for next time the app is fetching the old stored values.
How can i do this properly in blackberry?
Thanks
A:
Create a custom hashtable class like this
package com.myapp.items;
import net.rim.device.api.util.Persistable;
import java.util.*;
public class MyAppHashtable extends Hashtable implements Persistable{
}
And change your code to
public class Preferences
{
private static PersistentObject persistentObject = PersistentStore.getPersistentObject(0x2759d6ff72264bdbL);
private static MyAppHashtable tbl = new MyAppHashtable ();
public static void storeLoginToken(String token)
{
token = removeCharAt(token,0);
token = removeCharAt(token,token.length()-1);
tbl.put("token", token);
persistentObject.setContents(tbl);
persistentObject.commit();
}
public static String getLoginToken()
{
MyAppHashtable tbl = (MyAppHashtable )persistentObject.getContents();
try
{
String token = tbl.get("token").toString();
System.out.println("Token = "+token);
return token;
}
catch(Exception e)
{
return null;
}
}
}
This is so that we adhere to the following info from RIM
The BlackBerry persistence model
When you use the BlackBerry persistence model, data is only deleted if the store contains data that belongs to the removed application.
For example, if an application stores an object with a package called com.mycompany.application.storage and no other application on the BlackBerry smartphone makes reference to the package, the persistent store and the removed application are deleted.
The same is true if the object is wrapped in a container such as a Vector. Even if only one of the elements of the Vector has a package name that is not used by other applications, the entire Vector is removed from the persistent store.
Note: If the application does not store any objects with an identifying package structure, (for example, an application that stores java.util.Vector or javax.microedition.location.AddressInfo objects), the application should create and use a class that extends Vector in order to identify that Vector belongs to the given application. When you store this Vector, which is identified uniquely by its package, you guarantee that the data is removed from the persistent store when the application is removed.
This info is from here
| {
"pile_set_name": "StackExchange"
} |
Q:
New Jersey budget plan
Governor Murphy of NJ has proposed a state budget plan. I've been trying to find a copy of the budget plan on the internet, but can't find it. I also checked on the NJ state website.
Is it available to the public?
A:
Took a good amount of digging:
http://www.nj.gov/treasury/omb/publications/19bib/BIB.pdf
| {
"pile_set_name": "StackExchange"
} |
Q:
Load JSON data into a Bootstrap modal
I want to load a JSON file that creates a list inside a Bootstrap Modal. I have it set where if you click on a person's picture, the modal pops up.
<li class="project span3" data-type="pfa">
<a data-toggle="modal" data-target="#myModal" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
</a>
</li>
Here's an example of the JSON data:
var florida_exoneration = [
{
"last_name":"Atkins",
"first_name":"Kenneth",
"age":16,
"race":"Caucasian",
"state":"FL",
"crime":"Sexual Assault",
"sentence":"10 years",
"conviction":2004,
"exonerated":2008,
"dna":"",
"mistaken witness identification":"",
"false confession":"",
"perjury/false accusation":"Y",
"false evidence":"",
"official misconduct":"",
"inadequate legal defense":"",
"compensation":""
}
]
I'd like the modal to display something like this inside the box:
Title = "first_name + last_name"
Age = "age"
Race = "race"
State = "state"
""
""
I also want to make sure the data is tied to the picture so the modal doesn't get confused. I'm sorry if this is a bit confusing. I'll try and clarify if anyone has any questions.
A:
Method 1: using Ajax
Every time a user clicks an image, you get the id from the clicked image and then you send an Ajax request to server in order to get the JSON object.
HTML
<ul>
<li class="project span3" data-type="pfa">
<a href="#" data-id="2" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
</a>
</li>
</ul>
JavaScript
(function($) {
var infoModal = $('#myModal');
$('.thumbnail').on('click', function(){
$.ajax({
type: "GET",
url: 'getJson.php?id='+$(this).data('id'),
dataType: 'json',
success: function(data){
htmlData = '<ul><li>title: '+data.first_name+'</li><li>age: '+data.age+'</li></ul>';
infoModal.find('.modal-body').html(htmlData);
infoModal.modal('show');
}
});
return false;
});
})(jQuery);
Method 2: using hidden div
No need to any Ajax request, but you need to create a hidden div that contain all the information you want to display in the modal
HTML
<ul>
<li class="project span3" data-type="pfa">
<a href="#" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
<div class="profile hide">
<ul>
<li>title: Atkins Kenneth</li>
<li>Age: 16</li>
</ul>
</div>
</a>
</li>
</ul>
JavaScript
(function($) {
var infoModal = $('#myModal');
$('.thumbnail').on('click', function(){
htmlData = $(this).find('.profile').html();
infoModal.find('.modal-body').html(htmlData);
infoModal.modal('show');
return false;
});
})(jQuery);
| {
"pile_set_name": "StackExchange"
} |
Q:
Alert showing two times
I use cordova and Framework7 for create app. My script load and show image from server fine, but if server return 404 I get alert 2 times. Why, and how can I fix it?
function view(a) {
var img = new Image();
var s = a;
myApp.showPreloader('Загружаем...');
img.src = s;
img.onload = function() {
document.getElementById('showimg').innerHTML = '';
var openPhotoSwipe = function(a) {
myApp.hidePreloader();
myApp.allowPanelOpen = false;
document.getElementById("check").style.display = "block";
var pswpElement = document.querySelectorAll('.pswp')[0];
var items = [{
src: s,
w: img.width,
h: img.height
}];
var options = {
showAnimationDuration: 0,
hideAnimationDuration: 0
};
var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
gallery.listen('destroy', function() {
document.getElementById("check").style.display = "none";
var elements = document.getElementsByTagName("input");
for (var ii = 0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}
$$(window).width() < 770 && (myApp.allowPanelOpen = !0);
});
};
openPhotoSwipe();
}
img.onerror = function() {
myApp.alert('Not found...');
myApp.hidePreloader();
}}
A:
Try this:
function view(a) {
var img = new Image();
var s = a;
myApp.showPreloader('?????????...');
img.src = s;
var alertShown = false;
img.onload = function() {
document.getElementById('showimg').innerHTML = '';
var openPhotoSwipe = function(a) {
myApp.hidePreloader();
myApp.allowPanelOpen = false;
document.getElementById("check").style.display = "block";
var pswpElement = document.querySelectorAll('.pswp')[0];
var items = [{
src: s,
w: img.width,
h: img.height
}];
var options = {
showAnimationDuration: 0,
hideAnimationDuration: 0
};
var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
gallery.listen('destroy', function() {
document.getElementById("check").style.display = "none";
var elements = document.getElementsByTagName("input");
for (var ii = 0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}
$$(window).width() < 770 && (myApp.allowPanelOpen = !0);
});
};
openPhotoSwipe();
}
img.onerror = function() {
myApp.hidePreloader();
if(!alertShown){
alertShown = true;
myApp.alert('Not found...');
}
}}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What do opaque rims on biotite in a volcanic rock mean?
In a volcanic region, i have examined two samples petrographically. One of them has biotites with extensive opacitic rims. The other samples biotites hasn't got this property. They have the same modal mineral contents. What makes the difference?
A:
There are several options.
During decompression, biotite is no longer stable and the hydrogen volatilises, leaving behind fine-grained intergrowth of oxide and silicate minerals.
Oxidation of the rims during exposure of the lava to the atmosphere. Higher Fe3+ contents would make the biotite darker.
It is impossible to tell without a detailed electron microscopy analysis. However, my guess it that it is option 1.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are cricket farms for human nutrition allowed in Germany?
Is it allowed to breed and sell human edible crickets commercially? Can't find any farms by googling.
A:
The exact answer will depend on the details (scale of the operation, where it is happening, what purpose the crickets are being sold for etc.), but in general:
Yes, breeding and selling crickets is allowed in general.
Here's an article (German) on someone who plans to breed insects for food (the article only says he is breeding "Heuschrecken", which could be several different species from the order Orthoptera, but it's probably close enough):
Insekten auf dem Teller - Thorsten Breitschuh baut eine Heuschreckenzucht auf ("Insects on the plate - Thorsten Breitschuh is starting an orthoptera breeding program")
The article does mention some legal problems, but they mostly revolve around getting the insects certified as safe food, and complying with environment regulations during the breeding.
Also, you can buy crickets and similar insects in many pet stores as animal food for reptiles, so breeding and selling them as animal food is definitely not prohibited.
| {
"pile_set_name": "StackExchange"
} |
Q:
Uniqueness of the Comparison Functor
Suppose $F:C\rightarrow D$ and that $F\dashv U$ is an adjunction and $C^{T}$ the Eilenberg–Moore category for the monad $T=U◦F$, with the corresponding functors $F^{T}:C\rightarrow C^{T}$ and $U^{T}:C^{T}\rightarrow C$.
I have been able to prove that there is a comparison functor $Φ : D →C^{T}$ which satisfies
(1) $U^{T}◦Φ= U$
and
(2) $Φ◦F = F^{T}$
I am having trouble with uniqueness.
Here is what I have so far: Suppose $Φ'$ satisfies (1) and (2).
Let $U\in D$. Then using (1) with $Φ'(D)=(C',\alpha )$, it follows that $U◦Φ'(D)=U(C',\alpha )=C'$ whereas $Φ(D)=(UD,U\varepsilon_{D})$ and so $U◦Φ(D)=U(UD,\varepsilon_{D})=UD$ which says $C'=UD$
Now I need to show that $\alpha=U\varepsilon_{D}$. This is where I'm stuck.
edit: Using the hint below, the fact that the adjunctions have the same unit imply, after using (1) and (2) that
\begin{matrix}
\operatorname{Hom}(FC, D) & \xrightarrow{{\phi}} & \operatorname{Hom}(C, UD) \\
\left\downarrow\vphantom{\int}\right. & & \left\downarrow\vphantom{\int}\right.\\
\operatorname{Hom}(F^{T}C, Φ'(D))& \xrightarrow{\phi^{T}} & \operatorname{Hom}(C, U^{T}Φ'(D))
\end{matrix}
commutes.
($\phi$ and $\phi^{T}$ are the isomorphisms giving the adjunctions; the left downward arrow is the map $f\longmapstoΦ'(f)$ and the right downward arrow is the identity on the Hom$(C, UD)$.)
Then, setting $C=UD$ and following $id_{UD}$, you get that $Φ'\epsilon=\epsilon^T Φ'$, which is the hint. The rest follows easily.
A:
Here's a version of the proof that bypasses the $\Phi\epsilon=\epsilon^T\Phi$ lemma and proves uniqueness directly.
$U^T\Phi=U$ tells us that $\Phi d$ is a $T$-algebra with structure map $\gamma d: TUd\to Ud$
$\Phi$ sends $D$-arrows to $T$-homomorphisms, so $\gamma$ is a natural transformation $TU\to U$
$\Phi F=F^T$ tells us that $\gamma F=\mu =U\epsilon F$
Since $\gamma$ is natural we have $U\epsilon\circ\mu U=U\epsilon\circ\gamma FU=\gamma\circ TU\epsilon$
Precomposing with $T\eta U$ gives us $U\epsilon\circ\mu U\circ T\eta U=\gamma\circ TU\epsilon\circ T\eta U$
This rearranges as $U\epsilon\circ(\mu\circ T\eta)U=\gamma\circ T(U\epsilon\circ\eta U)$, which simplifies to $U\epsilon=\gamma$
| {
"pile_set_name": "StackExchange"
} |
Q:
Pop up box disappears when I click the text box
I have created a small call back popup on the footer
http://bit.ly/1MThJ5w
The problem is when I click the text box it disappeared. I don't know how to stop that. Does anyone has any ideas on how to fix this? Thanks.
It should only close and open when I click- CALL BACK
And also the close and open arrows are not showing as well
My code snippet:
<script type="text/javascript">
$(document).ready(function() {
$('.foot').click(function() {
if($('.foot').hasClass('slide-up')) {
$('.foot').addClass('slide-down', 1000);
$('.foot').removeClass('slide-up');
} else {
$('.foot').removeClass('slide-down');
$('.foot').addClass('slide-up', 1000);
}
});
});
CSS CODE:
/*Contact Styles
------------------------------------*/
.contact{
width:28%;
float:left;
padding-left:20px;
background:#001832;
color:#FFFFFF;
padding-top:15px;
padding-bottom:12px;
}
.contact h2{
font-size:27px;
font-family:impact;
font-weight:500;
color:#fff;
}
.contact form{
margin-top:6px;
}
.contact label{
font-size:10px;
}
.contact input{
width:210px;
color:#666;
}
.contact a{
text-decoration:none;
text-align: center;
background: none repeat scroll 0% 0% #0060A3;
color: #FFF;
display: inline-block;
padding: 12px 37px;
margin-top: 5px;
font-family: arial;
font-weight: 700;
margin-bottom:15px;
}
.contact .btn{
text-decoration:none;
text-align: center;
background: #0060A3;
color: #FFF;
display: inline-block;
padding: 10px 20px;
margin-top: 5px;
font-family: arial;
font-weight: 700;
margin-bottom:15px;
font-size:20px;
border-radius:0;
-webkit-border-radius:0;
-moz-border-radius:0;
}
/*Slider footer*/
.foot {
position:fixed;
width: 300px;
z-index: 10000;
text-align:center;
height: 500px;
font-size:18px;
color: #000;
display: flex;
justify-content: center; /* align horizontal */
right: 0;
left: 0;
margin-right: auto;
margin-left: auto;
bottom: -185px;
}
.slide-up
{
bottom: -445px !important;
}
.slide-down
{
bottom: -185px !important;
}
.call_back{
background:#405E51;
padding:10px;
margin-bottom:10px !important;
color:#fff;
}
#closer{
background:none;
width:10px;
margin-top: -25px;
margin-right: 15px;
float:right;
}
#closer{
background:none;
width:10px;
margin-top: -25px;
margin-right: 15px;
float:right;
}
A:
Your click event is bound to the wrong element. Change it to the "call_back" class instead.
Change this:
$('.foot').click(function() {
// your code
});
To this:
$('.call_back').click(function() {
// your code
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Using distinct-values within an xpath predicate
I'm working with XSLT/Xpath 2.0 and am trying to write an xpath statement that will allow me to filter some duplicate nodesets I have in my XML. Here's an example XML:
<?xml version="1.0" encoding="utf-8"?>
<test>
<card>
<TimeCard>1234</TimeCard>
<tax>HST</tax>
<adjAmt>-112</adjAmt>
</card>
<card>
<TimeCard>1234</TimeCard>
<tax>GST</tax>
<adjAmt>-112</adjAmt>
</card>
<card>
<TimeCard>4321</TimeCard>
<tax>HST</tax>
<adjAmt>-50</adjAmt>
</card>
<card>
<TimeCard>4321</TimeCard>
<tax>GST</tax>
<adjAmt>-50</adjAmt>
</card>
<card>
<TimeCard>2121</TimeCard>
<tax>GST</tax>
<adjAmt>-55</adjAmt>
</card>
</test>
I need an xpath that would return "adjAmt" but only once per "TimeCard". My host system creates duplicate "card" entries for "adjAmt" when different types of taxes are charged. In the above example, I only one it to return -112, -50, and -55; one entry per "timecard".
I've tried using distinct-values in a multitude of different spots against the timecard element but have not had any luck.
Anyone have any suggestions on what might work best?
A:
In XSLT 2 or 3 you could use for-each-group group-by to group the card elements by the TimeCard child element and then return the context node's adjAmt child or its number value as follows:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:mf="http://example.com/mf"
exclude-result-prefixes="xs mf"
version="3.0">
<xsl:output method="text"/>
<xsl:function name="mf:group-and-select-first" as="xs:decimal*">
<xsl:param name="cards" as="element(card)*"/>
<xsl:for-each-group select="$cards" group-by="TimeCard">
<xsl:sequence select="xs:decimal(adjAmt)"/>
</xsl:for-each-group>
</xsl:function>
<xsl:template match="/">
<xsl:value-of select="mf:group-and-select-first(test/card)"/>
</xsl:template>
</xsl:stylesheet>
https://xsltfiddle.liberty-development.net/bFDb2BP
I have wrapped that grouping code into a function as your question talks about using the code in an XPath predicate, the example simply calls the function in a function call of an xsl:value-of select expression but of course you can as well use that function inside of a predicate if needed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find the real Parent Element
I have a website that runs out of an iframe.
To logout I run the following JavaScript with a URL and this works fine.
window.parent.location.href
I catch I have is sometimes if I don't exit the site correctly and then reconnect I endup with 2 iframes (potentially more).
Is there a way to make the following JavaScript find the outer most (the true parent) of all potential iframes?
window.parent.location.href
I want to make sure no matter how many iframes are present the redirection will still occur.
any advice would be great... thx
A:
Use window.top instead of window.parent
| {
"pile_set_name": "StackExchange"
} |
Q:
Only import XML if it has been updated
I'm using NSURLConnection to grab an XML file. I parse the XML file and then use it to populate Core Data.
If the NSURLConnection fails to connect (i.e. user has no internet connection), I just read the persistent data from Core Data.
However, I'm thinking... Is there a way that I can do a check on the XML file to see if it has updated from the last time I used it? So I can save redownloading/repopulating it if is unchanged?
Checking Last Modified on the file or something?
Anyone have a good solution for this?
Thanks!
A:
This can be done by checking the http headers or etags.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access MouseEvent getX()/getY() from JPopupMenu?
I have a popupmenu like this
final JPopupMenu contextMenu = new JPopupMenu();
final JMenuItem addTask = new JMenuItem("Add Task");
Then i add a MouseListener:
component.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e)
{
if (e.isPopupTrigger()) {
contextMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
}
In my Actionlistener for the MenuItem i would like to access the x/y-data from my MouseEvent. Is this possible without saving them in an extra variable? i would like to get something like this:
addTask.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//System.out.println(Mouse.getX()+", "+Mouse.getY());
}
});
A:
If you want to get the mouse coordinate of event which has trggered the popup menu - no it's impossible without to save it. If you want to get the mouse event whcih has triggered the menu item action - yes it's possible: EventQueue.getCurrentEvent(); will return the event (you should check whether this event is a mouse event and if yes - cast it, because the action can also be triggered with key event).
public void actionPerformed(ActionEvent arg0) {
AWTEvent evt = EventQueue.getCurrentEvent();
if (evt instanceof MouseEvent) {
MouseEvent me = (MouseEvent) evt;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
onclick element for an element that is not created yet
I am using the google search API and I want that when you click on an image, this image will be copied to a different location.
I created a fiddle here: http://fiddle.jshell.net/wjewg062/
It works this way: The user types in a term in the input field and images will be displayed. When he/she clicks on one twice it will displayed in the image div.
I put the onClick event listener on to the searchresults div, hence the extra click in the beginning. However, I want it to be displayed on the first click.
Now, if I comment this out
var searchresults = document.getElementById('searchresults');
searchresults.addEventListener("click", function(event){
event.preventDefault();
imageing();
});
it doesn't work. The images will be links. I believe the reason for this is that the results are displayed in gs-image-box and not created yet. I tried calling the imaging function in different other functions like the searchImg or the OnLoad but nothing work.
I thought of using a check if element is clicked function described here Detect if I'm clicking an element within an element
but I think there must be an easier way.
I'm running out of ideas, can anyone give an idea or hint?
Thanks !
A:
The info you need is already in your searchresults eventListener. The target of this event will be the image you click, even if you add the event on a div higher in the structure.
A javascript event will by default be dispatched from the top element (window) all the way through the element that received the click, then will go back to the top. Any element that is an ancestor of the element that was clicked will receive the event info, so you can listen on any ancestor, but the target remains the element that was actually clicked.
In your case, by simply passing the target to your imageing() function, you can apply the behaviors you want without any extra manipulations.
One problem you might face, is if user clicks on searchresult but not on an img element. Then you'll have a bug, so you should handle these cases.
Something like this:
var searchresults = document.getElementById('searchresults');
searchresults.addEventListener("click", function (event) {
console.log(event.target, this);
event.preventDefault();
if(event.target.tagName == 'IMG'){
imageing(event.target);
}
});
function imageing(targetImg) {
var imageresult = document.getElementsByClassName('gs-image-box');
var xu = document.getElementById('companylogo');
var imgsrc = targetImg.src;
xu.src = imgsrc;
}
http://fiddle.jshell.net/pwjLrfnt/3/
| {
"pile_set_name": "StackExchange"
} |
Q:
No annotations present when reflecting a method using class.getDeclaredMethod
I'm writing some unit tests using reflection, and I'm having trouble retrieving annotations from method parameters.
I declared this interface:
private interface Provider {
void mock(@Email String email);
}
And I'm trying to reflect this method, as follows:
Class stringClass = String.class;
Method method = Provider.class.getDeclaredMethod("mock", String.class);
AnnotatedType annotatedType = method.getAnnotatedParameterTypes()[0];
Annotation annotation = annotatedType.getAnnotation(Annotation.class);
I'm expecting that annotation variable holds an instance of @Email annotation, but instead, its value is null.
Even this simple check returns false:
method.isAnnotationPresent(Email.class)
So, how can I retrieve the annotations for an specific param when reflecting a method?
Updated
It seems that in order to retrieve the parameters annotation I need to call method.getParameterAnnotations(). But the problem with this is that I don't know what annotations belong to what methods.
A:
If you want annotation to be visible during program execution, you need to annotate it with @Retention(RetentionPolicy.RUNTIME):
private interface Provider {
void mock(@Email String email);
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Email{}
@Test
public void test_annotation_existence() throws NoSuchMethodException {
Method method = Provider.class.getDeclaredMethod("mock", String.class);
Annotation[] firstParameterAnnotationsArray = method.getParameterAnnotations()[0];
boolean isAnnotationPresent = isAnnotationPresent(firstParameterAnnotationsArray, Email.class);
Assert.assertTrue("Annotation not present!", isAnnotationPresent);
}
private boolean isAnnotationPresent(Annotation[] annotationsArray, Class clazz) {
if (annotationsArray == null)
throw new IllegalArgumentException("Please pass a non-null array of Annotations.");
for(int i = 0; i < annotationsArray.length; i++ ) {
if (annotationsArray[i].annotationType().equals(clazz))
return true;
}
return false;
}
A:
You have to make a distinction between the Java 8 type annotations and the (since Java 5) parameter annotations. The crucial thing about type annotations, is, that you have to declare the possibility of using your annotation as type annotation explicitly.
Consider the following example:
public class AnnoTest {
@Retention(RetentionPolicy.RUNTIME)
@interface Email {}
void example(@Email String arg) {}
public static void main(String[] args) throws ReflectiveOperationException {
Method method=AnnoTest.class.getDeclaredMethod("example", String.class);
System.out.println("parameter type annotations:");
AnnotatedType annotatedType = method.getAnnotatedParameterTypes()[0];
//Annotation annotation = annotatedType.getAnnotation(Annotation.class);
System.out.println(Arrays.toString(annotatedType.getAnnotations()));
System.out.println("parameter annotations:");
System.out.println(Arrays.toString(method.getParameterAnnotations()[0]));
}
}
it will print
parameter type annotations:
[]
parameter annotations:
[@AnnoTest$Email()]
In this case the annotation is a property of the parameter.
Now change it to (note the @Target)
public class AnnoTest {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
@interface Email {}
void example(@Email String arg) {}
public static void main(String[] args) throws ReflectiveOperationException {
Method method=AnnoTest.class.getDeclaredMethod("example", String.class);
System.out.println("parameter type annotations:");
AnnotatedType annotatedType = method.getAnnotatedParameterTypes()[0];
//Annotation annotation = annotatedType.getAnnotation(Annotation.class);
System.out.println(Arrays.toString(annotatedType.getAnnotations()));
System.out.println("parameter annotations:");
System.out.println(Arrays.toString(method.getParameterAnnotations()[0]));
}
}
which will print
parameter type annotations:
[@AnnoTest$Email()]
parameter annotations:
[]
instead. So now, the annotation is a feature of the parameter type, i.e. String. Conceptionally, the parameter type of the method is now @Email String (which seems to be the most logical choice, as it allows declaring types like List<@Email String>, but you have to understand how these new type annotations work and it doesn’t work together with pre-Java 8 libraries).
Care must be taken when enabling an annotation for both, parameters and type use, as this can create ambiguous annotations.
If that happens, the compiler will record the annotations for both, the parameter and the type, e.g.
when you change the target in the example to @Target({ElementType.TYPE_USE, ElementType.PARAMETER}), it will print
parameter type annotations:
[@AnnoTest$Email()]
parameter annotations:
[@AnnoTest$Email()]
similar issues may arise at method return types, resp. field types when enabling an annotation for “type use” and methods, resp. fields.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to debug random data abort issue on arm based platform
As developing on ARM based project, we get data abort randomly, that is when we play with it we get a data abort interrupt. But the data abort is not always on the same point when we check with the register map with r14 or r13, even though check the function callback. Is there anyway that I can get the information about the root cause on data abort precisely? I have try the ref2 but could not get the same point when I trap the data about interrupt.
Related
ARM Data Abort error exception debugging
ARM: HOW TO ANALYZE A DATA ABORT EXCEPTION
A:
Checking the link register (r14) as described in your Keil link above will show you the instruction that triggered the data abort. From there you'll have to figure out why it triggered a data abort and how that could have happened, which is the difficult part.
In my experience what most likely happened is that you accessed an invalid pointer. It can be invalid for many reasons. Here are a few candidates:
You used the pointer before it was initialized
You used the pointer after it, or the containing memory, had been freed (and was subsequently modified when another function allocated it)
The pointer was corrupted by a stack overflow
The pointer was corrupted by other, unrelated, misbehaving code that is trampling on memory
The pointer was allocated on the stack as a local variable and then used after the allocating function had exited
The pointer has incorrect alignment for its type (for example, trying to access 0x4001 as a uint32_t)
As you can see, lots of things can be the root cause of an ARM data abort. Finding the root cause is part of what makes ARM software/firmware development so much fun! Good luck figuring out your puzzle.
| {
"pile_set_name": "StackExchange"
} |