text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Destroying a user can leave a bounty open on a deleted question
This question is a bit of an odd case.
The user placed a bounty on it, then engaged in a rollback war culminating with a lock. He then requested his account to be deleted. It was. The question, which was at -1 at the time, was automatically deleted along with the account. This should not happen since bounty questions ordinarily can be neither closed nor deleted.
Now the bounty languishes in a limbo state, its clock ticking away in futility, hoping against desperate hope that someone somewhere will rescue it. But no one hears its cries.
Cheer? No, I'm afraid not.
A:
Nothing bad happens from this "bug", the bounty simply times out with no action.
It should also be exceedingly rare to have a user deleted with a bounty in flight.
Thus, I don't think any action is warranted here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Canon 70-200 F4 L USM (non-IS) vs Tamron 70-300 VC
Please help, I am very torn between these 2 lenses in my budget. I am looking for a telephoto lens to use primarily outdoors for photos of my 3 year old, husband playing football and longer focal length candids. By I don't want to rule out using it indoors totally. I understand neither of these are fast lenses and I don't need VC/IS for running/sport but for the candids when I don't have my tripod with me and for wildlife ie family visits to the zoo etc VC/IS would be very useful. The IS version of the Canon is waaaay out of my budget.
How do the two lenses compare in terms of IQ, contrast, sharpness, AF speed and accuracy? I know I can bump the ISO indoors for the Canon to try and increase my shutter speed to help prevent camera shake but I don't really want to go above ISO 800. Do you think I will struggle not having IS/VC indoors?
I have tried the Tamron (only in a shop) and I was really surprised with what the VC allowed me to hand hold. But I don't want to loose IQ/sharpness/contrast for the sake of VC.
Has anyone compared the two?
I decided on the Tamron and Canon 70-200 F4 L USM (non-IS) and not the Canon 70-300 USM IS because of build quality and being non rotating to use filters. In the UK the prices differ slightly: the Tamron new is £329 and the Canon 70-200 F4 L USM (non-IS) used is selling for about £429 (I could not afford it new), different than the $350 and $709. I wish I could afford the 135mm F2!
A:
Go with the Canon 70-200mm F/4L, its image quality is vastly superior. That is the lens I still use for professional sport photography.
Stabilization does nothing for moving subjects, in order to freeze action in sports even 1/200s is too slow, you often need to shoot around 1/1000s which is fast enough to give your a perfectly sharp image without stabilization. Considering you primary subjects, IS wont be needed.
Not only that, the 70-200mm is F/4 all the way which lets more light in at the long end and lets the camera focus faster. This one focuses very quickly thanks to an internal focusing system and USM motor.
| {
"pile_set_name": "StackExchange"
} |
Q:
Rspec Test Always Failed for Class Method
as the subject said. It is seems the implemented code always create a new record instead of get existing one.
Here is my rspec test code:
describe "#from_facebook" do
it "return existing related user" do
existing_user = FactoryGirl.create(:user)
user_from_facebook = User.from_facebook({ uid: existing_user.uid })
expect(user_from_facebook.email).to eql existing_user.email
end
end
and here is the test implementation:
def self.from_facebook(fb_auth)
where(provider: "facebook", uid: fb_auth[:uid]).first_or_create do |user|
user.email = fb_auth[:email]
user.password = Devise.friendly_token[0, 20]
end
end
I always got this:
1) User#from_facebook return existing related user
Failure/Error: expect(user_from_facebook.email).to eql existing_user.email
expected: "[email protected]"
got: nil
(compared using eql?)
# ./spec/models/user_spec.rb:48:in `block (3 levels) in <top (required)>'
And here are the console results via puts.
for existing_user:
#<User id: 105, email: "[email protected]", encrypted_password: "$2a$04$90uzEdbwfnqfUL0CDhNOH.THUbzovFyJK1OPg7VcgxL...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2015-08-30 04:12:59", updated_at: "2015-08-30 04:12:59", auth_token: "vkvm2-fLe5x1dZGbewqw", provider: nil, uid: "133290925">
for user_from_facebook:
#<User id: nil, email: nil, encrypted_password: "$2a$04$lxdBWBsXY4febfgurgHJKOdNcOMCuQQO2DHshWChnxA...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: nil, updated_at: nil, auth_token: "", provider: "facebook", uid: "133290925">
Please let me know what is wrong here. Thanks in advance.
A:
Your User factory doesn't fully setup the user. It creates the following user object:
#<User id: 105,
email: "[email protected]",
encrypted_password: "$2a$04$90uzEdbwfnq...",
reset_password_token: nil,
reset_password_sent_at: nil,
remember_created_at: nil,
sign_in_count: 0,
current_sign_in_at: nil,
last_sign_in_at: nil,
current_sign_in_ip: nil,
last_sign_in_ip: nil,
created_at: "2015-08-30 04:12:59",
updated_at: "2015-08-30 04:12:59",
auth_token: "vkvm2-fLe5x1dZGbewqw",
provider: nil,
uid: "133290925"
Note that the provider is nil. Thus, your from_facebook method (which looks for the uuid and the provider) cannot find the user.
As a solution, use the following to create your existing_user in the spec:
existing_user = FactoryGirl.create(:user, provider: 'facebook')
| {
"pile_set_name": "StackExchange"
} |
Q:
New using React: TypeError: Cannot read property 'map' of undefined
I'm new in React and I following a tutorial and I'm getting an error and I haven't been able to figure it out. I'm trying to get some data from an API to display it in my project.
This is my code:
import React, { Component } from 'react';
import PhotoList from './PhotoList';
class App extends Component {
constructor() {
super();
this.state = {
photos: []
}
}
componentWillMount() {
fetch('https://jsonplaceholder.typicode.com/photos')
.then((response) => {return response.json()})
.then((photos) => {this.setState({ photos: photos })})
}
render() {
if (this.state.photos.length > 0) {
return (
<div className="container-fluid">
<PhotoList listado={this.state.photos} />
</div>
)
} else {
return <span>Esperando photos</span>
}
}
}
export default App;
import React from 'react';
import Photo from './Photo';
const PhotoList = ({ Photos }) => {
return (
<div>
{
Photos.map((Photos, i) => {
return (
<div>
key={i}
id={Photos[i].id}
title={Photos[i].title}
url={Photos[i].url}
</div>
);
})
}
</div>
);
}
export default PhotoList;
I'm getting this error:
Error
Thank you so much in advance,
A:
There are a few things to point out.
You can follow along on
1. Prop name passed to PhotoList do not match.
Within App, you pass photos to PhotoList using listado property.
<PhotoList listado={this.state.photos} />
But you are trying to retrieve non-existing Photos property.
const PhotoList = ({ Photos }) => {
So either you should change property name to Photos (lowercase preferred)
<PhotoList Photos={this.state.photos} />
or change the declaration of PhotoList
const PhotoList = ({ listado }) => {
2. Conflict with callback argument name
Photos.map((Photos, i) => {
Should be
Photos.map((photo, i) => {
Or any other ID other than Photos.
3. No need to access an element within .map using an array index
Instead of,
Photos.map((Photos, i) => {
return (
<div>
key={i}
id={Photos[i].id}
title={Photos[i].title}
url={Photos[i].url}
</div>
);
})
You should
photos.map((photo, i) => {
return (
<div>
<p>key={i}</p>
<p>id={photo.id}</p>
<p>title={photo.title}</p>
<p>url={photo.url}</p>
</div>
);
})
You can see that photo is an individual photo object thus no need to access it with Photos[i].
| {
"pile_set_name": "StackExchange"
} |
Q:
Failing to install activerecord-jdbcmysql-adapter gem
I am trying to follow the basic "Create a blog in 20 minutes" Rails screencast but have hit a stumbling block already.
When I try to rake db:migrate I get errors about the gem activerecord-jdbcmysql-adapter not being installed. When I try to install it, I am told it doesn't exist.
If I try to simply gem install mysql I get all sorts of madness appearing.
I am running this on Mac OS X 10.6.2 and my installation was all done through gem. My basic setup works (Hello world!).
Here is the error log:
$ rake db:migrate (in /Users/xxxx/Sites/blog) rake aborted!
Please install the jdbcmysql adapter:
gem install activerecord-jdbcmysql-adapter (no such file to load -- active_record/connection_adapters/jdbcmysql_adapter)
(See full trace by running task with --trace)
$ sudo gem install activerecord-jdbcmysql-adapter
ERROR: could not find gem activerecord-jdbcmysql-adapter locally or in a repository
$ sudo gem install mysql Password:
Building native extensions. This
could take a while... ERROR: Error
installing mysql: ERROR: Failed to
build gem native extension.
/opt/local/bin/ruby extconf.rb
checking for mysql_query() in
-lmysqlclient... no checking for main() in -lm... yes checking for
mysql_query() in -lmysqlclient... no
checking for main() in -lz... yes
checking for mysql_query() in
-lmysqlclient... no checking for main() in -lsocket... no checking for
mysql_query() in -lmysqlclient... no
checking for main() in -lnsl... no
checking for mysql_query() in
-lmysqlclient... no checking for main() in -lmygcc... no checking for
mysql_query() in -lmysqlclient... no
* extconf.rb failed * Could not create Makefile due to some reason,
probably lack of necessary libraries
and/or headers. Check the mkmf.log
file for more details. You may need configuration options.
Provided configuration options:
--with-opt-dir --without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog --without-make-prog
--srcdir=. --curdir
--ruby=/opt/local/bin/ruby
--with-mysql-config
--without-mysql-config
--with-mysql-dir --without-mysql-dir
--with-mysql-include
--without-mysql-include=${mysql-dir}/include
--with-mysql-lib
--without-mysql-lib=${mysql-dir}/lib
--with-mysqlclientlib
--without-mysqlclientlib --with-mlib
--without-mlib --with-mysqlclientlib
--without-mysqlclientlib --with-zlib
--without-zlib --with-mysqlclientlib
--without-mysqlclientlib
--with-socketlib --without-socketlib
--with-mysqlclientlib
--without-mysqlclientlib
--with-nsllib --without-nsllib
--with-mysqlclientlib
--without-mysqlclientlib
--with-mygcclib --without-mygcclib
--with-mysqlclientlib
--without-mysqlclientlib
Gem files will remain installed in
/opt/local/lib/ruby/gems/1.8/gems/mysql-2.8.1
for inspection. Results logged to
/opt/local/lib/ruby/gems/1.8/gems/mysql-2.8.1/ext/mysql_api/gem_make.out
A:
Looks like somehow or other I had two versions of rails installed. I originally did:
gem install rails
which installed 2.3.5. Then when I tried to run scaffolding it said I had the wrong version it complained and suggested I installed 2.3.5...
I did this with the command:
gem install -v=2.3.5 rails
This meant I had two (I found that out when I tried to uninstall), and for some reason it was trying to use the Ruby version... That may have been down to Netbeans using the wrong settings too.
In the end I uninstalled everything, ran:
gem install -v=2.3.5 rails
and made sure Netbeans was not trying to use JRuby as it was before. Now I have one version that doesn't complain for scaffolding or db:migrate. Sold!
| {
"pile_set_name": "StackExchange"
} |
Q:
C naming conventions: hidden variables / macros
IIRC, one shall not use built in names (e.g. open, read, etc.), names that start with underscore and capital letters (e.g. _Thread), names that start with double underscore or contain it (e.g. __GCC__). Even more for POSIX compatibility (see GCC naming conventions).
I'm creating a new library, where each function, type or macro begins with prefix (written in capital letters if it is a macro). However, I doubt which names I must use if I create a variable which is global but hidden. Or if it is a macro. Anyway, it shall be hidden. Is there any naming convention that I shall use? I thought that I may use __mycustomprefix_global, but I'm not sure. Thanks in advance!
UPDATE
I know about static and use it everywhere where it is possible. However, I'm speaking about the case where variables/functions/macros must certainly be global.
A:
In principle, identifiers starting with leading underscores are reserved for new language keywords, the C runtime and standard library as well as compiler intrinsics, so you should not use them.
However, if you use a namespace prefix, the chance of collisions are probably low so it won't matter in pratice. Personally, I'd go with a trailing underscore.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add strongly named keys (pfx) to all users on a server
I am trying to configure a jenkins windows slave msbuild tasks on, but I am having issues with click once projects and its strongly named keys.
Depending on which account installs the PFX key, it depends on what the results and errors are.
BACKGROUND:
Projects (ProjectX and ProjectY)
.net 4
ClickOnce app
uses a pfx key "ABC.pfx" to sign the assembly
Jenkins Windows Slave:
the Jenkins windows service runs under the user account "[email protected]"
As jenkins creates a workspace for each project and branch, we copied the "ABC.pfx" file to c:\
ATTEMPTED RESOLUTION 1:
I remote desktop onto server with my user account:
copy ABC.pfx onto the server at C:\
Run command prompt as Administrator
cd c:\
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\sn.exe" -d VS_KEY_123456789
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\sn.exe" -i ABC.pfx VS_KEY_123456789
Open normal command prompt and run (ClickOnce projects have build, then publish msbuild commands):
"C:/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe" "c:/jenkins/workspace/project-x/ProjectX/ProjectX.sln" "/verbosity:normal" /p:configuration="release" /p:outdir="c:/jenkins/workspace/project-x/output/ProjectX/" "/target:Clean;Build" /maxcpucount
"C:/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe" "c:/jenkins/workspace/project-x/ProjectX/ProjectX.sln" "/verbosity:normal" /p:configuration="release" /p:outdir="c:/jenkins/workspace/project-x/output/ProjectX/" "/target:Publish" /maxcpucount
Both of the msbuid command run fine for me
When run under the Jenkins account we get the error:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(2482,5): error MSB3326: Cannot import the following key file: ABC.pfx. The key file may be password protected. To correct this, try to import the certificate again or import the certificate manually into the current user's personal certificate store. [c:\jenkins\workspace\project-x\ProjectX\ProjectX.csproj]
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(2482,5): error MSB3321: Importing key file "ABC.pfx" was canceled. [c:\jenkins\workspace\project-x\ProjectX\ProjectX.csproj]
ATTEMPTED RESOLUTION 2:
I remote desktop onto server with the Jenkins user account
copy ABC.pfx onto the server at C:\
Run command prompt as Administrator
cd c:\
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\sn.exe" -d VS_KEY_123456789
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\sn.exe" -i ABC.pfx VS_KEY_123456789
Open normal command prompt and run:
"C:/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe" "c:/jenkins/workspace/project-x/ProjectX/ProjectX.sln" "/verbosity:normal" /p:configuration="release" /p:outdir="c:/jenkins/workspace/project-x/output/ProjectX/" "/target:Clean;Build" /maxcpucount
Jenkins user account gets the error:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(2482,5): error MSB3326: Cannot import the following key file: ABC.pfx. The key file may be password protected. To correct this, try to import the certificate again or import the certificate manually into the current user's personal certificate store. [c:\jenkins\workspace\project-x\ProjectX\ProjectX.csproj]
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(2482,5): error MSB3321: Importing key file "ABC.pfx" was canceled. [c:\jenkins\workspace\project-x\ProjectX\ProjectX.csproj]
I also get a build error
Does anyone have any idea how to get the Jenkins user account to acknowledge the PFX key?
Thanks for any help,
Sandra
A:
Finally I found the issue and solution to this, and thought I'd put it up if someone else was having a similar issue.
We cloned the build servers that the strongly named keys were on. After they were cloned all the keys and Click Once apps broke. No matter what we did we couldn't remove the old keys and reinstall them.
After building a new build server up from scratch and manually installing the PFX keys on the new server, everything worked again.
So for some reason, cloning servers does not clone pfx keys properly.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I add a new username and password to a database list in Python?
I am new to Python and I have made this code below. It's just a simple login code that allows you to register or login.
Now I am able to login. As you can see I put the usernames and passwords in the variable database.
In the function register() I am trying to add the newusername and newpassword to the database list in the form of (username, password) so the login() function sees it.
import time
import sys
import getpass
database = [
("Test1", "123"),
("Test2", "000")
]
def login():
time.sleep(1)
print("Welcome. Please login.")
while True:
time.sleep(1)
username = input("Username: ")
password = getpass.getpass("Password: ")
time.sleep(1)
if (username, password) in database:
print("Welcome, " + username)
main()
else:
print("User not found. Try again.")
def logout():
time.sleep(1)
print("Logout?")
lgout = input(">>")
if lgout == ("yes") or lgout == ("Yes") or lgout == ("YES"):
time.sleep(1)
print("Logout successful")
main2()
elif lgout == ("no") or lgout == ("No") or lgout == ("NO"):
print("Logout unsuccessful")
main()
else:
print("Command not valid")
def main():
time.sleep(1)
print("Current commands: Logout")
while True:
command = input(">>")
if command == ("Logout"):
logout()
else:
print("Command not valid")
def main2():
time.sleep(1)
print("Hello, would you like to login, register or exit?")
while True:
command2 = input(">>")
if command2 == ("Login") or command2 == ("login") or command2 == ("LOGIN"):
login()
elif command2 == ("Register") or command2 == ("register") or command2 == ("REGISTER"):
register()
elif command2 == ("Exit") or command2 == ("exit") or command2 == ("EXIT"):
sys.exit()
else:
print("Command not valid")
def register():
print("Register your information below")
newusername = input("Username: ")
newpassword = getpass.getpass("Password: ")
print("Success! Please login!")
login()
main2()
Sadly database["newusername"] = newpassword does not work since it's not a dictionary.
A:
The "database" you have here is a list of tuples.
To append something to the end of a list, use .append(). To construct a tuple, use parentheses containing values separated by commas. Putting those two together:
database.append( (newusername, newpassword) )
| {
"pile_set_name": "StackExchange"
} |
Q:
Java ME in Intellij CE
This question has been asked a couple of years ago, but it didn't get answered.
I added the Java ME plugin from the Ultimate Edition as described here.
I created a simple Hello World program to test it. I set the ME SDK 3.4 as the project sdk.
I also added the midlet at Project Structure > Modules > Mobile Module Setting > Defined Midlets.
The code compiles okay, but when I try to run it I get the following error:
Installing suite from: file:///C:/Users/Stan/.IdeaIC13/system/caches/temp2565880090933730950.jad
Either the configuration or profile is not supported
What am i missing?
A:
I have had a similar issue with trying to get JAVA ME to work in Netbeans. I am unfamiliar with IntelliJ however the error you have is generally caused by not adding the Main Midlet to your configuration in your IDE.
Right click your project file and see if you can find MIDlet settings, then specify the Main Midlet and you should be good to go!
Fenix
| {
"pile_set_name": "StackExchange"
} |
Q:
Bash/Awk script for appending columns to single file based on searching multiple outside files
I am trying to write a script that will take two files as input:
1) An annotated, tab-delimited file ("inFile") and
2) a file of variable length containing other annotated, tab-delimited files (identical formatting) to search with set_ids for each...
file1 set1
file2 set2
file3 set3
I want to output inFile, but with columns appended indicating whether each line of file_A is found in each of the sets to be searched.
This is my code so far
#!/bin/bash
inFile=$1
inSets=$2
set_filter () {
set_name=$3
awk -F"\t" ' BEGIN {OFS="\t"};
{
FNR == NR
{
idx=($1"."$2"."$3)
keys[$idx]=$set_name
next
}
{
idx=($1"."$2"."$3)
print $0, keys[$idx]
}
} ' $2 $1
}
IFS=$'\n'
for line in $(cat $inSets); do
set_file=$(echo $line | cut -f 1)
set_id=$(echo $line | cut -f 2)
??? set_filter $inFile $set_file $set_id
done
My basic idea is to define a function that will perform the lookup for a single file and use that in a loop over all of the files to be searched, adding a column with each iteration. I'm having trouble with the loop, however, and was hoping somebody could point me in the right direction. Thanks!
EDIT
The annotated files look like
# inFile:
day start stop
1 100 102
1 300 350
2 100 200
3 200 400
So I'm looking for instances (rows) where the same day.start.stop appears in one of the sets being searched. If set1 is:
day start stop
1 100 102
1 700 750
2 800 900
3 900 950
and set 2 is:
day start stop
3 200 400
1 100 102
2 800 880
1 300 350
Then the output should look like:
day start stop
1 100 102 set1 set2
1 300 350 set2
2 100 200
3 200 400 set2
A:
Here is one way using awk:
awk '
FILENAME != "infile" {
line[FILENAME,$0] = FILENAME
next
}
FNR > 1 {
printf "%s", $0
for (x in line) {
split (x, t, SUBSEP)
if (t[2] == $0) {
sep = FS
printf "%s%s", sep, line[x]
}
}
print "";
next
}1' set1 set2 infile
day start stop
1 100 102 set2 set1
1 300 350 set2
2 100 200
3 200 400 set2
You can keep adding sets just ensure your infile is at the very end.
| {
"pile_set_name": "StackExchange"
} |
Q:
Supremum of an integral in distributions?
I am reading a book on distributions and they are trying to show that $u = \sum_{n=-\infty}^{\infty} a_n e^{inx}$ converges to a distribution. I understand most of the argument the book is showing but at some point when analyzing the behavior of each of the terms of this integral, they obtain the integral $\int_{-\infty}^{\infty} e^{ikx}\partial^{n+2}\phi(x)dx$ and when taking the absolute value of this, they claim that $ |\int_{-\infty}^{\infty} e^{ikx}\partial^{n+2}\phi(x)dx|\leq \sup|\partial^{n+2}\phi(x)|$, how can argue that this is true? I just don't see how the integral is bounded by the supremum of the partial derivative. Any guide, help or references to understand this is highly appreciated. Thanks!
A:
If $\phi \in C_c^\infty(\mathbb R)$ then there is $R>0$ such that
$$
\left| \int_{-\infty}^{\infty} e^{ikx} \partial^{n+2}\phi(x) \, dx \right|
=\left| \int_{-R}^{R} e^{ikx} \partial^{n+2}\phi(x) \, dx \right| \\
\leq \int_{-R}^{R} \left| e^{ikx} \partial^{n+2}\phi(x) \right| \, dx
= \int_{-R}^{R} \left| \partial^{n+2}\phi(x) \right| \, dx \\
\leq \int_{-R}^{R} \sup \left| \partial^{n+2}\phi(x) \right| \, dx
= \int_{-R}^{R} \sup \left| \partial^{n+2}\phi(x) \right| \, dx \\
= 2R \sup \left| \partial^{n+2}\phi(x) \right|
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Floating Strike Lookback Delta Risk
I'm running through some delta hedging simulations of floating strike lookback call options (that is, I'm short the options) during a volatile (downside) period for the underlying and some very odd things have resulted.
First of all, these options have no Gamma, at least not by the standard understanding of gamma being
$$\frac{\partial^2 C}{\partial S^2}$$
I've obtained Gamma values both by a finite difference approximation and by partially differentiating the analytical solution (messy!), and both come to 0. However, the delta values are very volatile, and the hedge is getting crushed. So, a few thoughts I had from drawing on analogies from vanilla calls.
1) If call deltas are known to underestimate the price increase in up moves and overestimate the loss in down moves, then being short delta in a down market should be good.
2) Again, there is no Gamma, at least by the "traditional" measure, or whatever you want to call it. However, in a volatile market, being short gamma (by being short either a call or put) is bad.
3) For vanillas, we know that Gamma is high for at-the-money options.
Now, this is where things get really weird in my head. Given that, as mentioned, I'm hedging short calls in a down market, the structure of the floating strike lookback option means that basically the strike is getting continually reset to the current value of the underlying. That is, the options are basically always at-the-money during this period. So, I have options with a volatile delta that are at-the-money. So in effect, the hedge is suffering for the same reason that a short call hedge might suffer by being short Gamma, yet I'm not short Gamma...!?
Can anyone clarify this for me, and perhaps lead me to some literature about hedging floating lookback options? It seems to be unfortunately sparse.
Thank you.
A:
The floating strike lookback call options has zero gamma only on the day it is issued (and only assuming an homogeneous model for the underlying). Afterwards it has non zero gamma.
The payoff on maturity $T$ is:
$$
\text{payoff} = S_T - \min \{S_u | u \in [0, T]\}
$$
Now assume your model for the underlying is homogeneous with degree 1, that is when viewed from $t$, $S_u$ for $u \geq t$ is proportional to $S_t$. This is of course the case when the model is a geometric Brownian motion as in Black & Scholes.
On $t=0$,
$$
E_0[\text{payoff}] = E_0[S_T] - E_0[\min \{S_u | u \in [0, T]\}] = S_0 E_0[S_T/S_0] - S_0 E_0[\min \{S_u/S_0 | u \in [0, T]\}]
$$
Since $S_T/S_0$ and $S_u/S_0$ do not depend on $S_0$, $E_0[\text{payoff}]$ is linear in $S_0$ and the option has zero gamma.
On $t>0$,
$$
E_t[\text{payoff}] = E_t[S_T] - E_t[\min \{S_u | u \in [0, T]\}] =
E_t[S_T]- E_t[\min\{m_t, \min \{S_u | u \in [t, T]\}\}]
$$
where the running minimum $m_t = \min\{S_u | u \in [0, t]\}$ is already known. Now
$$
E_t[\text{payoff}] = S_t E_t[S_T/S_t] - S_t E_t[\min\{m_t/S_t, \min \{S_u/S_t | u \in [t, T]\}\}]
$$
As you can see the second term on the RHS is no longer proportional to $S_t$ because $m_t/S_t$ depends on $S_t$. Therefore $E_t[\text{payoff}]$ is no longer linear in $S_t$ and the option has non zero gamma.
In practical terms that means that you should view the option price as a function of both $S_t$ and $m_t$, that is $C(S, m, t)$. When you compute the gamma you compute $\frac{\partial^2 C}{\partial S^2}(S, m, t)$. When you approximate gamma using finite differences you compute
$$
(C(S+\epsilon, m, t) + C(S-\epsilon, m, t) - 2 C(S, m, t))/\epsilon^2
$$
that is you move $S$ by $\pm \epsilon$ but you do not change $m$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Outlook 2007: Gmail and POP3
I am using Microsoft Outlook 2007 for a number of my email accounts. I have account A set up to come into my main inbox. However, when I want to setup my Gmail account to come into a separate folder, but it comes into my main inbox, thus mixing mail from Account A with the Gmail account. How do I get Gmail to download messages into its own folder, without a message rule? If there is no other way to do it other than a rule, say so...
When I go to account settings and try to give the Gmail account its own Data file and deliver all Gmail mail there, it keeps reverting back to my Account A data file...Why is this? How can I fix it?
Thanks!
OS is Windows 7.
A:
I'd suggest using the IMAP protocol instead of POP3 for your gmail account. If you do it this way you'll get folders for each gmail folder (or filter) in your account created automatically.
Google's IMAP instructions
| {
"pile_set_name": "StackExchange"
} |
Q:
Redeem / Activate Explorer's pack Elder scrolls online
Does anyone know how to activate the Explorer's pack (for the vanity pet mainly) on Xbox one? I've redeemed the code and store says that I've purchased it, but can't, for the life of me manage to activate the content :(
update Read at online community site that items such as this are sent via in-game mail, yet going through to social->mail shows "no mail".
A:
Pets are no longer sent. You should receive your treasure maps later today or tomorrow by the mail system (might take a bit due to heavy load right after launch).
As for your vanity pet, open the game's main menu using the menu button, then look under "Collections". There's a sub menu for pets, which should include the preorder bonus.
Activate or deactivate it at any time.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot enable email/password authentication provider
I am enabling email/password sign in method in firebase menu.The code for creating a new user and also to login are given below:
$scope.chatRef = new Firebase("https://project-497516355415797631.firebaseio.com");
$scope.login = function(){
$scope.chatRef.authWithPassword({
email : "[email protected]",
password : "123456"
}, function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
}
$scope.createUser = function(){
$scope.chatRef.createUser({
email : "[email protected]",
password : "correcthorsebatterystaple"
}, function(error, userData) {
if (error) {
console.log("Error creating user:", error);
} else {
console.log("Successfully created user account with uid:", userData.uid);
}
});
}
Still the error Error: The specified authentication provider is not enabled for this Firebase. is showing.What i am doing wrong?Thank you for your time.
A:
You are using the old SDK for your project. the "new Firebase("etc...")" is for the Firebase Legacy Version not the Firebase 3.0 version you should use this documentation
https://firebase.google.com/docs/web/setup
| {
"pile_set_name": "StackExchange"
} |
Q:
Highcharts - is it support draw scatter line chart?
I want to use Highcharts to draw a scatter line chart.
following image is an example, but it has same color.
data source format:
[
{"ShakeDate":"\/Date(1301068800000)\/","Magnitude":3.3},
{"ShakeDate":"\/Date(1298390400000)\/","Magnitude":4.2,},
{"ShakeDate":"\/Date(1298390400000)\/","Magnitude":5.2,},
]
I cannot find a right chart type for this kind of chart.
Anyone can give me some advices?
Thanks.
update:
HighStock demo
bug: cannot limit max date to current date
A:
Just use the pointWidth option on plotOptions for your series and set it to 1 or 2.
See the fiddle:
Example
EDIT: with Highstocks, same thing, use pointWidth:
Highstock example
| {
"pile_set_name": "StackExchange"
} |
Q:
R is very slow reading in .jsonl files
I need to read .jsonl files in to R, and it's going very slowly. For a file that's 67,000 lines, it took over 10 minutes to load. Here's my code:
library(dplyr)
library(tidyr)
library(rjson)
f<-data.frame(Reduce(rbind, lapply(readLines("filename.jsonl"),fromJSON)))
f2<-f%>%
unnest(cols = names(f))
Here's a sample of the .jsonl file
{"UID": "a1", "str1": "Who should win?", "str2": "Who should we win?", "length1": 3, "length2": 4, "prob1": -110.5, "prob2": -108.7}
{"UID": "a2", "str1": "What had she walked through?", "str2": "What had it walked through?", "length1": 5, "length2": 5, "prob1": -154.6, "prob2": -154.8}
So my questions are:
(1) Why is this taking so long to run, and (2) How do I fix it?
A:
I think the most efficient way to read in json lines files is to use the stream_in() function from the jsonlite package. stream_in() requires a connection as input, but you can just use the following function to read in a normal text file:
read_json_lines <- function(file){
con <- file(file, open = "r")
on.exit(close(con))
jsonlite::stream_in(con, verbose = FALSE)
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get git not to do any line ending conversions except for specific file types
I would like git not to do any line ending conversions except for specific files (say .c and .h). I would like to do it through .gitattributes so I can override any environment on users' machines. This is primarily targeted at Windows clients.
I want something like this:
* -text
*.c eol=lf
*.h eol=lf
But git is just ignoring everything after the first line (it's performing no line end manipulation at all).
Is there a way to do this?
A:
The * -text line is explicitly declaring that all files should be handled as binary. This will supersede your EOL settings, as they only apply to text files. You can bypass this by forcing text mode on your whitelisted extensions.
* -text
*.c text eol=lf
*.h text eol=lf
GitHub has a good article on this, for more detail
https://help.github.com/articles/dealing-with-line-endings/
EDIT: re-read your post, and tailored the response to better match your requirements
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the exact position of the Large Magellanic Cloud?
I am not able to visualize the position of the LMC and have not found a satisfactory explanation...
Can someone please answer it this way?
Relative to a ray joining the Earth to the Galactic-Center(Milky Way's), please describe the position in the plane of the ray as- to the South/East/West or their combinations. And will the galaxy be below/above the plane of the ray?
Note: Please consider the direction of the ray(Earth->Center) as the axis of a compass that points towards the north.
E.g://Answer format that i was hoping for:
To the South-West of the Segment, and below its plane.
A:
First of all: your coordinate system (as I understand it) is not "well defined". You only provide a line (Earth --> Milky way centre) and define that as the North-South axis. You don't give a reference for the east-west axis or the up-down axis. So, I'll assume that the East-West axis lies along the plane of the Milky way and up is where the Boötes Dwarf system is. This way, our coordinate system is equal to this image from the LMC Wikipedia site.
The problem with this picture is that the position of the Earth is only implicitly given. It is "behind" the center of the Milky Way. So from that position, the LMC is almost to our right (east) and a bit below the plane of the Milky way; about 30 to 40 degrees down.
This is also nicely validated by this image, acquired here (note that the grid is in 30 degree angles).
So, finally we can answer your question in the way you wanted: in the north-east to east segment, and below its plane.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get the icon of an application on mac? Java
I am trying to get the image of a file on mac, But i cant find any answers
There is some code that works on windows.
String s = "c:/windows/regedit.exe";
File file = new File(s);
sun.awt.shell.ShellFolder sf =
sun.awt.shell.ShellFolder.getShellFolder(file);
Icon icon = new ImageIcon(sf.getIcon(true));
A:
There's no clear-cut answer for this. You'll have to do some investigation yourself. If you have an Application in Finder, right-click and choose 'Show package contents'. In the Contents folder, search for the Info.plist file. You'll find an entry containing CFBundleIconFile like this (I took TextEdit as an example):
<key>CFBundleIconFile</key>
<string>Edit.icns</string>
Go inside the Resources folder, and there you will find the .icns file. You can find information on how to do that in this question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting textarea newlines into and tags by JavaScript
I'm using a textarea in an html form and I'm trying to reformat its content into a valid html format by using <p> and <br/> tags.
I wrote this script and it seems to work but I wanted to make sure I'm not missing anything. So I'm asking for feedback. I'm aware that I'm not taking into consideration the possibility that the user might explicitly input html tags, but that's no problem because I'll be issuing the result in PHP anyway.
Thanks in advance.
An example to the output:
<p>Line 1<br/>Line 2</p><p>Line 4<br/><br/><br/>Line 7</p>
and the code:
function getHTML() {
var v = document.forms[0]['txtArea'].value;
v = v.replace(/\r?\n/gm, '<br/>');
v = v.replace(/(?!<br\/>)(.{5})<br\/><br\/>(?!<br\/>)/gi, '$1</p><p>');
if (v.indexOf("<p>") > v.indexOf("</p>")) v = "<p>" + v;
if (v.lastIndexOf("</p>") < v.lastIndexOf("<p>")) v += "</p>";
if (v.length > 1 && v.indexOf("<p>") == -1) v = "<p>" + v + "</p>";
alert(v);
}
Please note that this is a code meant to be part of a CMS and all I care to do by JavaScript is to rebuild the textarea result with those 2 tags. Kind of WYSIWYG issue...
A:
Here's what I came up with.
function encode4HTML(str) {
return str
.replace(/\r\n?/g,'\n')
// normalize newlines - I'm not sure how these
// are parsed in PC's. In Mac's they're \n's
.replace(/(^((?!\n)\s)+|((?!\n)\s)+$)/gm,'')
// trim each line
.replace(/(?!\n)\s+/g,' ')
// reduce multiple spaces to 2 (like in "a b")
.replace(/^\n+|\n+$/g,'')
// trim the whole string
.replace(/[<>&"']/g,function(a) {
// replace these signs with encoded versions
switch (a) {
case '<' : return '<';
case '>' : return '>';
case '&' : return '&';
case '"' : return '"';
case '\'' : return ''';
}
})
.replace(/\n{2,}/g,'</p><p>')
// replace 2 or more consecutive empty lines with these
.replace(/\n/g,'<br />')
// replace single newline symbols with the <br /> entity
.replace(/^(.+?)$/,'<p>$1</p>');
// wrap all the string into <p> tags
// if there's at least 1 non-empty character
}
All you need to do is call this function with the value of the textarea.
var ta = document.getElementsByTagName('textarea')[0];
console.log(encode4HTML(ta.value));
| {
"pile_set_name": "StackExchange"
} |
Q:
Variable in variable batch
Alright, I need help here. I have done this before where you have variable1 (let's say it's eat1=apple), variable2 (this is eat2=orange), and variable3 (appaleorange=apple and orange). I need it to do this:
echo Apple:%eat1%
echo Orange:%eat2%
echo Apple & Orange:%eat1%%eat2%
Now, you can see my problem. That above script wouldn't show the word and, only appleorange. That isn't my script and the reason I need this is because I have multiple variables with numbers in them. I have done this before and I forgot how... I know you can do a call and then multiple %'s.
In this case I want fterm variable to be fterm (not sure how to have it in there and not be a variable) and stermnum as a number that will be changed often on other parts of the script.
My code:
set stermnum=1
call set exsternum=%%fterm%%stermnum%%%
echo Selected term:%stermnum% ^(%exsternum%^)
Does anyone know what to do?
Thanks and sorry it was long :P
~Edit:I found it out... If it helps anyone I did:
call set exsternum=%%fterm%stermnum%%
Sorry for posting this even though I figured it out so fast
A:
The OP appended a solution to the question, but it does not relate to the original question scenario, and it still has a bug.
Here is the OP's solution in terms of the original scenario:
set "eat1=apple"
set "eat2=orange"
set "appleorange=apple and orange"
call echo %%%eat1%%eat2%%%
For the actual code, I believe the OP wants to access an array of variables named fterm1, fterm2, fterm3, etc. And the number suffix is in a variable named stermnum.
call set exsternum=%%fterm%stermnum%%%
If fterm is itself a variable containing the base name of the array, then the solution becomes:
call set exsternum=%%%fterm%%stermnum%%%
But CALL is inefficient - Probably not noticeable with a single CALL, but it becomes painfully slow if executed thousands of times in a loop.
There is a much faster solution using delayed expansion. Delayed expansion must be enabled prior to being used.
Original scenario:
setlocal enableDelayedExpansion
set "eat1=apple"
set "eat2=orange"
set "appleorange=apple and orange"
echo !%eat1%%eat2%!
Actual code, interpretation 1:
setlocal enableDelayedExpansion
REM additonal code ...
set exsternum=!fterm%stermnum%!
Actual code, interpretation 2:
setlocal enableDelayedExpansion
REM additonal code ...
set exsternum=!%fterm%%stermnum%!
| {
"pile_set_name": "StackExchange"
} |
Q:
Android - How can I find out how many unread email the user has?
I'm writing a program that should display the amount of unread sms, mms, phone calls and emails. It was quite easy to find how to query for sms and phone calls (I used the search on this page) but I have not been able to find out how to query for emails.
Is there anyway to find out how many unread emails the user got in their phone?
A:
I'm the author of Gmail Unread Count. Check out Gmail.java, it's what I use. There are a couple of ways to do it. I read the unread count directly from the label. You should be able to figure out how to use it by reading the source.
Getting the unread count from Email is afaik not possible so you'll have to do polling there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert boolean to integer
I want to store in a MySql tinyint(1)field values that i have already converted from boolean with php's intval().
Example:
$data = true;
$foo = intval($data);
if (is_numeric($foo)){
print_r($foo);
}
The problem is that even if the $data is true and the $foo is numeric, intval always returns 0.
Update:
I have this jQuery code in order to take true/false if an html checkbox is checked.
var foo = $('#' + form + ' ' + '[name = "foo"]').is(':checked');
then i'm sending the variable foo to my controller: (The jQuery code works correctly)
$foo = Input::has('foo') ? Input::get('foo'): false;
$newFoo = New Foo();
$newFoo->foo=$foo;
Finally in my class:
public $foo;
print_r(intval($this->foo));
A:
Because your $data is a string not boolean. You can cast it first and should work
| {
"pile_set_name": "StackExchange"
} |
Q:
Linux courses for a beginner
I work for a company that would like for me to acquire Linux skill. I do not know much about Linux.
I have tried to make a list of things I'd like to learn:
Installation and package management
GNU and Unix commands, devices, file systems and standard file system hierarchies
Command shells, scripting and data management
User interfaces and desktops
Administrative tasks and activities
Basic system services
How networking works
General security
Furthermore I have not tried online courses before and do not know which course to pick as I find a lot of different ones when I search online.
Does anyone have any experience with this or can recommend an online course to take? I do not mind paying for the courses.
A:
As far as full online courses go (video lectures, quizzes, group discussions, etc.), the big MOOCs all have some Linux content, e.g.:
LinuxFoundationX Courses (Linux Courses on EdX)
Udacity: Linux Command-Line Basics
Coursera: Linux Server Management and Security
There are also some technology focused and Linux-specific training sites:
Linux Academy
PluralSight
CBT Nuggets
Cybrary
Then there are the video-tutorial sites, e.g.:
Lynda
Udemy
Regarding what skills to learn, you might want to look at a Linux certification program. I've done a little bit of research into this, and for generic (i.e. not vendor-specific) Linux certification it looks like there are basically three organizations to consider:
Linux Professional Institute
Linux Foundation
CompTIA
And for entry-level Linux systems administration, they provide the following certifications:
LPIC-1: System Administrator
Linux Foundation Certified System Administrator (LFCS)
CompTIA Linux+ Powered by LPI
Note that CompTIA and LPI are working together and that their certifications overlap somewhat, e.g. see the following post:
difference between CompTIA Linux+ LX0-101 and LPIC-1 Exam 101 exam
LPI also offers a very introductory certification for absolute beginners:
LPI Linux Essentials
Moreover, CompTIA and the Linux Foundation offer training and exam preparation, some of which is online:
Linux Foundation Courses
CompTIA Training
CompTIA CertMaster
You might also find the following (older) post useful:
Online course that covers Unix/Linux Systems programming
| {
"pile_set_name": "StackExchange"
} |
Q:
Using PHP traits to simulate multiple inheritance
For this question I want to present my current design and my idea of using a trait. I would like to know whether my understanding of traits is correct and whether my problem can be solved with another design not involving them.
My current class hierarchy in my framework looks like this:
interface IPage { /* ... */ }
interface IForm extends IPage { /* ... */ }
abstract class AbstractPage implements IPage { /* ... */ }
abstract class AbstractForm extends AbstractPage implements IForm { /* ... */ }
In my applications that are based on the framework I used to have the following:
abstract class AbstractBasePage extends AbstractPage { /* ... */ }
Thus I could add some more stuff to all pages for this particular application that is not common to the framework or other applications. This worked well until I implemented the separation into pages and forms as indicated in the first snippet. Now I ended up with something like this:
abstract class AbstractBasePage extends AbstractPage { /* ... */ }
abstract class AbstractBaseForm extends AbstractForm { /* ... */ }
Let's assume in one application there should be a variable for each page and form that indicates whether something special is displayed in the templates. I would need to introduce the same variable in AbstractBasePage and in AbstractBaseForm. Doing so would force me to keep both snippets in sync which isn't good at all.
I was thinking about creating a trait that exposes variables and functions to both classes which they can in turn refer to in the corresponding functions. Using such a trait would reduce the code duplication at least since I could introduce one publicly accessible method that gets called by both classes but other than that there is a decent abstraction, isn't it?
Is this what traits are supposed to help with? Is there a more suitable approach?
A:
In this particular case I ended up introducing an interface (with functions used by the framework) as a contract that gets extended by IPage. Furthermore I had the particular implementation that is identical for pages and forms in a trait which then in turn got used in the framework classes AbstractPage and AbstractForm.
The mentioned implementation was inside the framework itself to have a concise design which then in turn is used to do that in my applications as well. For the applications I introduced a trait which holds the variables and functions that are identical in both pages and forms once again which then gets used in the AbstractBasePage and AbstractBaseForm classes.
For this scenario I needed a what is essentially a language assisted copy and paste feature since I wanted to add something that is not as easily to be done using inheritance but something that can be introduced to classes that are part of different class hierarchies. Therefore I decided to use traits.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I place a lien on a mobile home i am selling
I'm in the process of selling a trailer for $13,000. The purchaser wants to make a down payment 5 thousand dollars and pay the balance over period of time Including interest. How do I place a lien on the property?
A:
Check how a mobile home is classified where you live. In some states (assuming you live in the US) it's classified like an RV / vehicle. In most states, it depends on the mobile home. I am only aware of how to do this for a vehicle classification, which may / may not be the same in your case. You need to find that out first.
Keep in mind you could just keep the title until the payments are complete. Carrying a loan with the title transferred to the buyer and a lien can be a bit complex. But it is possible. If you really want to do it that way, call your local DMV and ask about the entire process because it varies by state. Tell them you want to transfer the title into the buyer's name with a lien for the loan you are carrying. There are two main action items here:
The promissory note needs to be written and should name both parties, have both signatures, 2 copies and contain the starting/ending date, the payment amounts (including principle and interest) when the first payment is due and when each payment is due after that. It should contain the late penalties if there are to be any, a repossession period if payments stop (check what the legally allowed period is for your state) and a note about reporting to the crediting agencies with the buyer's authorization allowing you to do that. There may be a specific form for your state for this piece, though of course it's not required if you don't want to go there. You can also include other things like your right to sell the note to collections etc. Search for standard free forms on the internet, or consider buying one.
The title needs to be transferred to their name at your local DMV and the lien needs to be recorded. It depends on the state you live in. But, most state DMVs allow this with both parties present. There may be a fee and an additional form you have to fill out for a "security interest." This may have to be filed with the DMV who will likely file it with the treasury, or you might have to file it with the treasury yourself.
I would also pull the buyers credit first. Ask them to get you their credit score. They can request a free one from some place like: FreeCreditReport.com. You'll want to check if they have a lot of outstanding debt / late payments etc. You may not want to do this at all depending on what you find, and their credit report may effect how much interest you want to charge in order to make it worth the risk.
| {
"pile_set_name": "StackExchange"
} |
Q:
Strange result on the nilradical $N(R)$ of a ring
I am studying about the nilradical $N(R)$ of a unital ring $R$. In my notes, the nilradical of a $R$ is defined as the sum of all nilpotent ideals of $R$.
It says, that $N(R)$ is always a nil ideal, but not a nilpotent.
But there is a lemma that it says that the sum of nilpotent ideals is also a nilpotent ideal. Thus, according to this, $N(R)$ should always be nilpotent ideal.
What do I miss?
A:
The sum of two (or finitely many) nilpotent ideals is nilpotent. However, infinite sums of nilpotent ideals are not necessarily nilpotent.
Consider, however, the ring
$$
\Bbb R[x_1,x_2,x_3,\ldots]/(x_1,x_2^2,x_3^3,\ldots)
$$
Here the nilradical $(x_1,x_2,x_3,\ldots)$ is indeed nil but not nilpotent.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python - nohup.out don't show print statement
Im new to python and web development, I have a basic issue I believe.
I'm running my server with pyramid, and I use nohup.out to write output to a file.
nohup ../bin/pserve development.ini
When I do tail -f nohup.out
I can see all the output coming from the logging.info() calls in my code.
but I don't see all the output from the print() calls.
what is the reason for that, and how can I set it that I will see the print() in the nohup file?
A:
You can use stdbuf -oL to flush the print statements. Command will look like
nohup stdbuf -oL python python_script.py > nohup.out &
A:
You can use
nohup python -u python_script.py &
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get value of all inputs not type hidden
I want to clear value of all inputs but except input type hidden which contains some value I want to submit on server.
What is the best way to select all form fields in a form but ignore hidden fields in the selection?
A:
You can try selecting like this:
$(":input:not([type=hidden])")
You can refer more here
| {
"pile_set_name": "StackExchange"
} |
Q:
HTML entities in markdown block code
I have tried to use HTML entities in code but it's not rendering properly when compiling it using a markdown processor. For example, Θ renders properly outside codes, but when within codes, it appears as <p><code>&Theta;</code></p> after compilation. Is it possible to use HTML entities in markdown code and compile them so they can be rendered properly ?
A:
You can't, which is an intentional design decision. Otherwise, how would you be able to use a code block to display HTML source code? As the rules state:
Within a code block, ampersands (&) and angle brackets (< and >)
are automatically converted into HTML entities. This makes it very
easy to include example HTML source code using Markdown -- just paste
it and indent it, and Markdown will handle the hassle of encoding the
ampersands and angle brackets. For example, this:
<div class="footer">
© 2004 Foo Corporation
</div>
will turn into:
<pre><code><div class="footer">
&copy; 2004 Foo Corporation
</div>
</code></pre>
A:
If it is - for some reason - important to include HTML entities in a code block, you always have the option to use HTML inside a Markdown document (see Inline HTML in the rules).
That is, instead of using indentation (or code fencing in GitHub Flavored Markdown/GitLab Flavored Markdown with three backticks ```), enclose the code block with appropriate HTML elements yourself:
<pre><code>Greek letters Θ Π and α
in a code block
</code></pre>
will turn into:
Greek letters Θ Π and α
in a code block
Note that you'll have to start your code at the same line as the opening <pre><code> tags or otherwise will end up having an empty line at the beginning of your code block.
It's not as nice to read in code and you have to decide whether the rendered or the raw view is more important in your case.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why a Name Function Expression not available outside function body
The Named Function Expression which is defined as
var ninja = function myNinja();
has a behavior which is not able to get through my head.
Have a look at the below code
var ninja = function myNinja() {
console.log(typeof myNinja) //prints 'function'
};
console.log(typeof myNinja) //prints 'undefined'
Now, myNinja is a named function and as far as I know javascript allow the named function to go beyond the scope of its own function.
This is creating confusion in my head.
A:
Now, myNinja is a named function and as far as I know javascript allow the named function to go beyond the scope of its own function.
Only in a function declaration. It's specifically not the case for a named function expression. It's just how this is defined in the specification.
All the gory details are in the spec, the most relevant bit is:
NOTE The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.
So if you changed your code to:
function myNinja() {
console.log(typeof myNinja) //prints 'function'
}
var ninja = myNinja;
console.log(typeof myNinja) //prints 'function' (now we're using a declaration)
...since that uses a function declaration, myNinja is added to the scope in which it's defined. (The declaration is also hoisted, like all declarations; it's not processed as part of the step-by-step code the way expressions are.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Get parent's property from child component in angular form
I'm using Angular 6 with reactive forms, I need to switch form between editable and custom 'readonly' view. There's multiple custom input components in project, so it seems that the easiest way is to use [readOnly] binding on custom-form element. The question is:
How can I get parent's readOnly value inside custom-input component without direct bindings to each of them?
For example:
Template with form
<custom-form formGroup="formGroup" [readOnly]="!(canEdit$ | async)">
<custom-input formControlName="field1"></custom-input>
<custom-input formControlName="field2"></custom-input>
<custom-select formControlName="field3"></custom-select>
...
</custom-form>
Custom input template
// Show input if form readOnly is false
<input *ngIf="!formIsReadOnly"...>
// Show some other representation if not
<span *ngIf="formIsReadOnly">...</span>
A:
If you don't want to add a readonly input parameter to your custom controls then you will need a service or an opaque token that each of the controls gets from its constructor to determine if the control will be readonly or not.
For an opaque token you will need to provide a boolean value at the root of the app and then anytime you want to change it you have to re-provide.
Service (Demo)
If you want to be able to toggle the readonly value on an off you will need to use a service.
readonly.service.ts
@Injectable()
export class ReadonlyService {
public readonly = false;
}
readonly.component.ts
@Component({
selector: 'app-readonly',
templateUrl: './readonly.component.html',
providers: [ReadonlyService],
})
export class ReadonlyComponent implements OnInit {
constructor(public readonlyService: ReadonlyService) { }
ngOnInit() {
this.readonlyService.readonly = true;
}
}
customInput.component.ts
@Input() public value: any;
constructor(public readonlyService: ReadonlyService) { }
customInput.component.html
<ng-container *ngIf="!readonlyService.readonly; else readonlyView">
<input placeholder="Enter a value" [(ngModel)]="value">
</ng-container>
<ng-template #readonlyView>
Your readonly value is: {{value}}
</ng-template>
| {
"pile_set_name": "StackExchange"
} |
Q:
How can set text for Jtextfield from the array?
I have a problem when doing my project.
I connect my database and get database about the value of food. I put all of the value to the array (public static array). But I wondering that anyway can I set the text of the textfield by the value from the array?
Here is my declaring array:
public static String[] fp;
----------- main()
fp = new String[9];
try {
ResultSet rs = st.executeQuery(get_food_price);
int i =0;
while (rs.next()) {
System.out.println(rs.getString(1));
fp[i] = rs.getString(1);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
----------- private void initialize() {
food1_price.setText(fp[1]);
------------ It's not working with fp[1] (array) but It do work with normal string like "acb" or "asdsa"
A:
Can you try this?
MySQLConnection db = new MySQLConnection();
Connection connect = db.getmysql_connection();
String query="SELECT * FROM "; //Your query
Statement stmt = (Statement) connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
int i=0;
while (rs.next()) {
System.out.println(rs.getString(1));
fp[i] = rs.getString(1);
i++;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
bootstrap class path not set in conjunction with -source 1.7 - netbeans
This is when i tried to build my Java code using Netbeans, i have no idea to solve it:
warning: [options] bootstrap class path not set in conjunction with
-source 1.7 Note: Some input files use unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. 1 warning
A:
You're telling the Java 8 (or later) compiler to treat your sources as Java 7 code.
But you're not setting the bootclasspath, so the compiler can't check that your code, supposed to be compatible with Java 7, doesn't use classes and methods that exist in Java 8, but don't exist in Java 7. So your code has a big chance of not being compatible with Java 7, hence the warning.
If your goal is indeed to be compatible with Java 7, then
install and use a Java 7 JDK instead of the JDK you're using now (simplest option)
or set the bootclasspath as the message tells you.
If you don't want to be compatible with Java 7, then change your compiler settings to use the source level you actually want.
| {
"pile_set_name": "StackExchange"
} |
Q:
Diagnosing IIS Shutdowns
Symptoms:
I attach a debugger, I wait a little while, it automatically detaches
I watch the event log during normal operation - after a single request comes in, it waits a little bit, the shuts down
Disagnosing. I've followed the following steps for logging shutdowns in IIS:
http://weblogs.asp.net/scottgu/archive/2005/12/14/433194.aspx
http://blogs.msdn.com/tess/archive/2006/08/02/asp-net-case-study-lost-session-variables-and-appdomain-recycles.aspx
I know these are working because...
What I see in the Event Logs when I change the web.config:
The description for Event ID 0 from source ASP.NET 2.0.50727.0 cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
_shutdownMessage=IIS configuration change
HostingEnvironment initiated shutdown
CONFIG change
CONFIG change
HostingEnvironment caused shutdown
_shutdownStack= at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal()
at System.Web.Hosting.HostingEnvironment.InitiateShutdown()
at System.Web.Hosting.PipelineRuntime.StopProcessing()
the message resource is present but the message is not found in the string/message table
But it doesn't help because the mysetery error doesn't tell me anything. I see the same thing as from before I added this extra logging:
The description for Event ID 0 from source ASP.NET 2.0.50727.0 cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
_shutdownMessage=HostingEnvironment initiated shutdown
HostingEnvironment caused shutdown
_shutdownStack= at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal()
at System.Web.Hosting.HostingEnvironment.InitiateShutdown()
at System.Web.Hosting.PipelineRuntime.StopProcessing()
the message resource is present but the message is not found in the string/message table
Anyone have any ideas for more debugging?
A:
Well, it turns out that IIS somehow got set to recycle the pool every minute - certainly not the usual configuration. (I think it was a prank.) I'm leaving this up so anyone who googles that error message might find something that helps them.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find number of values Grouped by MySQL groupby query
Is there any solution to find number of values Grouped by MySQL groupby query. Following is my Query.
$groupBy = 'PropertyViewer.ip_address';
$this->paginate = array("group"=>array($groupBy),"order"=>array("PropertyViewer.id desc"));
I need to find how many values grouped in each case.
A:
I think all you need is the COUNT() aggregate function in your SELECT query:
SELECT COUNT( ip_address) as num_values
FROM PropertyViewer
GROUP BY PropertyViewer.ip_address
ORDER BY PropertyViewer.id desc
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I add references for examples?
I am writing a paper in Computer Science / Information Technology. At several points in the paper, I mention the existence of particular types of software products. For example:
Advanced web data extraction systems offer the possibility for the user to define and execute Web wrappers by means of interactive graphical users interfaces (GUI) (e.g. Denodo, Kapowtech, Lixto and Mozenda).
The examples I am referencing are commercial products. Some of them have some articles associated with them which I can cite. Should I add reference to these articles? If yes, how can I do that?
A:
Like any other external resources you mention in your paper, in my opinion, the sources for the examples should be listed as regular references. This can happen in various forms:
If there is a scientific paper that in some way presents the external resource, cite that paper.
If the resource is only presented on a website, cite that website like you would cite other web sources. This can take various forms, though you should be consistent within any one paper you write. The author, unless a single person, should probably be the name of the entity that published the resource. The title can either be the website title, or the name of the resource (e.g. software name).
This has various benefits:
All external works are collected in your references section.
If you refer to the same source several times (especially on several pages), you can use the usual mechanisms by placing cite references.
Readers will not get confused by different formats and places for finding external works you refer to.
In an afterthought, I would find it extremely hard to consistently distinguish "examples" from "normal references". By "normal reference", I imagine a paper that confirms a statement you make. Now, imagine a simple statement like
In past works, users have been provided with feature X.
for which you want to supply a paper that describes a commercial software that does provide feature X. Now, is this paper an "example" or a "normal reference" that serves to confirm your statement? Clearly, it can be seen as both ... which is why I generally advise against trying to distinguish between any such "categories" of cited works.
| {
"pile_set_name": "StackExchange"
} |
Q:
Savings strategy for grad students (minimal expenditures and minimal savings)
This is question has been somewhat asked elsewhere:
Savings account vs Roth 401k
Savings Account Rates vs. CD Rates vs IRA CD Rates
Can a Roth IRA be used as a savings account?
However, I wanted to re-formulate the question for a different demographic. I am currently a graduate student in a US university with a $22,000 a year stipend (August - May, summer months can pick up additional work at university or elsewhere). My monthly rent (all in) is $675 and my living expenses are about $150. After some startup expenses (furniture, moving, etc.) I am at a stable earning-saving pace.
My question is: What financial instruments should I prioritize to maximize the minimal savings I can accumulate over the next 4-5 years?
I have minimial student debt (less than $5000) and a Vanguard Roth IRA with $3500. My savings account, having just stabilized, is about $1000. I have no emergency fund.
I am able to save between $600-$800 a month so far. Should I be pouring all of that into the Roth? Or splitting it 50/25/25 (Roth, savings, emergency fund)?
Any insight would be greatly appreciated! Can post additional info if needed.
Updates from comments:
What are your goals?
To build up a savings strategy that makes sense for me. I am not inclined towards markets/finance, and often find myself accusing decent sums (1k-5k) yet doing little with it. Ideally I would like to exit this program debt free with some savings built up.
Do you have family or other resources to fall back on?
Yes, I am fortunate enough to have decent enough family resources should anything terrible happen.
How is the job market for your field of study?
Strong. I am in a quantitative social sciences field with background in statistical programming, database management, and project leadership.
What is the interest rate on your student debt?
3.6%
A:
So I would ask another question. After this degree what do you intend to do?
If you intend on going into industry, I would be saving the bulk of it in a online "high" interest savings account. This would be used for covering moving expenses, or expenses associated with starting the new job. In a pinch, if things go south with your education financing plan, they could also be used to cover those expenses.
Once you are settled in the new job/location I would use the bulk of the funds to kill the student loan. However, your income will probably rise so dramatically that you will eclipse any efforts you made until that date to pay off debt or invest.
No big deal if you wanted to throw a bit extra (like 50 per month) at each the loan and ROTH. In these kind of cases, I prefer a concentrated approach.
If you were going to continue your education, then I would mostly forget about the ROTH and the loan if the interest rate is differed. I would just save, save, save in that same high yield savings account. This way you have a buffer to help you to complete your education. If your interest rate is not differed, I would dedicate all my savings to paying off the loan, and then savings. With focus you will have no student loan in less than 10 months.
| {
"pile_set_name": "StackExchange"
} |
Q:
Package shared code in VSTS extension
I'm writing a VSTS extension with build/release tasks in it. Where can I put code that is used by more than one task within an extension? Can I put it anywhere in the extension file tree (eg. the Common folder below) and then just use that path - will those files be downloaded by every agent running any task from the extension?
The directory structure I currently have looks like this:
My Extension
|- MyBuildTask
| |- MyBuildTask.ps1
| |- task.json
|- MyReleaseTask
| |- MyReleaseTask.ps1
| |- task.json
|- Common
| |- MyModule.psm1
|-vss-extension.json
A:
When you queue builds, anent only downloads the single task files, it's not able to share file between tasks. You have to pack all files the task needs in the task directory.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to add url in window.history object?
So far I've seen only by URL hashChange envent, and I'm not interested in that (Because I use BlackBerry 5.0 native browser and it does not have this event support).
For example, Just open your browser first time, then type http://yourdomain.com/page1.html in address bar, then hit enter( or go).
It will open that page, now can we add page2.html in history? so that if user press browser back button, I can redirect him to page2.html?
A:
You can't. It's a read only object.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find the actual DbSet for CRUD actions dynamically
I have searched on this site and am having trouble getting the actual DbSet from my context. I am trying to retrieve each dbset dynamically based on tablename.
var dynamicdbset = GetDbSetByTableName(uploadTableName); //Dbset name is Mytables
private dynamic GetDbSetByTableName(string tableName)
{
MyEntities context = new MyEntities();
System.Reflection.PropertyInfo[] properties = typeof(ClearGUIEntities).GetProperties();
var prop = properties.FirstOrDefault(p => p.Name == tableName + "s");
using (var db = new MyEntities())
{
var dbset = prop?.GetValue(db);
return dbset;
}
}
The issue here is it is returning some generic dbset but I can't use linq nor can I do a simple operation like
dynamicdbset.Where(t = > t.Id == 123).Single();
I need to be able to get the dbset dynamically by tablename and also query the data the same way I would be able to do if I create it specifically like
var value = context.MyTables.FirstorDefault()
A:
The returned dynamic DbSet is actually just a wrapper around the real DbSet object, which you could simply cast to. The problem is, however, the type of the DbSet could not be inferred without using a generic method.
The following would work but it is probably least preferable:
private IEnumerable<T> GetDbSetByTableName<T>(string tableName)
{
System.Reflection.PropertyInfo[] properties = typeof(ClearGUIEntities).GetProperties();
var prop = properties.FirstOrDefault(p => p.Name == tableName + "s");
using (var db = new ClearGUIEntities())
{
var dbset = prop?.GetValue(db);
return new List<T>(dbset as IEnumerable<T>);
}
}
Now, to work around this, we have at least two options:
Create an interface (with all the base properties you need) that is implemented by all the DbSets. This way, we can cast the dynamic object without having to specify a type while converting.
Return an IEnumerable<dynamic> which can be cast on the fly.
Option 1
public interface IBaseProperties
{
int Id { get; set; }
string Name { get; set; }
}
public class MyTable : IBaseProperties
{
// Add these with either T4 templates or create partial class for each of these entities
public int Id { get; set; }
public string Name { get; set; }
}
private IEnumerable<IBaseProperties> GetDbSetByTableName(string tableName)
{
System.Reflection.PropertyInfo[] properties = typeof(ClearGUIEntities).GetProperties();
var prop = properties.FirstOrDefault(p => p.Name == tableName + "s");
using (var db = new ClearGUIEntities())
{
var dbset = prop?.GetValue(db);
return new List<IBaseProperties>(dbset as IEnumerable<IBaseProperties>);
}
}
// ...
// Using it
// ...
var dynamicdbset = GetDbSetByTableName("MyTable");
int id = dynamicdbset.FirstOrDefault().Id;
Option 2
private IEnumerable<dynamic> GetDbSetByTableName(string tableName)
{
System.Reflection.PropertyInfo[] properties = typeof(ClearGUIEntities).GetProperties();
var prop = properties.FirstOrDefault(p => p.Name == tableName + "s");
using (var db = new ClearGUIEntities())
{
var dbset = prop?.GetValue(db);
return new List<dynamic>(dbset as IEnumerable<dynamic>);
}
}
// ...
// At this point, you can basically access any property of this entity
// at the cost of type-safety
string id = dynamicdbset.FirstOrDefault().Id;
string name = dynamicdbset.FirstOrDefault().Name;
BTW, the casting to List<T> is necessary because you're using the object outside of the using block, at which point it would have been disposed.
new List<IBaseProperties>(dbset as IEnumerable<IBaseProperties>);
| {
"pile_set_name": "StackExchange"
} |
Q:
Keras Neural Network Training Set Data Error: Expected Varying Shape
Recently, I have attempted to create a stock market prediction program upon the basis of previously conducted work within the field, whereby a neural network, created via the Keras module in Python, is fed adjusted stock price information from Quandl, utilising the aforementioned information to train itself. I have completed this program via the utilisation of assistance from the following tutorial; however, I have modified the provided program, replacing the utilisation of the 'sklearn' linear module with a Keras Sequential model. The tutorial is listed below:
https://www.youtube.com/watch?v=EYnC4ACIt2g&t=1551s
I additionally derived the Keras Sequential model information from the official documentation for the Keras module:
https://keras.io
I have completed the aforementioned within the Google Colaboratory program, an interpreter and online IDE for Python within the form of a Jupyter Notebook. I utilised the following code:
import tensorflow as tf
import keras
import numpy as np
import quandl
from sklearn.model_selection import train_test_split
df = quandl.get("WIKI/FB")
df = df[['Adj. Close']]
forecast_out = 1
df['Prediction'] = df[['Adj. Close']].shift(-(forecast_out))
X = np.array(df.drop(['Prediction'], 1))
X = X[:-forecast_out]
y = np.array(df['Prediction'])
y = y[:-forecast_out]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
model = keras.models.Sequential()
model.add(keras.layers.Dense(units = 64, activation = 'relu'))
model.add(keras.layers.Dense(units = 10, activation = 'softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5, batch_size=32)
However, the Colaboratory compiler provided the following error message:
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:4432: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead.
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:3576: The name tf.log is deprecated. Please use tf.math.log instead.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-32-70cb958ae676> in <module>()
7 metrics=['accuracy'])
8
----> 9 model.fit(x_train, y_train, epochs=5, batch_size=32)
2 frames
/usr/local/lib/python3.6/dist-packages/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
139 ': expected ' + names[i] + ' to have shape ' +
140 str(shape) + ' but got array with shape ' +
--> 141 str(data_shape))
142 return data
143
ValueError: Error when checking target: expected dense_16 to have shape (10,) but got array with shape (1,)
Is there a valid explanation for this error and can it be resolved? If so, what is entailed? Is it necessary to alter the training data or the neural network? Thank you for your assistance.
A:
In a neural network, your last layer (the output layer) should match the shape of the target (the y). As I see it, you are trying to forecast stock prices (continuous target), so the shape should be (1,). Your final dense layer should be:
model.add(keras.layers.Dense(units = 1, activation = 'linear')
On top of that, you're not classifying, so your loss shouldn't be categorical_crossentropy. It should be mean_absolute_error, or the likes.
Lastly, it is good practice to explicitly declare the input_shape in your first layer. That makes things easier (for us to help too).
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the name of function that is called when you use '%' in Emacs Evil normal mode?
I'm looking to call this function programmatically, but can't figure out what function is actually called that moves point to matching bracket.
A:
The function is evil-jump-item.
You can easily find the answer yourself. When in evil normal node, just type C-h k %, and it will tell you what the function is and what it does. C-h k (which runs describe-key) will work in the same way for any key binding you want to know about.
| {
"pile_set_name": "StackExchange"
} |
Q:
Как правильно дампить процесс в JVM?
Вообщем имею запущенный main.jar файл, нужно сдампить его в файл, есть команда:
jmap -F -dump <file> <pid>
но она работает не корректно (выводит ошибку прикрепления).
Как правильно вызвать эту команду ?
A:
Многие тулы из jdk с флагом -F используют serviceability агента, без одной хитрой проперти он упадёт, если версии jvm (вплоть до версий билда) не будут совпадать. Имеется в виду версии jvm целевого процесса и которая запускает агента. Попробуйте без этого флага, в таком случае будет использован dynamic attach api
| {
"pile_set_name": "StackExchange"
} |
Q:
Automatically close application after custom time?
Is there a way to automatically close a certain application after custom time?
Update: i.e. stop the Audioplayer after a certain time.
A:
Install gnome-schedule from the Ubuntu Software Center, load the program from Applications > System Tools. Use it to add an entry for the time you want the program to be closed like so:
This will kill all instances of firefox at a certain date/time, you can also have reoccurring events that kill off certain programs at certain times, for instance to encourage kids to not browse the internet or for killing certain games.
It is possible to do this kind of thing from the commandline too, but you need to know how to use crontab -l and how to write cron lines.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why 404 error through PHP cURL GET, but works fine in browser?
StumbleUpon recently changed their framework and their API no longer works, so I'm trying to write a PHP script to access my Stumble history.
Embarrassingly enough, I'm stuck at the simple step of trying to GET the login page ;)
https://www.stumbleupon.com/login/ loads fine in my browser
But this PHP code displays a 404 page:
// Vars
$url = "https://www.stumbleupon.com/login/";
$user_agent = "Mozilla/5.0";
// Curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
$response = curl_exec($ch);
echo $response;
I've thought maybe they block certain user agents, so I've tried the same one my browser is using, but no luck. I've also tried running the script from different IPs to eliminate an IP ban issue. I'm really clueless on this one...very odd.
Any ideas?
A:
Try using https://www.stumbleupon.com/login.php instead. The URL you put returns a 404 for me to.
| {
"pile_set_name": "StackExchange"
} |
Q:
material-ui: modify component property with inline not working
I want to modify the 'toggle' component property, so that when it is 'on' the color is green. The default behaviour is the the 'toggle' 'thumbOnColor' is set to the 'palette' primary color (in my case 'redA700').
The docs suggest the following should work, but it doesn't:
<Toggle
defaultToggled={relay}
label={localization.get("user_bracelets_relay")}
ref="relayField"
onToggle={par(updateRelay, component)}
thumbStyle={{thumbOnColor:"green"}}/>
I have tried using just 'style= ...' inline, 'style' with a .css, specifiying 'toggle: ...' in my apps Theme (ie. where I define my modified 'palette'. Nothing seems to work, no matter what I do, the default behaviour remains. Ideally, I want the toggle 'grey' when not set, and 'green' when it is.
Is it in fact possible to change the theme of the 'toggle' material-ui component in my app?
A:
The easiest way to do this is to define your own theme, then you can override the thumb and track colors. For more details, read the theme documentation here. However, if you are feeling dangerous, you should be able to use the following snippet, but beware the track color would also need to be similarly changed -
thumbStyle={{backgroundColor:"green"}}
Also, you will need to provide different values for this based on the toggled state of the component.
Update
The older version of the documentation had a themed toggle, you may be able to find it if you dig deep enough in the documentation source at github.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using variable inside a for in loop, doesn't considered to be read by compiler...why is that?
I have an NSArray, and I am declaring that variable inside a function locally and used inside in for loop. But while I Analyze code it appears to be an error or an issue. The issue is Dead store - Values stored to 'elements' during initialisation is never read. But I do use that variable inside a for in loop...
Visual Description :
So the question is, Why compiler says that after creating NSArray I haven't read anywhere in my code?
P.S. Code runs as I intended, but I just want to know why is this issue showing up?
Thanks for any explanation given.
A:
You're allocating memory for elemnts and initialising it, and then two lines later you overwrite that variable having never used the allocated memory!
Just write this instead:
NSMutableArray *values = [[NSMutableArray alloc] init];
NSArray *elements = [[alarmLevelsDoc rootElement] elementsForName:@"AlarmLevel"];
...
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get an AppleScript application to automatically run at login?
The script I have helps with my computers ability to edit videos. I only use my computer for editing. The script just activates a program that I have made. I want to be able open my computer after it has been shut down and get the program to open/run automatically.
I have tried to use the System Preferences' "open at log in" feature, but that doesn't work. Is there any other way?
The script I have is an application and the code is:
set appPath1 to path to resource "Opening 5.app"
tell application "Finder"
open appPath1
end tell
When I double click the app, it opens up my program which changes the way FCPX renders, plays and saves videos.
A:
I use this ..
Open System Preferences.
Go to Users & Groups.
Choose your nickname on the right.
Choose Login items tab.
Press +
Check startup programs you want to add.
A:
You should be able to just add “Opening 5.app” to the System Preferences » Login Items.
But if that doesn’t work for some reason, this sounds like the perfect job for a launchd .plist. They can be tricky to write, but there are two apps which are very good for getting the hang of them. The first is Lingon and the second is LaunchControl. They both have demos, and I would recommend trying them both and seeing which one you prefer.
If you're keen to learn more about launchd, a good resource is http://www.launchd.info.
Here's an example of how you might handle launching that app at login:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.tjluoma.opening5</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/open</string>
<string>-a</string>
<string>Opening 5</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
Save that to ~/Library/LaunchAgents/com.tjluoma.opening5.plist (where ~ refers to your home directory).
When you reboot (or logout and then login), it should launch “Opening 5” at login.
A:
If the script you provided is the actual script, you can launch “Opening 5.app” directly from the login items instead of the script.
If your script does other things not shown in your question, you can still use the script but you’d have to save the script as an application instead of a plain script to use it with login items.
| {
"pile_set_name": "StackExchange"
} |
Q:
comment up vote removes comment flag
Possible Duplicate:
Allow flagging a comment after upvoting it
per Cancelling upvote on comment? when an (possible accidental) upvote is made, then the flag icon is removed. As it is really easy to click on the wrong™ one I think that it should be changed so that the flag icon isn't removed, or that we are able to down-vote comments as well...
A:
I think being able to retract up-votes like the linked question proposes is probably the most logical. Downvoting comments has itself been downvoted into the ground every time it's proposed, and being able to upvote and flag a comment doesn't make much sense
| {
"pile_set_name": "StackExchange"
} |
Q:
Vue Watch not triggering
Trying to use vue watch methods but it doesn't seem to trigger for some objects even with deep:true.
In my component, I recieve an array as a prop that are the fields to create
the following forms.
I can build the forms and dynamicly bind them to an object called crudModelCreate and everything works fine (i see in vue dev tools and even submiting the form works according to plan)
But I have a problem trying to watch the changes in that dynamic object.
<md-input v-for="(field, rowIndex) in fields" :key="field.id" v-model="crudModelCreate[field.name]" maxlength="250"></md-input>
...
data() {
return {
state: 1, // This gets changed somewhere in the middle and changes fine
crudModelCreate: {},
}
},
...
watch: {
'state': {
handler: function(val, oldVal) {
this.$emit("changedState", this.state);
// this works fine
},
},
'crudModelCreate': {
handler: function(val, oldVal) {
console.log("beep1")
this.$emit("updatedCreate", this.crudModelCreate);
// This doesn't work
},
deep: true,
immediate: true
},
}
A:
From the docs
Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion. Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the data object in order for Vue to convert it and make it reactive.
Please take a look to Reactivity in Depth https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ Lambda - error: no matching function for call to
I am trying to pass a lambda as parameter to a function but once I attempt to access a variable inside the lambda which was declared outside, the build fails: error: no matching function for call to 'AWS::subscribe(char [128], mainTask(void*)::<lambda(AWS_IoT_Client*, char*, uint16_t, IoT_Publish_Message_Params*, void*)>)'
I was thinking that the [&] would take care of capturing variables. I also tried [=] as well as [someVar], [&someVar].
I'm using C++11.
char someVar[128];
aws->subscribe(
topic,
[&] (AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData) {
char *text = (char *)params->payload;
sprintf(someVar, "%s", text);
}
);
From the AWS library:
void AWS::subscribe(const char *topic,
pApplicationHandler_t iot_subscribe_callback_handler) {
m_error =
::aws_iot_mqtt_subscribe(&m_client, topic, (uint16_t)std::strlen(topic),
QOS1, iot_subscribe_callback_handler, NULL);
}
A:
The issue is that the AWS::subscribe function expects a function pointer, not a lambda. Capture-less lambdas can be converted to function pointers, but lambdas with captures (i.e. state) cannot.
You can see the "conventional" solution to this already in the signature: There is a void* parameter that you should pack all your callback-specific data into. Presumably this is the last argument of aws_iot_mqtt_subscribe that you currently set to NULL (prefer using nullptr btw).
This is uglier than using lambdas, but it's basically the only option for C-compatible library interfaces:
// Your callback (could also be a capture-less lambda):
void callbackFunc(/* etc. */, void *pData)
{
std::string* someVarPtr = static_cast<std::string*>(pData);
char *text = (char *)params->payload;
sprintf(*someVarPtr, "%s", text);
}
// To subscribe:
std::string someVar;
void* callbackData = &someVar; // Or a struct containing e.g. pointers to all your data.
aws_iot_mqtt_subscribe(/* etc. */, callbackFunc, callbackData);
| {
"pile_set_name": "StackExchange"
} |
Q:
calling Javascript function in JSP
I'm trying to call a function and activate an alert through it in my JSP.
This is what i've done so far:
<html>
<head>
<script type="text/javascript">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
function myFunction( test )
{
alert( test );
}
</script>
<title>Success</title>
</head>
<body>
<c:set var="test" scope="request" value="${requestScope.userDetails }"></c:set>
<input type="button" id="sample_button" onclick="myFunction(${test.userName})" value="test">
</body>
</html>
What is wrong with my code?
A:
In addition to that, You might also need to add a single quote inside the calling function
<input type="button" id="sample_button" onclick="myFunction('${test.userName}')" value="test">
Check for javascript errors & verify the generated HTML in browser
| {
"pile_set_name": "StackExchange"
} |
Q:
Inequality between altitude and sides in triangle
Let $a,b,c$ be the side lengths and $h_a,h_b,h_c$ the altitudes each connect a vertex to the opposite side and are perpendicular to that side. Then we need to prove $h_a^2+h_b^2+h_c^2\leq\dfrac14(a+b+c)^2$.
I know the inequality $h_a^2+h_b^2+h_c^2\leq\dfrac34(a^2+b^2+c^2)$ by using Cauchy inequality. But I could not extend the proof for the above inequality. Does one help me to prove this?
A:
Using 2(Area) = $r(a+b+c) = ah_a = bh_b = ch_c$ the inequality can be written in the more appealing form
$$ \sum \frac {1}{a^2} \leq \frac{1}{r^2} $$
which is the question of maximizing $\sum a^{-2}$ for fixed $r$.
Maybe that has a geometric solution? Of course there is equality for an equilateral triangle.
Descartes formula seems potentially useful:
https://en.wikipedia.org/wiki/Descartes%27_theorem
A:
Following ASCII advocate's idea, the problem boils down to proving that:
$$ 4\Delta^2\left(\frac{1}{a^2}+\frac{1}{b^2}+\frac{1}{c^2}\right)\leq (a+b+c)^2 \tag{1}$$
or, using Heron's formula,
$$ (a+b-c)(a-b+c)(-a+b+c)\left(\frac{1}{a^2}+\frac{1}{b^2}+\frac{1}{c^2}\right)\leq (a+b+c). \tag{2}$$
Through Ravi substitution that turns out to be equivalent to:
$$ 8xyz\left(\frac{1}{(x+y)^2}+\frac{1}{(x+z)^2}+\frac{1}{(y+z)^2}\right)\leq 2(x+y+z)\tag{3} $$
or to:
$$ \sum_{cyc}\frac{1}{(x+y)^2}\leq\sum_{cyc}\frac{1}{4xy}\tag{4}$$
that is trivial as a consequence of the AM-GM inequality.
| {
"pile_set_name": "StackExchange"
} |
Q:
Developing against IE6, IE7, IE8 and soon IE9
In approx 6 months when IE9 is unleashed web developers could have to support up-to 4 versions of IE.
This is very likely to increase support, development and testing for many.
I know Win7 has XP mode to run IE6. IE8 has an IE7 compatibility mode (which is not perfect), what happens when IE9 is released ?
Will there be an IE7/8 mode for IE9, will we be able to install IE9 alongside IE8 ?
Or what about Vista mode to run IE7/8 ?
Or do you think Microsoft will make a statement about IE6 having limited support, please do not use any more ?
What are you ideas/plans/strategies to ease/cope with this pain (plain not supporting IE6) ?
Cheers, Nick
A:
You should use the IE app compat VPC images for testing.
A:
Official Microsoft support for IE6 will end in 2014, along with Window XP. That is already decided. (in fact, it should have ended already but the end-of-life date was extended by a couple of years when MS extended the end-of-sale date for XP after the Vista debacle)
So after 2014, anyone running XP or IE6 will be out of support. There will still be people using it, but the corporates that have been holding out will be forced to move on as they tend to be quite risk-averse when it comes to having unsupported software on their systems.
Supporting IE9 should be a lot easier than IE6/7/8, since it is standards compliant in ways that its predecessors weren't. The code you write for other browsers like Firefox should work in IE9 relatively unchanged. There are obviously going to be modern HTML5 features that IE9 doesn't support or does differently to everyone else, but if you're having to support IE6/7/8 you won't be able to use those features anyway.
If you're in any doubt about how IE9 will work on your site, you can download the developer preview now and try it out.
By the way: For some useful browser compatibility charts, I recommend the Quirksmode site, which will tell you exactly what features are supported by which browsers.
For what it's worth, our company has officially stopped supporting IE6 on our site.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proccessing, nextGaussian isn't between -1 and 1?
I was working on a little Processing project to visualize gaussian random numbers, and I have a problem where the numbers produced are not between -1 and 1, which throws my whole thing off. What numbers do I have to scale the number by to scale it to the -1 to 1 range?
Program
import java.util.*;
Random generator;
void setup()
{
size(600,600);
generator = new Random();
background(255);
}
void draw()
{
generatenewdot();
}
void generatenewdot()
{
float xnum = (float)generator.nextGaussian();
float sd = 60;
float xmean = width/2;
float x = sd * xnum + xmean;
float ynum = (float)generator.nextGaussian();
float ymean = height/2;
float y = sd * ynum + ymean;
//Bigger when closer, smaller when farther
//get distance from center
float distance = sqrt(pow(sd*xnum,2) + pow(sd*ynum,2));
float size = (1 - (distance/sd)) * 10;
println("X: " + xnum + " | Y: " + ynum);
noStroke();
fill(0, 50);
ellipse(x, y, size, size);
}
Output
X: -1.2560346 | Y: 0.43913
X: 1.6684186 | Y: -1.0307527
X: -0.20982298 | Y: -0.22280085
X: -0.5874519 | Y: -2.3560321
X: -1.6996952 | Y: -0.6252706
X: -0.3767569 | Y: 0.8847021
X: 2.16339 | Y: 0.84067136
X: 0.9579867 | Y: -1.5785545
X: 0.39750758 | Y: -1.4931071
X: -0.43088776 | Y: 0.75665843
X: 1.0801688 | Y: -2.6318247
X: -1.1454289 | Y: -0.95125073
X: 1.4965589 | Y: 1.0736477
X: -0.39217913 | Y: -0.34573647
X: 0.0060171164 | Y: 1.0194058
X: -2.482392 | Y: -0.37381676
X: -0.120092504 | Y: -1.3072939
X: -0.79035485 | Y: -0.33741793
X: -1.0654978 | Y: -1.3986521
X: 0.30195275 | Y: -0.09365952
X: -1.3775821 | Y: -0.91224575
X: 0.15109988 | Y: -1.5025057
X: -0.9888884 | Y: 0.5061488
X: 1.7362484 | Y: -0.3089954
X: -0.48933098 | Y: -1.0289067
X: 0.54819685 | Y: 1.915066
X: -0.89757615 | Y: -0.5725651
X: -1.1072423 | Y: 0.1549204
X: -0.05344215 | Y: 0.044364702
X: -0.047609538 | Y: 0.7296939
X: 0.62724686 | Y: 0.30536157
X: 1.6744004 | Y: 0.13948894
X: 0.8259148 | Y: 1.3571945
X: 0.93188906 | Y: 0.89352655
X: -0.62066746 | Y: -0.2791857
X: 0.45208132 | Y: 0.7484442
X: 1.4533566 | Y: 0.15946567
X: -0.26117975 | Y: -0.9406836
X: 0.14579183 | Y: -0.6735571
X: -0.11575534 | Y: 0.24251445
X: -0.71969754 | Y: 1.2312696
X: -0.33103114 | Y: -0.3679331
X: -0.87640345 | Y: 0.18695408
X: 1.4733391 | Y: -1.717308
X: -0.47379303 | Y: 0.94097525
X: -1.2317376 | Y: -0.44845966
X: -1.9225131 | Y: 0.33214918
X: 0.6805828 | Y: -0.82625526
X: 2.0353675 | Y: -0.56851065
X: 0.43589613 | Y: -0.059929434
X: -0.53751755 | Y: 0.85414284
X: 2.2904902 | Y: -0.369723
X: -0.12156449 | Y: -1.0917004
X: -0.889154 | Y: 0.64644057
X: -0.22776474 | Y: 1.4512538
X: -0.7672019 | Y: -0.42612842
X: -0.410998 | Y: -1.1754745
X: 0.9694859 | Y: -0.32890838
X: 0.38745773 | Y: -0.7073066
X: -0.41483563 | Y: 0.3499609
X: 0.0570873 | Y: 1.0256606
X: 0.5236664 | Y: -1.6412264
X: -1.1053294 | Y: -0.06714651
X: 0.77513236 | Y: -0.36635277
X: 0.40660658 | Y: 0.72002655
X: -0.2413241 | Y: 0.10751419
X: -0.5079167 | Y: 0.2544589
X: 0.0738618 | Y: -0.46861497
X: 0.36933857 | Y: 3.282707
X: -0.38261575 | Y: -1.2680397
X: 0.26502755 | Y: -1.4085288
X: -1.0758035 | Y: 0.48999637
X: -1.0022781 | Y: 0.18629716
X: 1.089121 | Y: 0.22576475
X: -0.1774196 | Y: 1.1405197
X: -0.75939226 | Y: -1.246858
X: 2.0534744 | Y: -0.027038628
X: 1.2573285 | Y: -0.2153611
X: 0.91109043 | Y: -0.9592889
X: 1.1948314 | Y: 0.8129871
X: -0.2642877 | Y: -2.1204646
X: 0.76492834 | Y: 1.0202236
X: -0.19996478 | Y: -0.25985986
X: 0.305574 | Y: -0.15428662
X: -0.5793801 | Y: 0.05751243
X: -1.1586995 | Y: -1.354029
X: -2.0605218 | Y: 0.15988825
X: 0.13619052 | Y: 0.688434
X: -0.28077507 | Y: -1.5288342
X: -0.382878 | Y: -0.37027964
X: 0.7066691 | Y: -0.71114177
X: 0.3983471 | Y: 0.52614754
X: -0.7913421 | Y: 1.4425266
X: 0.12273746 | Y: 1.081629
X: -0.13688068 | Y: -1.1057968
X: 0.60105777 | Y: -0.93368775
X: -1.3000423 | Y: -0.061667506
X: 0.12970658 | Y: -0.82605433
X: 0.29501432 | Y: -0.52549535
X: 0.39391693 | Y: 0.8624781
X: 2.4755092 | Y: -1.0342329
X: -0.22210532 | Y: -0.6144739
X: -0.3413467 | Y: -0.19307336
X: -0.5308936 | Y: 0.30849203
X: 1.1740618 | Y: 1.2144334
X: 0.1827944 | Y: -0.17112117
X: 1.1925478 | Y: -0.3520857
X: -1.2051786 | Y: 0.15042834
X: 3.0183444 | Y: -0.90113115
X: -1.0622096 | Y: -0.30049986
X: 1.8420129 | Y: 1.2509897
X: -2.297314 | Y: -2.0725875
X: 1.0673923 | Y: -2.5084429
X: 0.3134048 | Y: -0.052358847
X: 0.16638549 | Y: 0.5592031
X: -0.067902535 | Y: -1.420417
X: -0.016045086 | Y: -1.0686399
X: -0.6912575 | Y: -0.9322265
X: 1.0217631 | Y: 0.5885641
X: -0.77907616 | Y: 0.5000267
X: 0.01890201 | Y: -0.11718043
X: -0.958193 | Y: -1.3351127
X: -0.3736327 | Y: 1.9608271
X: -0.7962202 | Y: 0.7476578
X: 0.25758967 | Y: -0.77497977
X: -0.48639807 | Y: -0.7017801
X: -0.82916087 | Y: 0.8303733
X: -1.707152 | Y: -1.3296013
X: -1.7046789 | Y: -0.24234797
X: -1.0117844 | Y: 0.45633218
X: -0.08127227 | Y: 0.48397893
X: 0.82085145 | Y: 2.2481968
X: 1.3258406 | Y: 2.198357
X: 0.2562196 | Y: 0.3340968
X: 0.60788757 | Y: 0.24063592
X: -0.031290732 | Y: -0.14278243
X: -1.2028422 | Y: 0.6705914
X: -0.7122825 | Y: 0.33648172
X: -1.3599969 | Y: -0.6731673
X: -0.5936929 | Y: -0.34959924
X: 1.964009 | Y: 0.8512692
X: -0.68523324 | Y: -0.4050971
X: 0.60271347 | Y: -0.09168337
X: 0.02265682 | Y: -0.8994877
X: 0.5623386 | Y: -1.1070106
X: -1.4453007 | Y: -0.31628308
X: -0.062762 | Y: 1.5903912
X: -0.3273365 | Y: 0.11271362
X: -0.011844525 | Y: -0.97879356
X: -0.21651044 | Y: -1.488296
X: 1.7444072 | Y: -0.6698305
X: 0.07018017 | Y: 0.052752882
X: 0.33038074 | Y: -0.51466936
X: -0.3488621 | Y: 0.6184827
X: 0.049165536 | Y: 0.7268606
X: 0.38889283 | Y: 0.22207315
X: 1.1190308 | Y: 0.18530433
X: -0.5596919 | Y: 0.038130693
X: 2.2971296 | Y: 0.08598893
X: 0.48901424 | Y: -0.6340521
X: -0.34295475 | Y: 2.4535484
X: 0.7059389 | Y: -0.060639072
X: -0.9430291 | Y: -0.030210787
X: 0.14106135 | Y: 0.3733378
X: 0.23838589 | Y: -0.11811932
X: -0.14800806 | Y: 0.02691031
X: -0.4372808 | Y: -0.912786
X: -1.2872834 | Y: -0.16293962
X: 1.9569577 | Y: -0.2684084
X: 1.4659501 | Y: 0.79093254
X: 1.1387724 | Y: 1.4153944
X: -0.9614859 | Y: 1.2193747
X: -0.24685526 | Y: 1.1087464
X: 0.25005496 | Y: -0.18707326
X: -0.08282836 | Y: 0.16380334
X: -0.890932 | Y: -0.01911562
X: -1.3180755 | Y: -1.7750782
X: -1.9738325 | Y: 0.4650801
X: 0.11823471 | Y: -0.7086047
X: 0.7637192 | Y: 3.0014162
X: 1.0746229 | Y: 0.5347033
X: -0.57545507 | Y: 1.2818112
X: 1.2836952 | Y: 1.0796871
X: -0.26668364 | Y: 0.19159853
X: -2.1289194 | Y: -1.8146951
X: 1.4087044 | Y: 0.266897
X: -0.12748817 | Y: 1.4472772
X: 1.0245978 | Y: 0.17778511
X: -1.416702 | Y: -1.1412634
X: -1.5589409 | Y: 0.095859885
X: 1.1145445 | Y: -0.32158515
X: -2.2714367 | Y: -1.032223
X: 1.2649084 | Y: -1.9037691
X: -0.33965677 | Y: 0.81614226
X: -0.12146729 | Y: 0.4777388
X: -0.4253145 | Y: 1.5192709
X: -0.20069526 | Y: 0.0266705
X: 0.7794582 | Y: 0.20600611
X: 0.068017714 | Y: -0.7936217
X: -0.8899986 | Y: -0.5964193
X: -0.18383493 | Y: -0.92586005
X: -0.7818783 | Y: -0.4391756
X: 2.9518538 | Y: 0.51974326
X: -0.30460843 | Y: 1.4595356
X: -0.76000154 | Y: -0.6935336
X: 1.2247328 | Y: -1.9350185
X: -0.17959218 | Y: 0.52692646
X: -1.1845113 | Y: -0.7372843
X: 0.7145226 | Y: 0.97987723
X: 0.294313 | Y: 0.42491102
X: 0.69715863 | Y: 1.0249106
X: 0.61984223 | Y: 1.9051309
X: 0.10692853 | Y: -0.7397708
X: -1.6503758 | Y: -0.56400114
X: -0.619303 | Y: -0.50828993
X: -1.0103049 | Y: 1.5179138
X: -0.6610786 | Y: -0.23466662
X: 1.47647 | Y: -0.7518148
X: 1.8461105 | Y: -0.89638317
X: -1.0333326 | Y: 0.5272911
X: 0.32953307 | Y: -2.068906
X: -0.3369011 | Y: 1.1342978
X: 0.26832464 | Y: 0.35111254
X: -1.1943347 | Y: 1.5756301
X: -0.2821439 | Y: -0.21851084
X: 0.045426905 | Y: 0.43564394
X: -0.08327247 | Y: 0.17497726
X: 0.26342446 | Y: 0.8225831
X: 0.51339006 | Y: -0.70085526
X: 0.6015727 | Y: 1.4097772
X: -0.87026924 | Y: -1.2695398
X: 0.9147027 | Y: -0.54681355
X: -0.25914836 | Y: 0.14173253
X: 0.79905576 | Y: -0.78842294
X: -0.122037366 | Y: 1.9061232
X: 0.031827897 | Y: 9.054022E-5
X: 0.8216564 | Y: 1.1695337
X: -0.3981461 | Y: 1.6214145
X: -0.6744849 | Y: 0.16823441
X: 0.1994377 | Y: 1.041054
X: -0.9688934 | Y: 0.5749102
X: 0.52517 | Y: 0.3087776
X: -0.31726742 | Y: 1.0651228
X: 0.5944692 | Y: -0.39537027
X: -0.14272667 | Y: 0.15524986
X: 1.0194787 | Y: -0.17233147
X: -0.3691948 | Y: 0.62380767
X: 1.2492002 | Y: -0.024808018
X: 1.0656878 | Y: -0.6394374
X: 1.8846616 | Y: 1.1887405
X: 2.2143235 | Y: -0.9957973
X: 1.1480668 | Y: -2.0087852
X: -0.7856953 | Y: 0.17126346
X: 1.4994434 | Y: 0.42100754
X: 0.61520094 | Y: 0.4594768
X: -1.8998433 | Y: 0.81686187
X: -0.59870094 | Y: 0.16190825
X: 0.7568211 | Y: 0.1445908
X: 0.068865344 | Y: -0.11507618
X: -0.13646689 | Y: -0.71280926
X: -0.42065284 | Y: 1.6816016
X: -0.8548044 | Y: -0.23868565
X: 0.44674578 | Y: -0.08002255
X: 0.15143052 | Y: 0.9913837
X: -0.24043444 | Y: -0.4339675
X: -0.07372746 | Y: -1.4390934
X: -2.0154748 | Y: -0.6124442
X: 2.336962 | Y: 0.09206108
X: 0.12995008 | Y: 0.6019416
X: -0.14780447 | Y: -0.9132321
X: 0.8062503 | Y: 0.1129237
X: 0.12131127 | Y: -1.5861236
X: 0.4869577 | Y: -0.67768985
X: -1.1218196 | Y: 1.184578
X: 0.7874171 | Y: -0.045187805
X: -0.67828524 | Y: -0.5735016
X: -0.994444 | Y: 0.28350237
X: 2.633789 | Y: 0.54614604
X: -0.08738608 | Y: 1.5393788
X: -0.1632809 | Y: 1.0571663
X: -0.9038875 | Y: 0.30314434
X: 1.3459784 | Y: 0.38406494
X: -0.638972 | Y: -0.21715638
X: 1.401298 | Y: 0.2867331
X: -0.92279404 | Y: 0.9176272
X: -0.041815635 | Y: -1.5927134
X: 0.14853486 | Y: -0.5005275
X: -0.12517829 | Y: 0.9995699
X: 0.30420595 | Y: -0.7695801
X: -1.1811762 | Y: -1.1573164
X: 0.3598652 | Y: 0.18536983
X: 0.92923003 | Y: -0.045854274
X: 1.0242708 | Y: -0.6519265
X: -0.15148447 | Y: -1.6188399
X: -0.5767954 | Y: -0.7759711
X: 1.691366 | Y: 2.0550196
X: -2.4651797 | Y: -0.532277
X: -0.38202325 | Y: 2.7200665
X: -0.026308075 | Y: -0.41392756
X: -0.54529566 | Y: 1.0306138
X: -0.2474008 | Y: -0.8410272
X: -0.8878296 | Y: 0.6692659
X: -1.0749551 | Y: -0.05105501
X: -1.4509034 | Y: -0.40763706
X: 0.63799614 | Y: 0.5781374
X: -0.15311946 | Y: 0.9867796
X: 1.0860987 | Y: 2.2270775
X: -1.8498964 | Y: -0.15837035
X: 0.5712155 | Y: 0.6274683
X: 0.10293772 | Y: -0.2556146
X: 0.70576346 | Y: -0.60659826
X: 0.40139621 | Y: 0.17961529
X: -1.8881758 | Y: 0.017092947
X: -2.8272333 | Y: -0.9225435
X: -0.10255992 | Y: -0.5627598
X: -1.5514668 | Y: 1.090334
X: 0.8607706 | Y: 0.44446054
A:
The Gaussian probability distribution extends to infinity, but you can scale it so that samples are in (-1, 1) with 95%, 99%, or higher probability. But some samples will always be outside of (-1, 1).
For example generator.nextGaussian()/1.69 will be in (-1, 1) with 95% probability, and outside with 5% probability.
| {
"pile_set_name": "StackExchange"
} |
Q:
exec() waiting for a response in PHP
Possible Duplicate:
php exec command (or similar) to not wait for result
I have a page that runs a series of exec() commands which forces my PHP script to halt alteration until it receives a response. How can I tell exec() to not wait for a response and just run the command?
I'm using a complex command that has a backend system I can query to check the status, so I'm not concerned with a response.
A:
Depends on what platform you are using, and the command you are running.
For example, on Unix/Linux you can append > /dev/null & to the end of the command to tell the shell to release the process you have started and exec will return immediately. This doesn't work on Windows, but there is an alternative approach using the COM object (See edit below).
Many commands have a command line argument that can be passed so they release their association with the terminal and return immediately. Also, some commands will appear to hang because they have asked a question and are waiting for user input to tell them to continue (e.g. when running gzip and the target file already exists). In these cases, there is usually a command line argument that can be passed to tell the program how to handle this and not ask the question (in the gzip example you would pass -f).
EDIT
Here is the code to do what you want on Windows, as long as COM is available:
$commandToExec = 'somecommand.exe';
$wshShell = new COM("WScript.Shell");
$wshShell->Run($commandToExec, 0, FALSE);
Note that it is the third, FALSE parameter that tells WshShell to launch the program then return immediately (the second 0 parameter is defined as 'window style' and is probably meaningless here - you could pass any integer value). The WshShell object is documented here. This definitely works, I have used it before...
I have also edited above to reflect the fact that piping to /dev/null is also required in order to get & to work with exec() on *nix.
Also just added a bit more info about WshShell.
| {
"pile_set_name": "StackExchange"
} |
Q:
Core Animation + UIDynamics + arc4random()
I have a single UFO that is an UIImage and I simply want it to float around and come in and off at random locations like the asteroids in the game Asteroids. I put some rotation and grow in there temporarily. It would be nice if all of the animations were done randomly. Even if it was only random motion I'd be super happy. How do I implement arc4random()? After I accomplish that simple task I'd like to learn how to apply arc4random() to various behaviours in UIDynamics. Thanks in advance.
import UIKit
class ViewController: UIViewController {
@IBOutlet var ufo: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
UIView.animateWithDuration(5.5, delay: 0, options: .Repeat, animations: {
let grow = CGAffineTransformMakeScale(2, 2)
let angle = CGFloat( -30)
let rotate = CGAffineTransformMakeRotation(angle)
self.ufo.transform = CGAffineTransformConcat(grow, rotate)
}, completion: nil)
}
}
A:
arc4random_uniform(n) will return a number from 0 to n. If you want this to return an Int then you can cast it as below:
var randomNumber = Int(arc4random_uniform(7))
Use this function to generate random numbers and then use those numbers in your animation.
For example, if you want your animation to have a random duration:
var duration = Double(arc4random_uniform(5)+1)
var x = CGFloat(arc4random_uniform(320))
var y = CGFloat(arc4random_uniform(960))
UIView.animateWithDuration(duration, delay: 0, options: .Repeat, animations: {
let grow = CGAffineTransformMakeScale(2, 2)
let angle = CGFloat( -30)
let rotate = CGAffineTransformMakeRotation(angle)
self.ufo.transform = CGAffineTransformConcat(grow, rotate)
self.ufo.frame = CGRectMake(x,y,self.ufo.frame.size.width, self.ufo.frame.size.height)
}, completion: nil)
The reason I have the arc4random_uniform(5)+1 is because the function is from 0 to n as I mentioned above, so 0 to 5 in this case but we do not want an animation with 0 duration so I added 1 to it to make the number 1 to 6.
| {
"pile_set_name": "StackExchange"
} |
Q:
LINQ SQL Method not Filling Highcharts
My goal is to create a column highchart that shows the name of various salesman and how much they have sold. I wrote this code to return from my SQL Database the names and the sum of the sales for each salesman:
[HttpPost]
public JsonResult ChartVendedores()
{
//Retorna um JSON contendo o nome do vendedor e o valor por ele vendido, usando inner join pelo id do vendedor.
try
{
var resultado = (from ve in db.tblVendedor
join vn in db.tblVenda on ve.vendedor_id equals vn.vendedor_id
group vn by new
{
ve.vendedor_nome
}into g
select new {
vendedor_nome = g.Key.vendedor_nome,
venda_valor = g.Sum(x => x.venda_valor)
}).ToList();
var jsonResult = new
{
Nomes = resultado.Select(x => x.vendedor_nome),
Valores = resultado.Select(x => x.venda_valor)
};
return Json(resultado);
}catch(Exception)
{
return null;
}
}
And this is where the chart is created, the method is called and it is suposed to fill the chart with the database's return data:
<script>
$(function () {
$.ajax({
url: '/Vendedores/ChartVendedores',
type: 'post',
async: false,
sucess: function (data) {
//Constrói o gráfico com os valores retornados pelo banco.
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Venda dos Colaboradores'
},
xAxis: {
categories: [
data.Nomes
],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Valor (R$)'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Valores',
data: data.Valores
}]
});
}
})
})
What am I'm missing? As long as code goes, i don't think I wrote any wrong code in the method. Am I calling it wrong? Am I manipulating it wrong? I tried to remove my Ajax code, only leaving the chart itself as it is on the highchart.com and it worked, so the problem is not on my container div or in the chart code.
EDIT: As commented bellow, I looked at my console and I'm getting an warning about one of the imports that Highcharts needs. The waning follows is this one. After seeing this, I tried to remove the AJax and only using the highchart code. It worked! For some reason when the chart tries to use this:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
It does not find it when the chart code is contained inside sucess: function(data){}
Note: I'm importing everything at the beggining of the code, meanwhile the script containing the Ajax is written last.
A:
$.ajax({
url: '/Vendedores/ChartVendedores',
type: 'post',
async: false,
sucess: function (data) {
should be changed to:
$.ajax({
url: '/Vendedores/ChartVendedores',
type: 'post',
async: false,
success: function (data) {
You have misspelt success.
| {
"pile_set_name": "StackExchange"
} |
Q:
LNK2001 and LNK1120 when compiling a x64 dynamic library linking a x86 static library
I recently got assigned to a c++ project, although I am not a c++ developer. I was provided Visual Studio 2010 Professional as IDE. So I gave it a shot.
I am to write a c++ dynamic library (*.dll) which wraps two static libraries (*.lib). The static libraries are third party libraries we bought a couple of years ago from another company. Using the dumpbin /header ... cmd call, I can say that both static libraries have the following file header value:
14C machine (x86)
I got this task working for the Win32 solution platform. I added the header files and the libraries to the project. The libraries are included by writing two #pragma comment(lib, ...) statements within the .cpp I need the functions in. Works like a charm. A sample function looks like this:
extern "C" void OURFreeStringBuf(Cm_StringBuf *sbuf)
{
FreeStringBuf(sbuf); // the call to the static library
}
This dynamic library is to be used in x64 architectures, aswell. So I tried to set the solution platform to x64. Now I get the following error for each call of one of the static libraries' functions (no code changes or other configuration changes were made):
error LNK2001: unresolved external symbol "..."
followed by a summarizing error:
error LNK1120: 29 unresolved external links
Could these errors be the result of trying to link x86 lib files in a x64 dll? Is there any chance to complete this task using the provided static libraries?
Thank you very much in advance.
A:
You can not - in other words, there is NO WAY to - link a 32-bit library with a 64-bit executable or DLL (or a 32-bit executable to a 64-bit DLL or vice versa). You will either have to compile your .DLL/.EXE as 32-bit, or find a 64-bit version of the 32-bit library. No other solution!
The 64-bit architecture is different from the 32-bit architecture in several aspects, but most importantly, the addresses (pointers) are 64-bit in a 64-bit architecture, which prevents almost any 32-bit code from working correctly in a 64-bit environment (because the upper 32 bits of the addresses are lost, which doesn't produce anything meaningful).
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get rid of annoying code tips in Visual Studio 2010?
When I first open Visual Studio 2010, I accidentally said "Yes" to help/code tips or something. Now whenever I type code, I get these annoying pop-ups explaining what happened or trying to improve my code, etc. These help tips are making it difficult to code and causing Visual Studio to run slowly.
How do I disable them?
Edit: my apologies for posting this. I did not realize it was off-topic. Does Stack Overflow have a proper place for questions about software tools such as IDEs?
A:
These are the help tips from CodeRush which is a IDE productivity tool from DevExpress. You can disable it by going to your tools menu and select DevExpres->UnLoad
Doing this will not only disable the smart tips, but the whole CodeRush.
Personally, It is not annoying for me. This helps me to be more productive. In a single statment "I love CodeRush to have in my VS environment"
| {
"pile_set_name": "StackExchange"
} |
Q:
Extract strings from JSON as array in PHP
I have the following JSON from Google API and i want to extract cse_image -> src and use it in PHP array as arr[0] for first , arr[1] for second and so on.
{
"kind": "customsearch#search",
"url": {
"type": "application/json",
"template": "https://www.googleapis.com/customsearch/v1?q={searchTerms}&num={count?}&start={startIndex?}&lr={language?}&safe={safe?}&cx={cx?}&cref={cref?}&sort={sort?}&filter={filter?}&gl={gl?}&cr={cr?}&googlehost={googleHost?}&c2coff={disableCnTwTranslation?}&hq={hq?}&hl={hl?}&siteSearch={siteSearch?}&siteSearchFilter={siteSearchFilter?}&exactTerms={exactTerms?}&excludeTerms={excludeTerms?}&linkSite={linkSite?}&orTerms={orTerms?}&relatedSite={relatedSite?}&dateRestrict={dateRestrict?}&lowRange={lowRange?}&highRange={highRange?}&searchType={searchType}&fileType={fileType?}&rights={rights?}&imgSize={imgSize?}&imgType={imgType?}&imgColorType={imgColorType?}&imgDominantColor={imgDominantColor?}&alt=json"
},
"queries": {
"nextPage": [
{
"title": "Google Custom Search - Gravity Falls",
"totalResults": "13600",
"searchTerms": "Gravity Falls",
"count": 2,
"startIndex": 4,
"inputEncoding": "utf8",
"outputEncoding": "utf8",
"safe": "off",
"cx": "005215763543692940433:2hdsc4__avm",
"filter": "0",
"disableCnTwTranslation": "disable"
}
],
"request": [
{
"title": "Google Custom Search - Gravity Falls",
"totalResults": "13600",
"searchTerms": "Gravity Falls",
"count": 2,
"startIndex": 2,
"inputEncoding": "utf8",
"outputEncoding": "utf8",
"safe": "off",
"cx": "005215763543692940433:2hdsc4__avm",
"filter": "0",
"disableCnTwTranslation": "disable"
}
],
"previousPage": [
{
"title": "Google Custom Search - Gravity Falls",
"totalResults": "13600",
"searchTerms": "Gravity Falls",
"count": 2,
"startIndex": 1,
"inputEncoding": "utf8",
"outputEncoding": "utf8",
"safe": "off",
"cx": "005215763543692940433:2hdsc4__avm",
"filter": "0",
"disableCnTwTranslation": "disable"
}
]
},
"context": {
"title": "Gravity Falls"
},
"searchInformation": {
"searchTime": 0.269451,
"formattedSearchTime": "0.27",
"totalResults": "13600",
"formattedTotalResults": "13,600"
},
"items": [
{
"kind": "customsearch#result",
"title": "Gravity Falls Apparel - Gravity Falls Wiki",
"htmlTitle": "\u003cb\u003eGravity Falls\u003c/b\u003e Apparel - \u003cb\u003eGravity Falls\u003c/b\u003e Wiki",
"link": "http://gravityfalls.wikia.com/wiki/Gravity_Falls_Apparel",
"displayLink": "gravityfalls.wikia.com",
"snippet": "Gravity Falls apparel are officially sold clothes. On December 11, 2012 \nWeLoveFine.com released...",
"htmlSnippet": "\u003cb\u003eGravity Falls\u003c/b\u003e apparel are officially sold clothes. On December 11, 2012 \u003cbr\u003e\nWeLoveFine.com released...",
"cacheId": "6Uh7-hm1BKoJ",
"formattedUrl": "gravityfalls.wikia.com/wiki/Gravity_Falls_Apparel",
"htmlFormattedUrl": "\u003cb\u003egravityfalls\u003c/b\u003e.wikia.com/wiki/\u003cb\u003eGravity\u003c/b\u003e_\u003cb\u003eFalls\u003c/b\u003e_Apparel",
"pagemap": {
"cse_image": [
{
"src": "http://img3.wikia.nocookie.net/__cb20130410025818/gravityfalls/images/thumb/5/54/Welovefine_rainbow_gnome.jpg/500px-Welovefine_rainbow_gnome.jpg" //This as arr[0]
}
],
"cse_thumbnail": [
{
"width": "225",
"height": "225",
"src": "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcS6kUI6yrCQkhX45BaaylTdDWb9tKvUf2OxwXJJv5NONxG1f0o09YerhB9j"
}
],
"metatags": [
{
"viewport": "width=device-width, initial-scale=1.0, user-scalable=yes",
"fb:app_id": "112328095453510",
"og:type": "article",
"og:site_name": "Gravity Falls Wiki",
"og:title": "Gravity Falls Apparel",
"og:description": "Gravity Falls apparel are officially sold clothes. On December 11, 2012 WeLoveFine.com released the first official Gravity Falls merchandise. The same day they launched a Gravity Falls T-shirt design contest which was judged by Alex Hirsch and Michael Rianda. The Grand prize winner received up to $2,000, with several runners up receiving various prizes on top of their own designs becoming part of the online store.",
"og:url": "http://gravityfalls.wikia.com/wiki/Gravity_Falls_Apparel",
"og:image": "http://img3.wikia.nocookie.net/__cb20130410025818/gravityfalls/images/thumb/5/54/Welovefine_rainbow_gnome.jpg/500px-Welovefine_rainbow_gnome.jpg",
"apple-itunes-app": "app-id=623705389"
}
]
}
},
{
"kind": "customsearch#result",
"title": "Gravity Falls, Oregon - Gravity Falls Wiki",
"htmlTitle": "\u003cb\u003eGravity Falls\u003c/b\u003e, Oregon - \u003cb\u003eGravity Falls\u003c/b\u003e Wiki",
"link": "http://gravityfalls.wikia.com/wiki/Gravity_Falls,_Oregon",
"displayLink": "gravityfalls.wikia.com",
"snippet": "Gravity Falls, Oregon is a mysterious, sleepy, small town in Central Oregon, \nwhere there are many supernatural occurrences. It was founded by Quentin ...",
"htmlSnippet": "\u003cb\u003eGravity Falls\u003c/b\u003e, Oregon is a mysterious, sleepy, small town in Central Oregon, \u003cbr\u003e\nwhere there are many supernatural occurrences. It was founded by Quentin ...",
"cacheId": "le0YqUje3GYJ",
"formattedUrl": "gravityfalls.wikia.com/wiki/Gravity_Falls,_Oregon",
"htmlFormattedUrl": "\u003cb\u003egravityfalls\u003c/b\u003e.wikia.com/wiki/\u003cb\u003eGravity\u003c/b\u003e_\u003cb\u003eFalls\u003c/b\u003e,_Oregon",
"pagemap": {
"cse_image": [
{
"src": "http://img2.wikia.nocookie.net/__cb20120526133929/gravityfalls/images/thumb/f/fd/S1e1_gravity_falls_oregon_map.jpg/500px-S1e1_gravity_falls_oregon_map.jpg" // This as arr[1]
}
],
"videoobject": [
{
"thumbnail": "http://img2.wikia.nocookie.net/__cb20140905002344/video151/images/thumb/e/ec/Gravity_Falls_-_Referencias_Interesantes/300px-Gravity_Falls_-_Referencias_Interesantes.jpg",
"duration": "01:47"
}
],
"cse_thumbnail": [
{
"width": "299",
"height": "168",
"src": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTEsgxZQQYbR400fXDcbDafk6y5Jr9wLjy7ZAV7F3sfBccdhkGnwfiNlPA"
}
],
"metatags": [
{
"viewport": "width=device-width, initial-scale=1.0, user-scalable=yes",
"fb:app_id": "112328095453510",
"og:type": "article",
"og:site_name": "Gravity Falls Wiki",
"og:title": "Gravity Falls, Oregon",
"og:description": "Gravity Falls, Oregon is a mysterious, sleepy, small town in Central Oregon, where there are many supernatural occurrences. It was founded by Quentin Trembley, It's where Stan Pines lives and runs the Mystery Shack, a tourist trap which overcharges unlucky visitors for a glimpse at the world's most bizarre museum. Twin siblings Dipper and Mabel Pines are sent to stay with Stan for the summer, which leads them to discover the different yet curious wonders of Gravity Falls. Gravity Falls...",
"og:url": "http://gravityfalls.wikia.com/wiki/Gravity_Falls,_Oregon",
"og:image": "http://img2.wikia.nocookie.net/__cb20120526133929/gravityfalls/images/thumb/f/fd/S1e1_gravity_falls_oregon_map.jpg/500px-S1e1_gravity_falls_oregon_map.jpg",
"apple-itunes-app": "app-id=623705389"
}
]
}
}
]
}
Language: PHP
I want to extract JSON using PHP then access it using
arr[0]:http://img3.wikia.nocookie.net/__cb20130410025818/gravityfalls/images/thumb/5/54/Welovefine_rainbow_gnome.jpg/500px-Welovefine_rainbow_gnome.jpg
arr[1]:http://img2.wikia.nocookie.net/__cb20120526133929/gravityfalls/images/thumb/f/fd/S1e1_gravity_falls_oregon_map.jpg/500px-S1e1_gravity_falls_oregon_map.jpg
How can i do this with json_decode or any other similar method
A:
$data = json_decode($string, true);
echo $data['items'][0]['pagemap']['cse_image'][0]['src'];
echo $data['items'][1]['pagemap']['cse_image'][0]['src'];
| {
"pile_set_name": "StackExchange"
} |
Q:
Excel Macro Change Cell Format to Text Of Protected Sheet
I have a requirement to change a protected sheet cell format to Text(from Date) as soon as the sheet is opened. I mean to say the value should appear as it was entered into the sheet.
I have kept my code in Workbook_Open() event of ThisWorkBook, and the sequence of steps given below.
Unprotect the Sheet: gSampleSheet.Unprotect Password:="MyPassword"
Change the Cell format: gSampleSheet.Range("K1:K100").NumberFormat = "Text"
Protect the Sheet: gSampleSheet.Protect DrawingObjects:=False, contents:=True, Scenarios:=True, Password:="MyPassword"
When a Date value is entered in the cell then it should be converted to Text format and the value should appear as is.
i.e. If 12/12/15, 12.12.15, 12-12-15, 12-Dec-15 are entered then they should appear as they are entered(instead of changed to Date Format).
However the cell is showing some random values like T2015tx or some other values. Please help me to fix this as I am struggling to find out the root cause.
A:
Try:
gSampleSheet.Range("K1:K100").NumberFormat = "@"
| {
"pile_set_name": "StackExchange"
} |
Q:
R: loading multiple RData with mclapply doesn't work
I wanted to load multiple RData in one command, as explained by Johua using
> lapply(c(a_data, b_data, c_data, d_data), load, .GlobalEnv)
[[1]]
[1] "nRTC_Data"
[[2]]
[1] "RTA_Data"
[[3]]
[1] "RTC_Data"
[[4]]
[1] "RTA_Data"
> rm(a_data, b_data, c_data, d_data); ls()
[1] "nRTC_Data" "RTA_Data" "RTAC_data" "RTC_Data"
However, since my RData are big, and I found no time improvement between lappy() and multiple load(), I decided to use multi-core approach like following:
library(parallel)
mclapply(c(a_data, b_data, c_data, d_data),load,.GlobalEnv, mc.cores = parallel::detectCores())
Though this significantly improved the loading time, also returns the list
[[1]]
[1] "nRTC_Data"
[[2]]
[1] "RTA_Data"
[[3]]
[1] "RTC_Data"
[[4]]
[1] "RTA_Data"
In my workspace, nothing is found
> rm(a_data, b_data, c_data, d_data); ls()
character(0)
I also tried replacing .GlobalEnv by environment(), but still didn't work.
Any one has a clue?
FYI, you can try with following commands:
> a = "aa";save(a, file = "aa.RData")
> b = "bb";save(b, file = "bb.RData")
> c = "cc";save(c, file = "cc.RData")
> d = "dd";save(d, file = "dd.RData")
> # lapply approach
> rm(list = ls())
> a = "aa.RData"; b = "bb.RData"; c = "cc.RData"; d = "dd.RData"
> lapply(c(a, b, c, d), load, .GlobalEnv); rm(a, b, c, d)
> # mclapply approach
> rm(list = ls())
> a = "aa.RData"; b = "bb.RData"; c = "cc.RData"; d = "dd.RData"
> mclapply(c(a, b, c, d), load, .GlobalEnv, mc.cores = parallel::detectCores()); rm(a, b, c, d)
A:
I think it's because when using mclapply the underlying forking creates separate processes. In the code below I use mclapply with myload function that loads the Rdata file and returns the object loaded. The difference with your lapply version is that you have the data in the list returned by mclapply
myload <- function(x){
x <- load(x)
get(x)
}
a = "aa.RData"; b = "bb.RData"; c = "cc.RData"; d = "dd.RData"
res <- mclapply(c(a, b, c, d), myload, mc.cores = parallel::detectCores());
| {
"pile_set_name": "StackExchange"
} |
Q:
No input validation in node webkit (nw.js) based app
This is my HTML code
<input type="text" required="" placeholder="Username">
which basically make the username necessary for form submission and displays a tooltip for the field if left black on submission.
The HTML Page works fine, output:
However on running the genrated app.exe file, there are no messages, output:
My Question:
Is this a Node Webkit limitation? Are there any workarounds?
A:
This IS a nw.js limitation.
The tooltip is generated by Chrome the browser in your former image, but nw.js does not have the same version as Chrome as you are using, so its support for HTML5 stuff like this is expected to be sub-par.
I can't find any references for this claim, but this is most likely what's happening.
| {
"pile_set_name": "StackExchange"
} |
Q:
Print text after 7th occurrence of delimiter in unix
I have text file that follows this format:
name loc - u q1:a|b|c|d|e|f|g|h q2:i|j|k|l|m|n|o|p
For each line, I want to extract the text after the 7th occurrence of "|" for each "q" in that line. In other words, I want to print something like this:
q1 q2
name h p
Is there a way I can do this with awk or grep without a loop?
Thanks in advance!
A:
I think the whitespace between fields are tabs. Since you are using q1 and q2 as headers, I guess they appear set on each line.
First you need to cut out the second, third and fourth field. cut is easy here.
For each remaining field you need the same sed-operation. Something like
echo "name loc - u q1:a|b|c|d|e|f|g|h q2:i|j|k|l|m|n|o|p" | cut -f1,5- |
sed 's/[^\t]*:\([^|]*|\)\{7\}/ /g'
| {
"pile_set_name": "StackExchange"
} |
Q:
interpret everything after LeftBracket as a string until next RightBracket
[Solution]
on the bottom under Edit3
I am currently developring a new grammar (from certain requirements which I cannot change) and the following requirement poses a problem, I cannot solve at the moment. I am using Antlr4 with the C# target.
The syntax is as follows:
print [blabla ]
so everything inside the brackets is considered a string. So also this:
print [3 + 2]
will print
3 + 2
Now I have lexer rules which will obviously match the 3 as an Integer. So how can I create a parser rule which will parse anything until a ']' is found? I currently have the following production:
control
:
| Print expr
| Print LeftBracket printArg RightBracket
;
the problem I am facing is that the left bracket does not always start a string. Sometimes (eg in while) the condition is also in brackets. I thought about just accepting every Lexer rule until the RightBracket is reached and then generate the string at runtime when I use the generated parse tree, but seems to me very annoying and I would need to insert the whitespaces later on which will be difficult.
If you need more parts of my grammar just ask in a comment and I will provide you with more details
Kind regards
Lukas
EDIT: more information about my grammar:
The following production use brackets:
Print LeftBracket printArg RightBracket
Repeat IntegerConstant LeftBracket body RightBracket
While LeftBracket expr RightBracket LeftBracket body RightBracket
If expr LeftBracket body RightBracket LeftBracket body RightBracket
SetPos LeftBracket IntegerConstant IntegerConstant RightBracket
EDIT2:
So I tried to use the modes but I got problems on returning from them. These are the code lines I have regarding the modes:
mode printMode;
WhitespacePrint
: [ \t]+
-> skip
;
LeftBracketPrint : '[' -> popMode, pushMode(stringMode);
NotLeftBracket : ~'[' -> popMode;
mode stringMode;
String : ~']'+;
RightBracketPrint: ']' -> popMode;
And I added a pushMode(printMode) on the Print lexer rule (matches the keyword)
Now parsing print [ 1 + 2] creates a single token containing the whole string inside the brackets. Now when I use print 1 + 2 (which should output 3), I get a no viable alternative ar input 'print1' exception, since the '1' has a type of NotLeftBracket. How can I switch the mode without consuming the input?
EDIT3:
Next I tried to use some inline code and use lookahead which finally solved my problem:
mode printMode;
LeftBracketPrint : [ \t]+ '[' -> popMode, pushMode(stringMode);
WhitespacePrint
: [ \t]+ {_input.La(1) != '['}?
-> skip, popMode
;
mode stringMode;
String : ~']'+;
RightBracketPrint: ']' -> popMode;
A:
I would start by treating everything inside brackets as a BracketLiteral in the lexer.
LeftBracket : '[' -> pushMode(BracketLiteralMode);
mode BracketLiteralMode;
BracketLiteral : ~']'+;
RightBracket : ']' -> popMode;
Before determining how the special cases would be handled, I would then enumerate every last possibility for where an exception to the BracketLiteral rule could appear in the grammar. If you can add those details, I would be able to make some suggestions regarding how to handle those cases.
| {
"pile_set_name": "StackExchange"
} |
Q:
cannot connect to fresh installed gitlab 7.0 on CentOS 6.5
When i try to connect with ssh to the fresh installed gitlab he ask for a password. the http is working aswel the webinterface.
I have already added the rsa key to gitlab but it looks like the openssh server not use the gitlab authorized_keys file.
Gitlab version 7.0
installed fresh CentOS 6.5 and followed this commands:
wget https://downloads-packages.s3.amazonaws.com/centos-6.5/gitlab-7.0.0_omnibus-1.el6.x86_64.rpm
sudo yum install openssh-server
sudo yum install postfix # Select 'Internet Site', using sendmail or exim is also OK
sudo rpm -i gitlab-7.0.0_omnibus-1.el6.x86_64.rpm
sudo -e /etc/gitlab/gitlab.rb
(added my hostname)
sudo gitlab-ctl reconfigure
sudo lokkit -s http -s ssh
A:
I had the same issue on GitLab 7 omnibus on CentOS 6.5: after a fresh install, when I git push git@.... it was asking for a password. I fixed it by changing the permissions on .ssh folder and .ssh/authorized_keys:
yum install policycoreutils-python -y
chmod 700 /var/opt/gitlab/.ssh/
chmod 600 /var/opt/gitlab/.ssh/authorized_keys
semanage fcontext -a -t ssh_home_t "/var/opt/gitlab/.ssh"
semanage fcontext -a -t ssh_home_t "/var/opt/gitlab/.ssh/authorized_keys"
restorecon -R -v /var/opt/gitlab/.ssh/
You will probably need policycoreutils-python package to run semanage. Install it with yum if needed !
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I do a sum in python for n+(n+12)+(n+24)+(n+36) and then for (n+1)+(n+13)+(n+25) and so on until reaching n+12?
So lets say I have monthly data and I am trying to find a type of monthly change but the monthly change I want would be the following having this data frame the one I have is much bigger having every month from 2010 to 2019.
axis Month Date Value
1 1-2012 10
2 2-2012 11
3 3-2012 15
4 1-2013 12
5 2-2013 13
6 3-2013 17
7 1-2014 15
8 2-2014 16
9 3-2014 20
I want to arrive to an output such as
axis value_sum
1. 37
2. 40
3. 52
1.which is equal as the sum of axis(1+4+7)
2.which is equal as the sum of axis(2+5+8)
3.which is equal as the sum of axis(3+6+9)
so at the end I will have just 12 numbers as an output.
Iv been trying to do this as with def and defining a function but when getting to this part I simply dont know what to do.
I actually am pretty new with managing data frames with python/pandas so I would appreciate the help.
A:
Assuming 'Month Date' is a string, group by quarter (extracted by .str[:1]) and sum:
df['Value'].groupby(df['Month Date'].str[:1]).sum()
If first part is a month (can be two digit):
df['Value'].groupby(df['Month Date'].str.split('-').str.get(0)).sum()
| {
"pile_set_name": "StackExchange"
} |
Q:
Updating one field per row, 1 million + rows
I have a large address database I need to "clean up".
Example, the address contains the county but not always in the same field, sometimes its in address3 and sometimes address4 or not at all.
I've put everything in a table, created a new field called County and the php loads the data (1000 rows at a time for testing) into an array.
It searches for "CO." in address3 or 4 and if found then copies the contents of that cell to "County". So far so good.
The problem is that it runs extremely slow, I use the following as the UPDATE:
$update = "UPDATE opportunities SET County='" . $address4 . "' " . "WHERE id=" . $id;
Is there a faster way to do this than running the above line for each entry?
A:
It would be faster to do it directly in SQL, but by its nature this sort of string searching will be pretty slow:
UPDATE opportunities
SET County = CASE
WHEN address3 LIKE '%CO.%' THEN address3
WHEN address4 LIKE '%CO.%' THEN address4
END
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert 5V to 3.3V without logic level converter
I've got a 2.2 SPI monitor (QVGA TFT monitor & SD Card), but I am using Arduino UNO board. All pins are 5V. How can I use a resistor to communicate between TFT, SD and UNO?
I have lots of different Ohm resistors, and have 3 Logic Level Converter (non bi-direction).
I try the LLC connect to TFT, but no luck, it just has the backlight ON, nothing I can see.
Thanks TJ, I had wired with this circuit, but the voltage seems not enough 3V. Am I something go wrong?
simulate this circuit – Schematic created using CircuitLab
Also, I have try to change R1 to 330 ohm & R2 to 680 ohm. Seems also cannot convert to 3V / 3.3V
A:
You can use a simple voltage divider to make 3,3V from 5V. 3,3v is high enough for the arduino to detect it as a high input.
Take for r2 470 ohm and for r1 220 ohm.
| {
"pile_set_name": "StackExchange"
} |
Q:
do assertations exist in both JAVA and JUnit?
I am looking at one of the question that is posted long back by x person.
Ex: assertEquals(driver.getPageSource().contains("sometext"), true);
(or) assertEquals(boolean , boolean);
If the above method exists I love to use it. I looked around JUnit API and its methods and there is no such method .
1) If it exists can someone post the relevant link, please ?
2) do assertations exist in JAVA default classes? (I know they are there in JUNIT)
A:
Why not use assertTrue(driver.getPageSource().contains("sometext"));?
A:
If you want to do assertions in your main Java code (say for a sanity check), you can use the assert keyword. Methods like assertTrue() and assertEquals() from JUnit are meant to be used in JUnit-based unit testing code.
A:
The assertEquals methods are in JUnit, specifically in the org.junit.Assert class:
You typically import them with a static import statement like this:
import static org.junit.Assert.*;
assert on its own is part of core Java, it provides a way to add sanity checks that get run while you are debugging, but which get ignored (and therefore don't add any overhead) in production code.
assert(something==somethingElse);
| {
"pile_set_name": "StackExchange"
} |
Q:
Export only select feature properties to a CSV file from Earth Engine
I want to calculate the number of fires for a region and export the result to Google Drive as a CSV file. The code I'm using to do this seems to work, but the object fire_ind_count contains many additional properties besides fire count. How can I alter my code to obtain an object with only the count of fires to export?
// Load country shapefile
var lsib = ee.FeatureCollection("USDOS/LSIB_SIMPLE/2017");
var vn_shape = lsib.filterMetadata('country_na', 'equals', 'Argentina');
print (vn_shape);
// Load fire counts image
var fire = ee.ImageCollection('FIRMS')
.filterBounds(vn_shape)
.filterDate('2019', '2020');
var scale = fire.first().projection().nominalScale();
// Filter fire with more than 50% confidence and add a new band representing areas where confidence of fire > 50%
var filterConfidence = function(image) {
var line_number = image.select('line_number');
var confidence = image.select('confidence');
var conf_50 = confidence.gt(50).rename('confidence_50');
var count_band = line_number.updateMask(conf_50).rename('count');
return image.addBands(count_band);
};
var fire_conf = fire.map(filterConfidence);
print('fire_conf', fire_conf);
// Count for individual image.
var countIndividualImg = function(image) {
var countObject = image.reduceRegion({
reducer: ee.Reducer.countDistinct(),
scale: scale,
geometry: vn_shape,
maxPixels: 1e9
});
return image.set(countObject);
};
var fire_ind_count = fire_conf.map(countIndividualImg);
print('fire_ind_count', fire_ind_count);
Export.table.toDrive({
collection: fire_ind_count,
description: 'FireCountsInAustralia_gt50_conf'});
A:
By default, all properties of a collection will be exported. You can use the selectors argument to specify the properties you want to export.
Export.table.toDrive({
collection: fire_ind_count,
description: 'FireCountsInAustralia_gt50_conf',
selectors:['count']
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Facebook 'NoneType object error'
I am new to programing and python. I wrote this script below and I am getting a "TypeError: 'NoneType' object is not iterable"
import csv
import json
import urllib
import sys
import time
import re
class FacebookSearch:
def __init__(self,
query = '"https://graph.facebook.com/search.{mode}?{query}&{access_token}'
):
access_token = 'XXXXX|XXXXX'
def search(self, q, mode='json', **queryargs):
queryargs['q'] = q
query = urllib.urlencode(queryargs)
def write_csv(fname, rows, header=None, append=False, **kwargs):
filemode = 'ab' if append else 'wb'
with open(fname, filemode) as outf:
out_csv = csv.writer(outf, **kwargs)
if header:
out_csv.writerow(header)
out_csv.writerows(rows)
def main():
ts = FacebookSearch()
response, data = ts.search('appliance', result_type='recent') #I am getting the error on this line
js = json.loads(data)
messages = ([msg['created_time'], msg['id']] for msg in js.get('data', []))
write_csv('fb_washerdryer.csv', messages, append=True)
if __name__ == '__main__':
main()
I am not sure why I am getting the "TypeError: 'NoneType' object is not iterable" on the line where I am defining my search term for the graph API.
A:
Add return query at the end of FacebookSearch's search method. You are actually asking it to unpack None which search is current returning. When a function has no explicitly defined return it defaults to return None.
>>> response, data = None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable
| {
"pile_set_name": "StackExchange"
} |
Q:
Apache write permissions ( Drupal module unable to write/create css/js files)
I'm using a Drupal module called 'Code Per Node'. It allows basically what the name describes: custom code in the form of JS or CSS on a per node basis. Upon publishing the node, the module writes the css and js to a file specified in the module's configuration settings.
In development, I have the directory set to /cpn, I've temporarily made the permissions for that folder 0777 just to cover all angles.
The problem is, I've moved the site to a staging server and something about the environment is restricting the module from writing the CSS and JS files. it returns a 'The file could not be created' error upon publishing.
I've tried: Setting open permissions and moving directory inside of /sites/default, no dice.
Is there anything else I should look at that would prevent this module from writing these files? Perhaps an Apache config setting?
As a side note, I would much prefer the custom code be generated inline on the page, so if anyone knows any actively supported modules that accomplish this, that would also be much appreciated.
Thanks
A:
Problem was that the tmp directory for Drupal was still set to a local path.
| {
"pile_set_name": "StackExchange"
} |
Q:
SELECT Data FROM CURSOR of PACKAGE, print it
I want to print data of Cursor_pkg.c1.row_emp, for ex:Cursor_pkg.c1.row_emp.last_name that would be exist in Cursor_pkg.row_emp after Cursor_pkg_func.Print_Cur procedure would work. How can I do it?
I create PACKAGE with cursor and rec
I create PACKAGE with procedure that fetch cursor data in rec
I want to output fetched data. How?
There is two questions: I want to output data from package emp_rec (row) and I want to output it directly from PACKAGE Cursor_pkg_func procedure
P.S. The main idea is storing data and procedure/function for fetching and selecting data
CREATE OR REPLACE PACKAGE Cursor_pkg AUTHID DEFINER IS
CURSOR C1 IS
SELECT last_name, job_id FROM employees
WHERE job_id LIKE '%CLERK%' AND manager_id > 120
ORDER BY last_name;
row_emp C1%ROWTYPE;
END Cursor_pkg;
/
CREATE OR REPLACE PACKAGE Cursor_pkg_func IS
PROCEDURE Print_Cur;
END Cursor_pkg_func;
/
CREATE OR REPLACE PACKAGE BODY Cursor_pkg_func IS
PROCEDURE Print_Cur IS
BEGIN
OPEN Cursor_pkg.C1;
LOOP
FETCH Cursor_pkg.C1 INTO Cursor_pkg.row_emp;
EXIT when Cursor_pkg.C1%NOTFOUND;
DBMS_OUTPUT.put_line(Cursor_pkg.row_emp.last_name);
END LOOP;
CLOSE Cursor_pkg.C1;
END;
END;
/
BEGIN
Cursor_pkg_func.Print_Cur;
END;
But I want to select and print from Cursor_pkg.row_emp PACKAGE without created function.
And how to print not only last_name but all row?
Errors start with: What's wrong with last three statements?
CREATE OR REPLACE PACKAGE Cursor_pkg_func IS
TYPE outrec_typ IS RECORD (
var_char2 VARCHAR2(30)
);
TYPE outrecset IS TABLE OF outrec_typ;
FUNCTION f_trans (p in number ) RETURN outrecset PIPELINED;
END Cursor_pkg_func;
/
CREATE OR REPLACE PACKAGE BODY Cursor_pkg_func IS
FUNCTION f_trans (p in number) RETURN outrecset PIPELINED IS
out_rec outrec_typ;
BEGIN
OPEN Cursor_pkg.C1;
LOOP
FETCH Cursor_pkg.C1 INTO Cursor_pkg.row_emp;
EXIT when Cursor_pkg.C1%NOTFOUND;
END LOOP;
LOOP
out_rec.var_char2 := Cursor_pkg.row_emp.last_name;
PIPE ROW(out_rec);
DBMS_OUTPUT.put_line(out_rec.var_char2);
END LOOP;
CLOSE Cursor_pkg.C1;
RETURN;
END f_trans;
END Cursor_pkg_func;
/
begin
Cursor_pkg_func.f_trans(5);
end;
/
A:
You have defined a pipelined function, and this is not the way to call it:
SQL> begin
2 Cursor_pkg_func.f_trans(5);
3 end;
4 /
Cursor_pkg_func.f_trans(5);
*
ERROR at line 2:
ORA-06550: line 2, column 1:
PLS-00221: 'F_TRANS' is not a procedure or is undefined
ORA-06550: line 2, column 1:
PL/SQL: Statement ignored
SQL>
You need to use a TABLE() function. Although then you will discover the bug in your code:
SQL> select * from table(Cursor_pkg_func.f_trans(5))
2 /
SMITH
SMITH
SMITH
''''
SMITH
SMITH
SMITH
SMITH
ERROR:
ORA-00028: your session has been killed
273660 rows selected.
SQL>
Note I had to kill that session from another session, otherwise it would still be running. So let's simplify the function and get rid of that pointless second loop ....
CREATE OR REPLACE PACKAGE BODY Cursor_pkg_func IS
FUNCTION f_trans (p in number) RETURN outrecset PIPELINED IS
out_rec outrec_typ;
BEGIN
OPEN Cursor_pkg.C1;
LOOP
FETCH Cursor_pkg.C1 INTO Cursor_pkg.row_emp;
EXIT when Cursor_pkg.C1%NOTFOUND;
out_rec.var_char2 := Cursor_pkg.row_emp.last_name;
PIPE ROW(out_rec);
END LOOP;
CLOSE Cursor_pkg.C1;
RETURN;
END f_trans;
END Cursor_pkg_func;
/
.... then lo!
SQL> select * from table(Cursor_pkg_func.f_trans(5))
2 /
VAR_CHAR2
------------------------------
ADAMS
JAMES
MILLER
SMITH
SQL>
"When I add begin and end; select not work"
You have created a pipelined function. Why did you do that? The reason you ought to have done that was because you wanted a PL/SQL function which could be used in the FROM clause of a SELECT statement. That is the use case for pipelined functions. So putting the call into an anonymous PL/SQL block really doesn't make sense.
But anyway.
Please read the documentation. It is quite comprehensive, it is online and free. The pertinent section in the PL/SQL Reference is the chapter on Static SQL. It makes clear that SELECT statements in PL/SQL must always fetch records into a variable of some description. Anonymous PL/SQL blocks are just the same as stored procedures in this regard. Find out more.
| {
"pile_set_name": "StackExchange"
} |
Q:
Given the conditions above, find when $x$, $y$, $z$ satisfy below: $ (x^2-1)(y+1)=\dfrac{z^2+1}{y-1}$
Let $x,y,z \in \mathbb{Z^+}$ and $x \neq y \neq z$.
Given the conditions above, find when $x$, $y$, $z$ satisfy below:
$$ (x^2-1)(y+1)=\frac{z^2+1}{y-1}\,.$$
What I did was I factored the numerator to
$$(x+1)(x-1)(y+1)=\frac{z^2+1}{y-1}\,,$$
but I am having trouble figuring out how to isolate the variables. I tried some values with trial and error and wasn't able to get any.
A:
Multiply both sides by $y-1$, expand, and simplify. You then have several relatively easy ways to attack the question. Is that enough to go on?
| {
"pile_set_name": "StackExchange"
} |
Q:
git move portion of old repository to a new repository
I've a repository which contains several directories at the root, e.g.
gitroot/a
gitroot/b
gitroot/c
And I would like to create a new git repository from only the contents of a, whilst retaining its history. Is this possible? I've seen the sparse checkouts, but I'm not sure how I could use this to create a brand new repository (with relevant history) from a subdirectory.
A:
After cloning your existing repository, you can use filter-branch
git filter-branch --subdirectory-filter a -- --all
After that;
git clean -d -f // Remove untracked files from the working tree
git gc --aggressive // Cleanup unnecessary files and optimize the local repository
git prune // Prune all unreachable objects from the object database
| {
"pile_set_name": "StackExchange"
} |
Q:
Training broke with ResourceExausted error
I am new to tensorflow and Machine Learning. Recently I am working on a model. My model is like below,
Character level Embedding Vector -> Embedding lookup -> LSTM1
Word level Embedding Vector->Embedding lookup -> LSTM2
[LSTM1+LSTM2] -> single layer MLP-> softmax layer
[LSTM1+LSTM2] -> Single layer MLP-> WGAN discriminator
Code of he rnn model
while I'm working on this model I got the following error. I thought My batch is too big. Thus I tried to reduce the batch size from 20 to 10 but it doesn't work.
ResourceExhaustedError (see above for traceback): OOM when allocating
tensor with shape[24760,100] [[Node:
chars/bidirectional_rnn/bw/bw/while/bw/lstm_cell/split =
Split[T=DT_FLOAT, num_split=4,
_device="/job:localhost/replica:0/task:0/device:GPU:0"](gradients_2/Add_3/y,
chars/bidirectional_rnn/bw/bw/while/bw/lstm_cell/BiasAdd)]] [[Node:
bi-lstm/bidirectional_rnn/bw/bw/stack/_167 =
_Recvclient_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0",
send_device="/job:localhost/replica:0/task:0/device:GPU:0",
send_device_incarnation=1,
tensor_name="edge_636_bi-lstm/bidirectional_rnn/bw/bw/stack",
tensor_type=DT_INT32,
_device="/job:localhost/replica:0/task:0/device:CPU:0"]]
tensor with shape[24760,100] means 2476000*32/8*1024*1024 = 9.44519043 MB memory. I am running the code on a titan X(11 GB) GPU. What could go wrong? Why this type of error occurred?
* Extra info *: the size of the LSTM1 is 100. for bidirectional LSTM it becomes 200.
The size of the LSTM2 is 300. For Bidirectional LSTM it becomes 600.
*Note *: The error occurred after 32 epoch. My question is why after 32 epoch there is an error. Why not at the initial epoch.
A:
I have been tweaking a lot these days to solve this problem.
Finally, I haven't solved the mystery of the memory size described in the question. I guess while computing the gradient tensoflow accumulate a lot of additional memory for computing gradient. I need to check the source of the tensorflow which seems very cumbersome at this time. You can check how much memory your model is using from terminal by the following command,
nvidia-smi
judging from this command you can guess how much additional memory you can use.
But the solution to these type of problem lies on reducing the batch size,
For my case reducing the size of the batch to 3 works. This may vary
model to model.
But what if you are using a model where the embedding matrix is much bigger that you cannot load them into memory?
The solution is to write some painy code.
You have to lookup on the embedding matrix and then load the embedding to the model. In short, for each batch, you have to give the lookup matrixes to the model(feed them by the feed_dict argument in the sess.run()).
Next you will face a new problem,
You cannot make the embeddings trainable in this way. The solution is to use the embedding in a placeholder and assign them to a Variable(say for example A). After each batch of training, the learning algorithm updates the variable A. Then compute the output of A vector by tensorflow and assign them to your embedding matrix which is outside of the model. (I said that the process is painy)
Now your next question should be, what if you cannot feed the embedding lookup to the model because it's so big. This is a fundamental problem that you cannot avoid. That's why the NVIDIA GTX 1080, 1080ti and NVIDA TITAN Xp have so price difference though NVIDIA 1080ti and 1080 have the higher frequency to run an execution.
A:
*Note *: The error occurred after 32 epoch. My question is why after 32 epoch there is an error. Why not at the initial epoch.
This is a major clue that the graph is not static during execution. By that I mean, you're likely doing sess.run(tf.something) instead of
my_something = tf.something
with tf.Session() as sess:
sess.run(my_something)
I ran into the same problem trying to implement a stateful RNN. I would occasionally reset the state, so I was doing sess.run([reset if some_condition else tf.no_op()]). Simply adding nothing = tf.no_op() to my graph and using sess.run([reset if some_condition else nothing]) solved my problem.
If you could post the training loop, it would be easier to tell if that is what's going wrong.
| {
"pile_set_name": "StackExchange"
} |
Q:
Quadratic Problem with 2 constraints
Could someone help me to solve the following:
$\min x^Tx$
s.t.
$x^T a=1$
$x^T b=0$
where $x$,$a$ and $b$ are $(N\times1)$ vectors and $1$ and $0$ scalars.
Thank you!
A:
The stated problem is finding the minimum norm point in an underdetermined set of equations, see http://www.math.usm.edu/lambers/mat419/lecture15.pdf
This problem is a special case of the least squares problem with equality constraints, see http://inst.eecs.berkeley.edu/~ee127a/book/login/l_ols_variants.html
Let me solve the problem:
Let $C = [a,b]^T$ and $c = [1,0]^T$ such that your problem becomes
$$\min_{x} \|x\|^2 ~~~~~{\rm s.t. }~~~ Cx =c $$
then, the solution is given by
$x^\star = C^T(C C^T)^{-1}c$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting up NSTableView with NSMutableArray of custom classes as data source
Alright, so I'm learning programming in Objective-C and Cocoa, and I've run into a problem in the project I'm working on. So in my code, I have a NSMutableArray (sources) of objects of a custom class. Each object has a NSString name. I'm trying to get a table view to display all the objects in sources, by the name of each object.
I have the app delegate class following the NSTableViewDataSource protocol, which means having an objectValueForTableColumn method, and a numberOfRowsInTableView method.
In numberOfRowsInTableView, I just have a return [sources count]; statement, and it works fine.
In objectValueForTableColumn, I have return [[sources objectAtIndex: rowIndex] name];, but nothing is displayed.
I have added a lot of NSLog statements for debugging, and I think I know what the problem is, but I don't know why, or how to fix it.
So, inside objectValueForTableColumn, the sources array is nil. Inside, numberOfRowsInTableView, sources is active, and that method works fine. Now, both these methods run many times, and every time, sources is active in numberOfRowsInTableView, but nil in objectValueForTableColumn.
I replaced the return statement in objectValueForTableColumn with return @"Test string.";, and it displays the correct number of rows in the table view. Because of this, I know that the table view is set up correctly, besides the problem I am having with sources.
I can't figure out why sources works in one method, but not the other. I also haven't found a solution to get my table view working correctly. Any help or insight would be appreciated.
Thanks,
Alex
edit:
- (void) loadFromFile
{
NSString *filePath = @"/Users/alex/opt/Wallify.plist";
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: filePath])
{
NSData *data = [[NSData new] initWithContentsOfFile: filePath];
NSLog(@"Loaded data from file.");
self.sources = [NSKeyedUnarchiver unarchiveObjectWithData: data];
[data release];
for ( ATImageSource *i in sources)
{
NSLog(@"retaining i");
[i retain];
}
[sources retain];
NSLog(@"&imgsrc: %p", sources);
NSLog(@"imgsrc: %@", sources);
NSLog(@"Name: %@",[[sources objectAtIndex: 0] name]);
}
else
{
// Saved settings file does not exist
// Load defaults
self.sources = [[NSMutableArray alloc] initWithArray: nil];
[self.sources retain];
// new code to setup testfoldersrc
ATFolderSource *f = [ATFolderSource new];
f.name = @"Documents";
f.source = @"/Users/alex/Documents/";
f.localPath = @"/Users/alex/Documents/";
f.type = @"f";
[f populateArrayFromLocalPath];
[self.sources addObject: f];
[f release];
// new code to setup testrsssrc
ATRSSSource *r = [ATRSSSource new];
r.name = @"NASA Large Image of the Day";
r.source = @"http://www.nasa.gov/rss/lg_image_of_the_day.rss";
r.localPath = @"/Users/alex/opt/nasa_lg_image_of_the_day/";
r.type = @"r";
[r getImagesFromRSS];
[r populateArrayFromLocalPath];
[self.sources addObject: r];
[r release];
}
}
A:
I suspect it's a race condition in which the array is not populated correctly before NSTableView requests the display data, or something is messing with it in the meantime.
At any rate, there is probably a better way to do this using an NSArrayController. Apple has a detailed tutorial that can even do sub-arrays of the array (Master/Detail views). It's mostly some point and click work, and maybe as advanced as an override or two. Check it out at http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaBindings/Tasks/masterdetail.html.
Using this method should also provide things like sorting and filtering for free, as well as easier maintenance (depending on your viewpoint).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to clean up this jQuery snippet correctly
I'm using this jQuery snippet to change the background position of a image, when the links are hovered. But I have to add alot more selectors to it, and it's going to take up alot of lines this way, but I cannot seem to find a way to minify it? Can it be done? Or maby there is a more correct way to do this background changing?
<script type ="text/javascript">
jQuery(function(){
jQuery(".1-panel").hover(function(){
jQuery(".panel-image").css('background-position','0px -135px');
});
jQuery(".2-panel").hover(function(){
jQuery(".panel-image").css('background-position','0px 0px');
});
jQuery(".3-panel").hover(function(){
jQuery(".panel-image").css('background-position','0px -265px');
});
jQuery(".4-panel").hover(function(){
jQuery(".panel-image").css('background-position','0px -560px');
});
jQuery(".5-panel").hover(function(){
jQuery(".panel-image").css('background-position','0px -410px');
});
});
</script>
A:
I'll add a common class like panel to all the 5 elements 1-panel, .... 5-panel, also add an additional data-* attribute like data-imagebp like
<div class="1-panel panel" data-imagebp="0px -135px">...</div>
<div class="2-panel panel" data-imagebp="0px 0px">...</div>
...
<div class="5-panel panel" data-imagebp="0px -410px">...</div>
then
jQuery(function ($) {
var $pimage = $(".panel-image");
$(".panel").mouseenter(function () {
$pimage.css('background-position', $(this).data('imagebp'));
});
});
Note: There is no need to use hover() here as you are not doing anything in mouse leave event, so you can just register the mouseenter handler
| {
"pile_set_name": "StackExchange"
} |
Q:
Выборка максимальной даты из двух таблиц с одинаковой структурой
Даны две таблицы с одинаковой структурой:
Таблица 1 - Приём наличных:
CREATE TABLE IF NOT EXISTS `cashreceiving` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`idaccount` int(10) unsigned NOT NULL,
`dateop` date NOT NULL,
`timeop` time NOT NULL,
`accepted` double NOT NULL,
`monebalance` double NOT NULL,
`moneytype` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;
Таблица 2 - Выдача наличных:
CREATE TABLE IF NOT EXISTS `cashwithdrawal` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`idaccount` int(10) unsigned NOT NULL,
`dateop` date NOT NULL,
`timeop` time NOT NULL,
`accepted` double NOT NULL,
`monebalance` double NOT NULL,
`moneytype` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
Необходимо найти остаток на счете (monebalance) исходя из максимальной даты (dateop) и времени (timeop) в обоих таблицах.
Запрос на одну таблицу примерно следующий:
SELECT
`cashreceiving`.`idaccount` ,
MAX( `cashreceiving`.`dateop` ) ,
MAX( `cashreceiving`.`timeop` ) ,
MAX( `cashreceiving`.`monebalance` ) AS maxmoney
FROM `cashreceiving`
WHERE `cashreceiving`.`idaccount` =1
Где idaccount - это имя счета.
A:
Если я правильно понял задачу, то одна запись с максимальной датой/временем из двух таблиц может быть выбрана так:
select idaccount,dateop,timeop,monebalance
from
(
select * from (
select * from cashreceiving
where idaccount=1
order by dateop desc,timeop desc
limit 1
) A
union
select * from (
select * from cashwithdrawal
where idaccount=1
order by dateop desc,timeop desc
limit 1
) B
) C
order by dateop desc,timeop desc
limit 1
А вообще с такой структурой таблиц, готовьтесь возмещать убытки клиентам или заказчикам. Во первых, double это число с плавающей точкой, в нем точность числа не гарантирована. Т.е. деньги в нем в принципе хранить нельзя. Используйте decimal или в копейках храните в целочисленных полях (int). Во вторых, хранение текущего баланса в виде числа, которое ищется по максимальным датам в двух таблицах очень спорное решение. Мне даже сложно представить, какая у вас логика в приложении будет накручена, что бы этот баланс правильно вычислять. И если при такой логике не следить или не правильно следить за транзакциями и блокировками, то будет масса проблем с одновременной модификацией одних и тех же данных. В конечном счете код, который будет обеспечивать данную логику потенциально будет содержать ошибки, ведущие к неправильным вычислениям баланса.
Наиболее надежным способом хранения денежных операций является одна таблица со всеми операциями по счету, причем только со значениями конкретной текущей операции, + или - в ней разумеется должен быть "вид транзакции" по которому можно будет понять, что это за операция. Со временем кроме просто "поступления" и "списания" может появится масса разновидностей начислений/списаний. Так же к транзакции можно хранить id-ссылки на первичные документы, на основании которых прошли операции (если нужны), хранящиеся в своих таблицах, со своей спецификой для конкретных операций. И самое главное - текущий баланс аккаунта по такой таблице получается как абсолютная сумма всех операций в таблице по данному id аккаунта. Вычислить неправильно невозможно. Не учесть совместный доступ так же практически нереально, т.к. записи просто добавляются и никогда не модифицируются. Единственное, может со временем появится отправка записей в архив, с выведением начального сальдо и внесением его в эту таблицу одной записью. Ну тут надо будет просто аккуратно в одной транзакции реализовать.
И кстати в mysql есть замечательный тип данных datetime позволяющий хранить дату/время в одной колонке.
| {
"pile_set_name": "StackExchange"
} |
Q:
Integrals and bijective functions
Assume that $f: [a, b] \rightarrow [a,b]$ is continuously differentiable bijection and that $f(a) = a$, $f(b) = b$.
Show that
$$\int_a^b g(x) \, dx + \int_a^b f(x) \, dx = b^2-a^2$$
where $g:[a, b] \rightarrow [a, b]$ is the inverse function of $f$
With this one I have no idea where to start. What should we do with the information about $f$ being bijective and $g$ being the inverse of $f$?
A:
Let $u=f^{-1}(x)$. Then $x=f(u)$ and $dx=f'(u)\,du$. We will integrate by parts:
$$\int_a^b g(u) h'(u)du = \left[g(u)h(u)\right]_a^b-\int_a^b g'(u)h(u)du$$
by choosing $g(u)=u$ and $h(u)=f(u)$, so:
$$
\begin{aligned}
\int_a^b u f'(u)du &= \left[uf(u)\right]_a^b-\int_a^b 1\cdot f(u)du\\
&=bf(b)-af(a)-\int_a^b f(u)\,du
\end{aligned}
$$
Since $f(b)=b$ and $f(a)=a$, we have:
$$bf(b)-af(a)=b^2-a^2$$
Chaining all this together:
$$
\begin{aligned}
\int_a^b f^{-1}(x)\,dx&=\int_a^b uf'(u)\,du\\
&=\int_a^b u(f(u))'\,du\\
&= \left[uf(u)\right]_a^b-\int_a^b f(u)\,du\\
&=b^2-a^2-\int_a^bf(x)\,dx
\end{aligned}
$$
from which we deduce the conclusion.
A:
Suppose for convenience $0<a<b.$ Draw a picture. The area between the graph of $f$ and the $x$-axis is $\int_a^b f(x)\, dx.$ Same for $g$ with respect to the $y$-axis. If we add these two areas, we get the area of $[0,b]\times [0,b]$ minus the area of $[0,a]\times [0,a],$ which is $b^2-a^2.$
| {
"pile_set_name": "StackExchange"
} |
Q:
What are some techniques to safely handle both 32bit and 64bit pointers without a conditional macro?
I'm updating some code in a library because i've found out my original code assumed 32bit pointers. I have my own thinkings on how to fix it, but for thoroughness, I want to ask what are some techniques you would use to make this code work for both 32bit and 64bit without a macro?
char *argList = (char *)malloc(sizeof(id *) * argumentsCount);
sizeof(id *) is 4 on 32bit, 8 on 64bit. I'm using char *argList to build an array of pointers to objects, then using NSArray's getObjects method:
[myNSArray getObjects:(id *)argList];
works in 32bit, crashes in 64bit (for obvious reasons)
A:
Though I don't have all of the context, I suspect that this isn't really a 32/64 bit problem. What you probably want is something along the lines of:
id *argList = malloc(sizeof(id) * argumentsCount);
Depending on the situation, I sometimes like to allocate blocks of memory like this with the allocation already zero'd out:
id *argList = calloc(1UL, sizeof(id) * argumentsCount);
Both of these allocate a chunk of memory capable of holding argumentsCount number of pointers to objects. You can access the individual pointers like so:
argList[0] = [[NSString alloc] initWithUTF8String:argv[0]];
argList[1] = [[NSString alloc] initWithUTF8String:argv[1]];
NSLog(@"Argument 0 is: %@", argList[0]);
When you declare argList as a pointer to char type, as you did in your example, indexing individual elements (ie, argList[0], argList[1]), will access the individual bytes of the memory allocated for argList, not the individual pointers as you're probably expecting. When you declare argList as id, as I did in the above, indexing individual elements steps through the memory allocated for argList by sizeof(id) bytes. The compiler will automatically compensate for the correct pointer size for the target architecture.
Assuming that the pointer returned by malloc() is 0x1000, here's a table of the addresses that would be calculated for 32 and 64bit mode for char * and id * declarations:
32-bit: char * id * 64-bit: char * id *
argList[0]: 0x1000 0x1000 0x1000 0x1000
argList[1]: 0x1001 0x1004 0x1001 0x1008
I have no idea why this ever worked for you in 32-bit mode.
| {
"pile_set_name": "StackExchange"
} |
Q:
Volley-Lib -> String cannot be converted to JSONObject with a real JSONObject
the JSONObject is this:
{"tag":"login","success":1,"error":0,"name":"pb","dir":"DH","br":"LL","gr":"IW","email":"empty"}
logcat says:
Value Access of type java.lang.String cannot be converted to JSONObject
the running an AsyncTask beside, and it works. why the volley-code says its a string? The answer from the server is a JSONObject for sure.... Why it says its a String?
private void makeJsonObjectRequest() {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
String dir = response.getString("dir");
Log.d("dir", dir);
} catch (JSONException e) {
e.printStackTrace();
Log.d("JSONException", e.getMessage().toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("onErrorResponse", error.getMessage().toString());
}
})
{
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("name", name);
params.put("password", password);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
A:
I don't know why it's append but I got the same issue with volley with the same type of request (HTTP POST + HEADER + PARAMS)
I fix it using StringRequest and parsing it manually. Try in this way
StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
Log.d(TAG, "Success "+ s.toString());
try {
JSONObject data = new JSONObject(s);
String dir = data.getString("dir");
Log.d("dir", dir);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error response " + error.getMessage());
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("name", name);
params.put("password", password);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Django Displaying data from GET request
Let's assume that I have a GET request the code below show the format of the request
Example :
/?title1=xxx&message1=xxx&file1=xxx&...&titleN=xxx&messageN=xxx&fileN=xxx
The example above display the data from the GET request.
How could I traverse the list of GET request and display each 'requestN' on it's own div.
Of course this using jinja template and django .
I actually find a solution for showing only two parameters .
{% for key, value in GET.items %}
{% if forloop.counter0|divisibleby:2 %}
{% include "title_snippet.html" with title=value %}
{% else %}
{% include "message_snippet.html" with message=value %}
{% endif %}
{% endfor %}
This solution display data only for two parameters. But I want it to work for N parameters.
?titre1=titre1&?message1=message1&?titre2=titre2&?message2=message2
A:
I don't see this being solved on template side in a easy way. You need to put some logic while rendering your template.
On your controller side.
def myview(request):
values = []
for key, value in request.GET.items():
if key.startswith("title"):
product = {}
index_value = key.replace("title","")
product["title"] = key
if request.GET.get("message"+index_value):
product["message"] = request.GET["message"+index_value]
values.append(product)
return render_to_response("template.html", {"all_values":values})
And on your template side something like
{% for value in all_values %}
<div >
{% include "title_snippet.html" with title=value.title %}
{% include "message_snippet.html" with message=value.message %}
</div>
{% endfor %}
| {
"pile_set_name": "StackExchange"
} |
Q:
faithful modules that aren't free
What are some examples of faithful modules that are not free?
It is clear that free modules are faithful but would the converse be true also?
A:
It is well-known that if an ideal of a ring is free, then it is principal. Hence, every non-principal ideal of a domain is a faithful non-free module. For example, in the ring $R:=\mathbb{Z}[x, y]$, the ideals $\langle x+n, y+m\rangle$ for all $m, n\in\mathbb{Z}$ are faithful non-free $\mathbb{Z}$-modules. By this method we can construct many examples!!!
| {
"pile_set_name": "StackExchange"
} |
Q:
Elasticsearch : 200 million aliases ?
I watched Shay Banon's talk where he brings about an interesting design pattern for creating 'per user indices'. He talks about creating a single index and using aliases with a routing key to represent each user 'index'. Is there a limit on the number of aliases you can create ?
I saw this post where somebody was having problems creating 1 million indices and explains how index templating would be a good idea to optimize things.
I am planning to work on something similar but the scale is in the order of 200 million aliases. Is this possible today ? Anybody has any numbers around it ?
Should I be thinking of a completely different design or would the same pattern hold ?
A:
you would create a huge cluster state with 200 million aliases, so I dont think that this would work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Calling JS from an applet works in Firefox & Chrome but not Safari
I have the following code in an applet to call some Javascript (it's a bit convoluted because the fn that's called gets an object from the DOM identified by divId and calls a function on it).
@Override
public final void start() {
System.err.println("start() method called");
this.javascript = JSObject.getWindow(this);
this.jsObjectDivId = getParameter("parent_div_id");
this.initCallbackFnName = getParameter("init_callback");
Object args[] = {this.jsObjectDivId, this.initCallbackFnName};
System.out.print("Calling init_callback\n");
this.javascript.call("callJS", args);
}
The callJS function is:
window.callJS = function(divId, functionName, jsonArgString) {
var args, obj;
obj = $(divId).data('neatObject');
args = eval(jsonArgString);
return obj[functionName](args);
};
In Firefox/Chrome the divId and functionName arguments contain valid strings and everything works fine; the desired function is called on the object hanging off the specified DIV data.
In Safari, the divId and functionName arguments are both reported as a JavaRuntimeObject with values of true.
> divId
JavaRuntimeObject
true
What gives?
A:
LiveConnect is not fully supported in all browsers. Especially, Safari doesn't convert Java Strings to the prober JS equivalent when using call. In your case you can just use eval at the Applet side instead of call and put in a JSON string object with the arguments. Something like:
javascript.eval(callback + "({\"id\":\"" + id + "\",\" ... })")
Basically, you need to know the cross-browser compatible subset of LiveConnect that works.
I've written a blog post that describes the subset: http://blog.aarhusworks.com/applets-missing-information-about-liveconnect-and-deployment/
It comes with a LiveConnect test suite which runs in the browser: http://www.jdams.org/live-connect-test
| {
"pile_set_name": "StackExchange"
} |
Q:
Does MQTT Support User to User Messages
I know that using MQTT topics devices can subscribe to them. But is there any way that a IoT device can send some message to a target IoT device (by device id or something) without using a topic or is there any standard topic for this scenario?
A:
There is no way to communicate without a topic, but you can create a topic for any purpose. So typically if you wanted to send a message to another client, you would publish it somewhere in the hierarchy of topics to which that client is subscribed.
That could be as simple as something like device/12345/inbound or whatever you prefer. And because topics can have hierarchy, in addition to whatever detail you put in the body, you can also encode categorization of your message into the topic, much as RESTful APIs often do in a URL.
A good reason for using target-specific (or owner-account-specific) topics is that the most easy solutions for MQTT security compartmentalization are topic-scope.
| {
"pile_set_name": "StackExchange"
} |
Q:
ReactJS - Return a component from innerHtml function
How to return a component through the JS innerHTML() function? With the code below, it is returning on the browser screen:
[object Object]
document.getElementById("threeline-icon").innerHTML =
`${<ThreelineIcon />}`
;
}
Component Code:
import React from 'react'
const ThreelineIcon = () => {
return (
<div>
<span className="top"></span>
<span className="middle"></span>
<span className="bottom"></span>
</div>
)
}
export default ThreelineIcon
A:
You can use the renderToString method used by server side rendering to convert a React component into HTML. But please keep in mind that this works only if your Component is static, I mean any events or lifecycle methods (except componentWillMount) will not work.
import ReactDOMServer from 'react-dom/server';
document.getElementById("threeline-icon").innerHTML =
ReactDOMServer.renderToString(<ThreelineIcon />);
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change a value in an array C++
This function is for code to play a game of tic tac toe:
//--------------------FUNCTION--------------------
bool playCell(int player, int position, int gameBoard[]) {
if (gameBoard[position] == 10 || gameBoard[position] == 11) {
return false;
} else {
return true;
if (player == 0){
gameBoard[position] = 10;
} else {
gameBoard[position] = 11;
} // end if
}
} // end function
playCell takes a player (0 for "O", 1 for "X"), a position (1 to 9), and the nine element gameBoard, and returns true if the move is legal (i.e. that spot is not yet taken), and false otherwise. If the move is legal it changes the position to that players number (10 for "O", 11 for "X"). If the player or position input is invalid, it returns false.
I'm trying to figure out how to get the array to change its value to either a 10 or 11 depending on the player, and saving to the position they entered to play in.
A:
The return keyword redirect the program flow back to the main program. So the code after return will not be executed. Change the position of return:
//--------------------FUNCTION--------------------
bool playCell(int player, int position, int gameBoard[])
{
if (gameBoard[position] == 10 || gameBoard[position] == 11)
{
return false;
}
else
{
if (player == 0)
{
gameBoard[position] = 10;
}
else
{
gameBoard[position] = 11;
} // end if
return true;
}
} // end function
| {
"pile_set_name": "StackExchange"
} |
Q:
How broad should our tags be?
This is after one of the discussions in chat where we had some debate over how broad or how narrow a tag scope should be.
We currently have crows, dogs et al. These are pretty narrow in scope. However, we also have birds and animals as tags. Which are much broader in scope.
Going with specifics make the tags numerous in number. For example, tomorrow if I add a question on a different species of bird, I'll be inclined to add that as a tag. And that might be the only question under the tag. And I'll have to add multiple tags to keep it relevant for searches.
Having a broader tag might keep the number of questions under the tag large. And might not give idea about the specifics of what the question is targeting (Not sure if this would be a problem for search engines).
So what's the take of our community on this. Here's a discussion on a specific tag before.
Note: I understand that the help center states that we need to prevent creating new tags if possible thereby implying specific tags might not be of any use. I'm asking for community consensus on this. The help is defined for us and we can change it based on our consensus.
A:
I also feel that having only very narrow tags is bad, whether for SEO (I no nothing about that) or just because a tag without enough questions can't really do grouping. However a new tag is by definition always a narrow tag, as there is just one question in it. So it is just the natural evolution of a tag, to start off narrow. To bridge that problem, we have 5 tag slots: Just use an applicable, broader tag and also add the new, thus narrow tag. If the narrow one attracts critical mass, using the broad one might become unnecessary for new questions (e.g. gear -> tents).
It's not that hard: Just use/add/modify what feels right on new questions, and if there is a specific disagreement take it to meta, and don't mass retag old questions (don't retag old questions at all unless there is a pressing issue).
| {
"pile_set_name": "StackExchange"
} |
Q:
Formatting SQL Data having inserted it into HTML (Webpage) using PHP
Problem - I've created a DB Connection, I've queried the DB, and I've turned the results into an associative array. Displaying the SQL Data using PHP is the trouble I'm having. I've managed to display it in a basic way, however my aim is for this information to display as a 'News Column' down the side of the page, and therefore I need the data to be inserted into Divs for me to be able to manipulate.
Attempt thus far - As one can see below, the presentation of this attempt to display my data is cringeworthy. However in this way I did manage to distinguish the types of headings for each piece of data.
echo "<h2>" . $row["title"]. "</h2><h3>Date: " . $row["dateTime"]. "</h3><h4>Passage: " . $row["passage"]. "</h4><br>";
HTML For Current Webpage:
http://i.imgur.com/9U1TWkd.png (What my 'News Column' looks like)
http://i.imgur.com/1tgA0sx.png (My HTML Code I want Data to be inputted into) - The aim is for someone to be able to complete this form (http://i.imgur.com/0xMnOVB.png) and the data to go into the DB (done this), and display in the column with the 'Title' appearing in the right place, same with 'Date' and finally with the 'Passage'.
What I've Found Online:
I dislike wasting people's time so I've spent a few hours searching online. Thus far I've found mostly people creating HTML Tables with their SQL Data, which is great and all, however I've not found anyone who's using Divs/Headings/Paragraphs etc...
My CSS:
I have a CSS File which I'm retrieving (or whatever the term is) via HTML Code which is working (so far).
A:
Interestingly, you seem to have all the components you need: An example of how the markup (the HTML) needs to be outputted and the DB query and data to inject into it. Unless I'm missing something (it's always possible!), then all that remains is for you to glue the two together.
Assuming the form represented in your most recent graphic is generated within a .php file you can either pre-build a giant variable containing all the markup necessary to render your output, or write some static HTML and insert only the dynamic elements using native PHP (PHP is itself a templating language of sorts).
Using the latter method you'd do something like the following (forgive different CSS class names and tag hierarchy, I can't copy/paste from a PNG :-)
<div class="wrapper">
<?php foreach($myResult as $row): ?>
<div class="article>
<h3><?php echo $row['Title']; ?></h3>
<div class="date"><?php echo $row['Date']; ?></div>
<p><?php echo $row['Body']; ?></p>
<div>
<?php endforeach; ?>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
UIImagePickerController in UIPopoverController is showing as blank white view
I'm currently writing an iOS app wherein I want to let the user pick an image from their photo library. I don't want them to be able to take a new photo or edit the existing one, but that's unimportant right now. Since this is an iPad app, I have to show the UIImagePickerController view in a popover view (or an exception is thrown, etc.). This is the code I am currently using to try to achieve that:
- (void)viewDidLoad{
[super viewDidLoad];
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
_picker = [[UIImagePickerController alloc] initWithRootViewController:self];
_picker.delegate = self;
}else{
[[[UIAlertView alloc] initWithTitle:@"goto fail;" message:nil delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil] show];
}
self.view.backgroundColor = [UIColor purpleColor];
}
- (void)viewDidAppear:(BOOL)animated{
popoverController = [[UIPopoverController alloc] initWithContentViewController:_picker];
[popoverController presentPopoverFromRect:(CGRect){CGPointZero, {1, 1}} inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:animated];
[super viewDidAppear:animated];
}
I expect this to show an image picker view in a popover, obviously. Instead, I get this:
This code is running on a real iPad, not in the simulator. I have never been prompted to grant access to my photos, and there is no entry for the app in the photo area of the privacy settings of Preferences.app. I am testing this on an iPad 4 (which has a camera), and cannot test in the simulator, as it is having issues at the moment. I'm not really sure where the issue could be coming from - it's quite perplexing.
A:
Also you should specify UIImagePicker's sourceType.
_picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
UPDATE
Initialise picker this way:
_picker = [[UIImagePickerController alloc] init];
| {
"pile_set_name": "StackExchange"
} |
Q:
is there a way to cast to a type by using a string
I have a string that tells me what I want to cast my object to, Is there a way to cast to that object?
Here is some pseudo code that defines what I would like to do
public TypeToCastTo Cast(T object, String TypeToCastTo) {
switch (TypeToCastTo) {
case "foo":
return (foo)T;
case "otherType":
return (otherType)T;
...
}
}
edit
I wanted to create a game where I can click on a button to purchase something e.g. sword or armour which inherits from worldObject. I figure since I might be returning a weapon or armour class (which both inherit from worldObject) that it would make sense to return a worldObject and then downcast to the correct class (Based off it's name (String)).
edit 2:
As mentioned in the comments this is an XY problem. I was originally trying to make a function that would return the downcast type but in reality that doesn't make sense, since in the case it is used somewhere else, i will need a switch statement to determine what to do with the object anyway (at this point i can cast) so rather than having
public TypeToCastTo Cast(T object, String TypeToCastTo) {
switch (TypeToCastTo) {
case "foo":
return (foo)T;
...
}
}
And using my function to cast the WorldObject, I can have
Method DoingSomethingWithWorldObject(WorldObject T) {
switch(T.typeToCastTo) {
case "foo":
foo temp = (foo)T;
// code using temp
case "other":
other temp = (other)T;
// code using temp
...
}
}
although several people mentioned it was probably wrong the way i was thinking of doing it, Including the answer i have marked correct (Which answered my question even though i was asking the wrong question), The reason i actually understood this was because of a response that was deleted.
A:
As mentioned in the comments, you can do this by using reflection with the Class.cast method:
public Object cast(Object object, String typeToCastTo) {
switch (typeToCastTo) {
case "foo":
return Foo.class.cast(object);
case "otherType":
return OtherType.class.cast(object);
}
}
However the return type of the method needs to be Object as you don't know the actual return type that is encoded in the typeToCastTo parameter.
That is it only makes at least some sense, if you have an instance of Class at hand:
Class<Foo> fooClass = (Class<Foo>) Thread.currentThread().getContextClassLoader().loadClass("my.foo.Foo");
Foo fooObject = foo.cast(object);
But all of this seems rather pointless...
Based on the comments. To invoke a parent class' private method, you don't need to cast:
Object object = new SubFoo();
Method privateFooMethod = Arrays.asList(ParentFoo.class.getDeclaredMethods())
.stream().filter(m -> m.getName().equals("privateFooMethod")).findAny()
.get();
privateFooMethod.setAccessible(true);
privateFooMethod.invoke(object);
But you should really think twice before using reflection to achieve something like this. This very much looks like a bad class/interface design resulting in weird solutions for rather basic needs.
| {
"pile_set_name": "StackExchange"
} |
Q:
mix deps.get fails, {:failed_connect, [{:to_address, {'repo.hex.pm', 443}}, {:inet, [:inet], {:option, :server_only, :honor_cipher_order}}]}
I'm trying to fetch dependencies for my elixir project. I can't tell if Hex is down or not (I was able to fetch just fine this morning). When I run
$ mix deps.get
I see this:
Failed to fetch record for 'hexpm/phoenix_live_reload' from registry (using cache)
{:failed_connect, [{:to_address, {'repo.hex.pm', 443}}, {:inet, [:inet], {:option, :server_only, :honor_cipher_order}}]}
Failed to fetch record for 'hexpm/phoenix_ecto' from registry (using cache)
{:failed_connect, [{:to_address, {'repo.hex.pm', 443}}, {:inet, [:inet], {:option, :server_only, :honor_cipher_order}}]}
Failed to fetch record for 'hexpm/phoenix' from registry (using cache)
{:failed_connect, [{:to_address, {'repo.hex.pm', 443}}, {:inet, [:inet], {:option, :server_only, :honor_cipher_order}}]}
Failed to fetch record for 'hexpm/phoenix_pubsub' from registry (using cache)
{:failed_connect, [{:to_address, {'repo.hex.pm', 443}}, {:inet, [:inet], {:option, :server_only, :honor_cipher_order}}]}
Failed to fetch record for 'hexpm/postgrex' from registry (using cache)
{:failed_connect, [{:to_address, {'repo.hex.pm', 443}}, {:inet, [:inet], {:option, :server_only, :honor_cipher_order}}]}
Failed to fetch record for 'hexpm/ex_machina' from registry (using cache)
{:failed_connect, [{:to_address, {'repo.hex.pm', 443}}, {:inet, [:inet], {:option, :server_only, :honor_cipher_order}}]}
Failed to fetch record for 'hexpm/jason' from registry (using cache)
{:failed_connect, [{:to_address, {'repo.hex.pm', 443}}, {:inet, [:inet], {:option, :server_only, :honor_cipher_order}}]}
And so on for every dependency. What does :no_honor_cipher mean? Am I doing something wrong or is Hex down?
A:
I faced the same error, for me the suggestion from @legoscia worked: update Hex with mix local.hex
| {
"pile_set_name": "StackExchange"
} |
Q:
LinearLayout: TextViews at left, big ImageView at right
i'm working on a LinearLayout but unfortunately it's not working as it should.
The goal is to have a LinearLayout with two TextViews (one placed below the other) on the left side, and an ImageView on the right side.
The ImageView should be as big as possible, the TextViews should take the remaining space.
At the moment my layout XML is like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_linearlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="1dp"
android:background="@drawable/background" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="2dp"
android:orientation="vertical" >
<TextView
android:id="@+id/layout1label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:singleLine="true"
android:text="1234"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/layout2label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1234_label2"
android:textSize="14dp" />
</LinearLayout>
<ImageView
android:id="@+id/layout_image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
android:layout_margin="2dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:src="@drawable/ic_launcher" />
The part that isn't working: If the text in the TextViews is "too long", the ImageView gets shrinked. I want it exactly the other way round.
Any solutions?
A:
It would be more efficient to use RelativeLayout instead of LinearLayout. Then you can place your views without having to nest layouts:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/image"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
/>
<TextView
android:id="@+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/image"
android:layout_below="@+id/title"
/>
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
By arranging the TextViews to be relative to the ImageView instead of the other way around, the ImageView takes priority for the space, and the text works with the remainder.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.