text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
How do you check if an embedded document exists in a document in mongoid?
How do you check if an embedded document exists for a document using mongoid in Ruby on Rails? Say I have a document user that has name, email, and might have a nicknames embedded document. Right now if I run user.first.nicknames and if that user doesn't have the nicknames embedded document in it, it will error out. I've tried matches? and exists? but they don't work.
Thanks!
A:
With a little help from the other answers here, I found something that worked for me and I think this is what the original poster had in mind;
Model.where(:"subdoc.some_attribute".exists => true)
This will return all documents where the "some_attribute" exists on the subdocument.
Notice the syntax of the symbol, that's what I was missing.
A:
This should return true if it doesn't exist User.first.nicknames.nil? and this will return true if it does exist: User.first.nicknames.present?
| {
"pile_set_name": "StackExchange"
} |
Q:
In Liferay what is the "kernel" package?
I am writing a Liferay hook.
When referencing a Java class in Liferay, the "Organize imports" dialog in Eclipse often offers me either com.liferay.portal.TheClass or com.liferay.portal.kernel.TheClass.
On which criteria should I choose one or the other?
Is there a general rule?
What is the philosophy behind this kernel package?
A:
Normally, kernel package is in the portal-service.jar, which is globally visible to portlets, if you have two implementations, my bet would be always the "kernel" version as there's a good chance that the other one is located within portal-impl.jar which sits in Liferay's WEB-INF/lib folder hence it's not visible to other applicaitons like portlets, hooks, etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
indent-[code-]rigidly called from emacs LISP function
I'm trying to write an emacs LISP function to un-indent the region
(rigidly). I can pass prefix arguments to indent-code-rigidly or
indent-rigidly or indent-region and they all work fine, but I don't
want to always have to pass a negative prefix argument to shift things
left.
My current code is as below but it seems to do nothing:
(defun undent ()
"un-indent rigidly."
(interactive)
(list
(setq fline (line-number-at-pos (region-beginning)))
(setq lline (line-number-at-pos (region-end)))
(setq curIndent (current-indentation))
;;(indent-rigidly fline lline (- curIndent 1))
(indent-region fline lline 2)
;;(message "%d %d" curIndent (- curIndent 1))
)
)
I gather that (current-indentation) won't get me the indentation of the first line
of the region, but of the first line following the region (so a second quesiton is
how to get that!). But even when I just use a constant for the column (as shown,
I don't see this function do any change.
Though if I uncomment the (message) call, it displays reasonable numbers.
GNU Emacs 24.3.1, on Ubuntu. And in case it matters, I use
(setq-default indent-tabs-mode nil) and (cua-mode).
I must be missing something obvious... ?
A:
All of what Tim X said is true, but if you just need something that works, or an example to show you what direction to take your own code, I think you're looking for something like this:
(defun unindent-rigidly (start end arg &optional interactive)
"As `indent-rigidly', but reversed."
(interactive "r\np\np")
(indent-rigidly start end (- arg) interactive))
All this does is call indent-rigidly with an appropriately transformed prefix argument. If you call this with a prefix argument n, it will act as if you had called indent-rigidly with the argument -n. If you omit the prefix argument, it will behave as if you called indent-rigidly with the argument -1 (instead of going into indent-rigidly's interactive mode).
| {
"pile_set_name": "StackExchange"
} |
Q:
Cognito - signup request doesn't use the given username but a UUID
Not sure what is missing, but when I use the signup request, a user is created in my cognito user pool with a UUID user name (actually the sub attribute value) and not the email.
val signup = new SignUpRequest()
.withUsername(user.email) // <- cognito ignore this, and use a UUID for username
.withClientId(clientId)
.withSecretHash(secret)
.withPassword(user.password)
.withUserAttributes(List(email, givenName, familyName))
Looking in the documentation a UUID is used when the value of the email is not valid.
The email I use looks similar to this: [email protected] (which is a valid email)
BTW, when I use the AdminCreateUserRequest api, it get created with the email as the username as expected.
val createUser =
new AdminCreateUserRequest()
.withUsername(user.email)
.withUserPoolId(cognitoUserPoolId)
.withUserAttributes(attributes)
client.adminCreateUser(createUser)
Edit:
Now with snapshots:
This is using the signup api -
And this is using the create user api:
Only the sign up doesn't work, What did I miss?
A:
You should look at this: http://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-aliases-settings-option-2
If you are using option 2, with the SignUp call, the username is replaced with a sub.
| {
"pile_set_name": "StackExchange"
} |
Q:
Undefined method when using devise in rails
am using devise for my authentication,i tried customizing the users/sign_in route to users/login but i keep getting this error
NoMethodError in Devise::Sessions#new
undefined method `user_session_path' for #<Module:0x651c828>
It highlights this line which is in the sign_in view
<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
below is my route.rb
devise_scope :user do
get "login", to: "devise/sessions#new"
post "login", to: "devise/session#new"
end
A:
If you don't need to ADD new paths to devise, and you simply want to change the path names, then this is a better option:
devise_for :users, path: '', path_names:
{:sign_in => 'login', :sign_out => 'logout'}
Though - if you're altering the controllers (using your own instead of devise stock controllers) then this doesn't work well.
Platformatec has some really great documentation though, you should pour through it and mix and match to meet your needs. https://github.com/plataformatec/devise/wiki/How-Tos
| {
"pile_set_name": "StackExchange"
} |
Q:
Append the contents of latest Stackage nightly build to the global cabal config file
I've made the following python script to to append the contents of the latest Stackage nightly build to the global cabal config file (instead of going to the site, copying the page and appending it manually...). I would appreciate your feedback:
"""
Appends the latest stackage nightly sources from Stackage(http://www.stackage.org/nightly)
to your global cabal config file
It also makes two backups: one of the appended file and one of the unappended file
Stackage(http://www.stackage.org/) is a stable source of Haskell packages
"""
import requests
import shutil
from os.path import expanduser
from os.path import join
cabal_config_path = expanduser('~/.cabal/config')
stackage_nightly_url = 'https://www.stackage.org/nightly/cabal.config?global=true'
def write_cabal_config_backup(filename):
"""
Writes a backup of the current global cabal config file in the ~/.cabal directory
"""
shutil.copyfile(cabal_config_path,
join(expanduser('~/.cabal'), filename))
def unappend_stackage():
"""
Unappend stackage sources from the global cabal config file. Be careful that
the sources must be at the end of the file, or this function will delete things
that you don't want it to.
"""
def unappended_cabal_config():
# Searches for the string 'Stackage' and returns a list made of the lines
# of the file from there up, excluding the 'Stackage' line and everything below.
with open(cabal_config_path) as f:
cabal_config = f.readlines()
for i in range(len(cabal_config)):
if 'Stackage' in cabal_config[i]:
return cabal_config[:i]
return cabal_config
def write_unappended_cabal_config():
cabal_config = unappended_cabal_config()
with open(cabal_config_path, 'wt') as f:
for line in cabal_config:
f.write(line)
write_unappended_cabal_config()
def append_stackage_nightly():
"""
Appends stackage nightly sources to the global cabal config file
"""
def get_stackage_nightly():
r = requests.get(stackage_nightly_url)
if r.status_code == 200:
return r.text
stackage_nightly = get_stackage_nightly()
if stackage_nightly:
with open(cabal_config_path, 'a') as f:
f.write(stackage_nightly)
if __name__ == '__main__':
write_cabal_config_backup('config_backup_appended')
unappend_stackage()
write_cabal_config_backup('config_backup_unappended')
append_stackage_nightly()
A:
The unappend_cabal_config can be more efficient and more elegant using a generator:
Reading all the lines from the file when you may only need the ones until one containing "Stackage" is wasteful
It's good to avoid the index variable in loops when possible
Like this:
def unappend_cabal_config():
with open(cabal_config_path) as fh:
for line in fh:
if 'Stackage' in line:
return
yield line
A:
You code doesn't follow all of PEP8.
There are 8 lines that are too long.
Limit all lines to a maximum of 79 characters.
For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.
Also you shouldn't have whitespace at the end of lines. 'def foo(): '.
As others have said.
Surround top-level function and class definitions with two blank lines.
You should avoid names such as f and r.
CONSTANS should be fully capitalised.
Also there is PEP257 as well.
Your docstrings should be in 'imperative mood'.
You should have one line docstrings on one line not three.
Also why do you like nested scopes so much?
This just confused me at first, you return information, to then check the information, and then you use a 'function' on it.
def append_stackage_nightly():
def get_stackage_nightly():
r = requests.get(stackage_nightly_url)
if r.status_code == 200:
return r.text
stackage_nightly = get_stackage_nightly()
if stackage_nightly:
with open(cabal_config_path, 'a') as f:
f.write(stackage_nightly)
You should if stackage_nightly is not None:, but you can just remove it.
And you are calling the functions 'the wrong way around'.
If you put the with statement in a function it would make more sense.
Here I will make it a generater, so that we minimise read/write operations.
def append_stackage_nightly():
result = requests.get(stackage_nightly_url)
if r.status_code == 200:
yield result.text
Edit: due to an error.
Now we can change the unappend_stackage so that it only writes to the file.
This is so we don't clear the file first. (The error)
We will make it take an iterable and write to the file.
def unappend_stackage():
def unappended_cabal_config():
with open(cabal_config_path) as f:
cabal_config = f.readlines()
for i in range(len(cabal_config)):
if 'Stackage' in cabal_config[i]:
return cabal_config[:i]
return cabal_config
def write_unappended_cabal_config():
cabal_config = unappended_cabal_config()
with open(cabal_config_path, 'wt') as f:
for line in cabal_config:
f.write(line)
write_unappended_cabal_config()
As we changed the append_stackage_nightly, we can loop through a generator.
Rather than making a new one.
And we will flatern out the function so it is a single function.
def unappend_stackage(iterable):
with open(cabel_config_path, 'wa') as cabel_write:
for line in iterable:
if 'Stackage' in line:
break
# You may want this to be `continue`,
# unless you know for sure there is no data after the first Stackage.
cabel_write.write(line)
This removes the need to write to cabel_config_path twice, and read from it once.
| {
"pile_set_name": "StackExchange"
} |
Q:
Books on patents
I am looking for some intermediate level books on patents.
I heard about a book called "Patent It Yourself", has anyone read it and can you recommend it? What group is the book targeting and does it give some deeper insight? Is it country specific?
(Other suggestions are appreciated too)
A:
I'm a big fan of Patents Demystified as a guide to patents for inventors and startups. Some folks here on Stack Exchange suggested it to me and it was just what I was looking for. Seems like the patent book that most people use.
It has a great foundation of the basics and works up to intermediate and advanced patent strategies. Unlike most patent books I found, this one is really easy to understand and has specific actionable steps and strategies for protecting inventions and maximizing protection.
It's primarily directed to the U.S. patent process, but also discusses how the foreign patent process works as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I tell nodemon to ignore all node_modules except for one directory
I have a Node.js server I am developing and I'm using nodemon to have the server restarted when the source code changes.
This server has a dependency on another module, which I am also developing, so it would be nice if changes to that module also restarted the server.
Best attempt yet (Thanks, bitstrider!)
I made a repo to reproduce this problem with minimal code if anyone wants to check it out: https://github.com/shawninder/nodemon-troubles
The highlights are in nodemon.json:
{
"ignoreRoot": [
".git",
".nyc_output",
".sass-cache",
"bower-components",
"coverage"
],
"ignore": [
"node_modules/!(is-node)",
"node_modules/is-node/node_modules"
]
}
ignoreRoot is the same as the defaults, but without node_modules.
ignore is where I'm trying to tell it to ignore node_modules, but not is-node.
This almost works (editing is-node restarts the server) but it's watching all the node modules, not only is-node.
How can I tell nodemon to ignore all node modules except for one?
Details
I'm using the latest version of nodemon, 1.11.0
I also tried with https://github.com/remy/nodemon/pull/922
Explaining the problem
Nodemon takes the ignores and combines them into one big regular expression before passing this along to chokidar. It's a custom parsing algorithm based on regular expressions and supports neither glob negation nor regular expression syntax. For example, the example above produces the following regular expression:
/\.git|\.nyc_output|\.sass\-cache|bower\-components|coverage|node_modules\/!\(is\-node\)\/.*.*\/.*|node_modules\/is\-node\/node_modules\/.*.*\/.*/
Notice the negation character ! end up as a literal ! in the resulting regular expression. Using negative look-ahead syntax also doesn't work because the control characters are transformed into literal characters.
A:
Since nodemon uses minimatch for matching, you should be able to use negation with the symbol !, according to the documentation.
So in your case, try:
{
"ignore" : "node_modules/!(my-watched-module)/**/*"
}
This should ignore all module files except those within my-watched-module
NOTE: The ignore rule here only targets files, not directories. This behavior makes sense in the context of nodemon because its watching for file changes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Angularjs: Verify check box are clicked
I have a check box in a form. Before submitting form I want to check if atleast one check box is selected. If not, disable the submit button. List of checkbox is dynamic.
I have tried with ng-click="check()"
<label class="checkbox-inline">
<input type="checkbox" name='Apple' ng-model='cb.fruit.Apple' ng-click="check()"> Apple
</label>
<label class="checkbox-inline">
<input type="checkbox" name='Grape' ng-model='cb.fruit.Grape' ng-click="check()"> Grape
</label>
<label class="checkbox-inline">
<input type="checkbox" name='Mango' ng-model='cb.fruit.Mango' ng-click="check()"> Mango
</label>
Inside Angularjs Controller,
$scope.check = function(){
fruit_false = 0;
fruit_true = 0;
for (var o in $scope.cb.fruit){
$log.info(o);
if (!o) fruit_false++;
if (o) fruit_true++;
$log.info(fruit_false);$log.info(fruit_true);
}
// this logic needs to be corrected
if (fruit_false == 0 && fruit_true == 0)
$scope.cd.fruitcheck = false;
else
$scope.cd.fruitcheck = true;
}
Problem is when one check box is clicked, cb.fruit.Apple=true is not reflected. At $log.info(o); it says undefiend.
When two check box are selected (Apple=true, Grape=true), $log.info(o); shows only one value (Apple= true). But it should not happen like this.
Is there any other simple way to solve this or where I am going wrong?
A:
The solution is quite straightforward:
(See associated PLUNKER DEMO)
Since you have mentioned that, "List of checkbox is dynamic", and relating it with the models you have created for each checkbox, then the first step would be to iterate each checkbox items using the ng-repeat directive. Use the (key, value) syntax to display each of the checkbox label and use its key as a direct reference for the models.
E.G:
<label ng-repeat="(fruitName, isChecked) in cb.fruits" for="{{fruitName}}">
<input type="checkbox" ng-model="cb.fruits[fruitName]" id="{{fruitName}}" /> {{fruitName}}<br>
</label>
Create a function to determine the existence of a checked value within the $scope.cb.fruits object. Use this function in the ng-disabled directive to disable and enable the submit button.
E.G:
HTML
<button type="submit" ng-disabled="!hasSelectedFruit()">Button</button>
JAVASCRIPT
$scope.cb = {
fruits: {
Apple: false,
Grapes: false,
Mango: false
}
};
$scope.hasSelectedFruit = function() {
var fruits = $scope.cb.fruits;
for(var index in fruits)
if(fruits[index])
return true;
return false;
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Calling a Bash script variable from the commandline
I have a Bash script that accepts a command-line argument. The script defines a couple of string arrays. The argument determines which array(s) I would like to print. Since there are a bunch of different possible sets of arrays to choose from, I would like to be able to specify on the command-line exactly which arrays to print.
For example, say I define these arrays:
#/bin/bash
myarray1=(abc 123)
myarray2=(def 456)
myarray3=(ghi 789)
myarray4=(jkl 012)
myarray5=(mno 345)
myarray6=(pqr 678)
myarray7=(stu 901)
I would like to choose from the command-line whether or not I want to print all the arrays, or various combinations of these arrays, such as myarray1, myarray3, and myarray4. But on another run, I only want to print myarray5 and myarray7.
I would ideally like to be able to run the script like this:
np ~/usr-bin > bash myscript.bash myarray1 myarray3 myarray4
So that the output is this:
abc 123
ghi 789
jkl 012
Or like this:
np ~/usr-bin > bash myscript.bash myarray5 myarray7
So that the output is this:
mno 345
stu 901
I'd like Bash to take these arguments and recognize that they're array/variable names, and then print them as if I were doing this: echo $1
I have barely done any Bash scripting before, and the method I've tried to accomplish this with doesn't seem to work. Is this something that's possible, or is there a much better way to accomplish this than the way I'm trying to go about it?
A:
Since Bash 4.3 (2014-02-26), you can use namerefs as a simple solution:
print_arrays() {
for a in "$@"; do
# This makes _t_ an alias for the variable whose name is $a
declare -n _t_="$a"
echo "${_t_[@]}"
done
}
Prior to 4.3, you need to use the ! indirection syntax. However, the variable indirected through needs to contain the entire array reference, including subscripts. And you can only indirect through a variable, not a string expression. So you'd need to do something like this:
print_arrays() {
for a in "$@"; do
# Construct the "name", which is the subscripted array name
_t_=${a}[@]
echo "${!_t_}"
done
}
If you're new to Bash, you should read the Bash manual section on arrays, which explains the curious syntax "${array[@]}". The definition here of _t_ is intended to create that syntax; it is not itself a subscript expression.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it sufficient to check weak convergence on a (weak* or strongly) dense subset of the dual?
Let X be a Banach space. If $D \subset X^*$ is (weak*ly or strongly?) dense, then does $f(x_n) \to f(x)$ $\forall f \in D$ imply that $x_n \to x$ weakly?
My thoughts: If $g_m \to g$ in the dual, then we can write:
$|g(x) - g(x_n)| \leq |g(x) - g_m(x)| + |g_m(x) - g_m(x_n)| + |g_m(x_n) - g(x_n)|$, where the middle term always vanishes for a fixed $m$ as $n \to \infty$ by assumption, though this is a moving target. The first term will vanish as $m \to \infty$ in either the weak* topology or the strong topology on the dual, and the latter term vanishes if the dual topology was the strong topology and the sequence $x_n$ was bounded in norm.
A:
and the latter term vanishes if the dual topology was the strong topology and the sequence $x_n$ was bounded in norm.
That is the crucial thing. The sequence needs to be bounded to deduce weak convergence from pointwise convergence on a norm-dense subset.
If $(x_n)$ is a bounded sequence in $X$, it is an equicontinuous sequence as a sequence of functions $X^\ast \to \mathbb{K}$ (via the canonical embedding $X\hookrightarrow X^{\ast\ast}$), and for equicontinuous sequences, pointwise convergence on a dense subset implies pointwise convergence everywhere, that is here weak convergence.
If the sequence $(x_n)$ is not bounded, there still can be dense subsets, even linear subspaces, $D\subset X^\ast$ such that $f(x_n) \to f(x)$ for all $f\in D$, but of course an unbounded sequence cannot be weakly convergent.
| {
"pile_set_name": "StackExchange"
} |
Q:
How many different armies exist in Warhammer Fantasy?
I'm following the news about the "Total War: Warhammer" game.
I have seen that they are going to take out the second game and it will include 4 more armies of Warhammer.
In this next edition will put:
Lizards men
Skavens
High Elves
Dark Elves
These 4 armies would be united to those already existing:
Empire
Bretonia
Chaos warriors
Beast men
Dwarfs
Orcs and goblins
Vampire counts
Wood Elves
As for this, I have been thinking about those that are missing... I only have 4 more that would be :
Chaos Dwarves
Daemons of Chaos
Kingdom of the Ogres
Funeral kings
Exposed all of this, I'm forgetting something? Or are there only these armies in the Warhammer? Could they add some other armies that only comes out in the lore? If so, what would it be?
A:
Its been a while since I've played, and It looks like they have changed things a bit with the latest edition, but I think you have covered all the major published ones.
There did used to be a mercenary army called Dogs of War that you could play, although normally the units were fielded as mercenaries in other armies.
There have also been Araby and Kislev armies in Warmaster, another discontinued game in the same universe. These armies may have had experimental white dwarf rules as well, not sure.
There were also various combined army rules (e.g. Combined chaos armies of various forms), but I wouldn't count them as separate factions, as well as specialised versions of different armies (e.g. rules for different vampire factions that allowed a few different units in the list).
| {
"pile_set_name": "StackExchange"
} |
Q:
Moving all but one folder to sub-directory - git
I have a git repo synced with Github with the following structure.
~/Data_Store/
~/Data_Read/
....
...
~/R/
The .git folder is in ~/
I wish to achieve the following end state.
The current repo moved to a new folder called ghubrepo in ~/ghubrepo/
A new repo created linked to BitBucket called bbrepo in ~/bbrepo/
Retain the ~/R/ folder in ~/ (not synced to any repo)
I have already done the folder structure so it appears as below:
~/ghubrepo
~/bbrepo
~/R
~/.git
I am now stuck. git status shows all files deleted (except ~/R/) so I dare not commit.
Any suggestions on way fwd?
A:
You would need to move the existing repo first in order to avoid a git status showing you that "everything is deleted".
mkdir ~/ghubrepo
mv ~/* ~/ghubrepo # you might have a warning stating that it cannot move
# ghubrepo in itself
mv ~/.git ~/ghubrepo
Then you can proceed with the rest of the structure.
But first, check that a git status in ~/ghubrepo is what you expect.
| {
"pile_set_name": "StackExchange"
} |
Q:
Absolute Layout Panel within JScrollPane
I'am using panel with absolute layout (don't ask why) and I need to add elements on it programmatically. I done that part, but now I want to surround panel with JScrollPane so that when user add more items, scroll bar does its job. But surrounding panel with scroll bar doesn't work. What can I do here.
JFrame frame = new JFrame();
frame.setSize(582, 451);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 11, 546, 391);
frame.getContentPane().add(scrollPane);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
panel.setLayout(null);
for(int i=0;i<labelList.size();i++){
if(a==4){
a=0;
b++;
}
labelList.get(i).setBounds(10+120*a+10*a, 10+130*b+10*b, 120, 130);
labelList.get(i).setOpaque(true);
labelList.get(i).setBackground(Color.WHITE);
labelList.get(i).setText(Integer.toString(i));
panel.add(labelList.get(i));
a++;
}
A:
You're not going to like my answer, but I feel that we should be compelled to give you the best answer, which is not always what you want to hear. And that is this: use layout managers to do your component layouts. Yes while it might seem to newbies that null layouts are the easiest to use, as you gain more experience you will find that exactly the opposite is true. Null layout use makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain. Instead you will want to study and learn the layout managers and then nest JPanels, each using its own layout manager to create pleasing and complex GUI's that look good on all OS's.
As for ease of use, I invite you to create a complex GUI with your null layout, and then later try to add a component in the middle of this GUI. This will require you to manually re-calculate all the positions and sizes of components added to the left or below the new component, which is prone to many errors. The layout managers will all do this automatically for you.
Specifically use of valid layout managers will update your JPanel's preferredSize automatically increase as more components are added and as the JPanel is revalidated (the layouts are told to re-layout their components). Your null JPanel will not do this, and so the JScrollPane will not work. Yes, a work around is for you to manually calculate and set your JPanel's preferredSize, but this is dangerous and not recommended for the same reasons noted above.
| {
"pile_set_name": "StackExchange"
} |
Q:
R markdown link is not formatted blue when knitted to pdf
for some reason no link in my R markdowns (rmd) is formatted blue. knitting the simple rmd below to pdf is leaving the text color black. only when hovering over it does one realize that it's actually a link. knitting it to html will make the link blue. of course I can use a latex wrapper but I wonder why that is?
sessionInfo()
R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
loaded via a namespace (and not attached):
knitr_1.15
RStudio 1.0.44
---
title: "R Notebook"
output:
pdf_document: default
html_notebook: default
---
```{r, echo=F}
# tex / pandoc options for pdf creation
x <- Sys.getenv("PATH")
y <- paste(x, "E:\\miktex\\miktex\\bin", sep=";")
Sys.setenv(PATH = y)
```
[link](www.rstudio.com)
A:
Add urlcolor: blue to the yaml.
---
title: "R Notebook"
output:
pdf_document: default
html_notebook: default
urlcolor: blue
---
```{r, echo=F}
# tex / pandoc options for pdf creation
x <- Sys.getenv("PATH")
y <- paste(x, "E:\\miktex\\miktex\\bin", sep=";")
Sys.setenv(PATH = y)
```
[Link to R Studio](www.rstudio.com)
Bare urls will also be highlighted:
http://www.rstudio.com
| {
"pile_set_name": "StackExchange"
} |
Q:
Displaying all records in a mysql table
The code below works fine for printing one record from a database table, but what I really want to be able to do is print all the records in the mysql table in a format similar to my code.
I.E.: Field Name as heading for each column in the html table and the entry below the heading. Hope this is making sense to someone ;)
$raw = mysql_query("SELECT * FROM tbl_gas_meters");
$allresults = mysql_fetch_array($raw);
$field = mysql_query("SELECT * FROM tbl_gas_meters");
$num_fields = mysql_num_fields($raw);
$num_rows = mysql_num_rows($raw);
$i = 1;
print "<table border=1>\n";
while ($i < $num_fields)
{
echo "<tr>";
echo "<b><td>" . mysql_field_name($field, $i) . "</td></b>";
//echo ": ";
echo '<td><font color ="red">' . $allresults[$i] . '</font></td>';
$i++;
echo "</tr>";
//echo "<br>";
}
print "</table>";
A:
Just as an additional piece of information you should probably be using PDO. It has more features and is helpful in learning how to prepare SQL statements. It will also serve you much better if you ever write more complicated code.
http://www.php.net/manual/en/intro.pdo.php
This example uses objects rather then arrays. Doesn't necessarily matter, but it uses less characters so I like it. Difference do present themselves when you get deeper into objects, but not in this example.
//connection information
$user = "your_mysql_user";
$pass = "your_mysql_user_pass";
$dbh = new PDO('mysql:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
//prepare statement to query table
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
//loop over all table rows and fetch them as an object
while($result = $sth->fetch(PDO::FETCH_OBJ))
{
//print out the fruits name in this case.
print $result->name;
print("\n");
print $result->colour;
print("\n");
}
You probably also want to look into prepared statements. This helps against injection. Injection is bad for security reasons. Here is the page for that.
http://www.php.net/manual/en/pdostatement.bindparam.php
You probably should look into sanitizing your user input as well. Just a heads up and unrelated to your current situation.
Also to get all the field names with PDO try this
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
Once you have all the table fields it would be pretty easy using <div> or even a <table> to arrange them as you like using a <th>
Happy learning PHP. It is fun.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to show and hide toggle button when screen resize
I want to show my userlist (by default and no toggle) when the screen is in full size and provide a toggle when the screen is in mobile size which could help show/hide the list.
I am using the following the code:
<button type="button" class="btn btn-default" data-toggle="collapse" data-target="#demo">Users Online</button>
<div id="demo" class="collapse">
<div ng-repeat="user in chatCtrl.userList">{{user}}</div>
</div>
<script>
$(document).ready(function(){
$("#demo").on("hide.bs.collapse", function(){
$(".btn").html(' Users Online');
});
$("#demo").on("show.bs.collapse", function(){
$(".btn").html(' Users Online');
});
});
</script>
It gives me the toggle even when the screen in full size.
So just one question: how to only show the toggle button when screen collapses?
Any suggestion and reference will be appreciated!
Thanks.
A:
Give your button an id and use a media query
@media(min-width:768px){
#id-for-button{
display:none;
}
}
It will be hidden on everything above 768px or the screen size that you choose.
https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
| {
"pile_set_name": "StackExchange"
} |
Q:
Solving a limit with a determinant
I've found this result:
$$ \lim_{h\to 0} \frac{\det\left(A^{-1}(t)A(t + h)\right)- 1}{h} = tr \left(A^{-1}(t)\frac{dA(t)}{dt}\right)$$
It occurred to me to do a Taylor expansion of $A(t + h)$, but I get
$$\lim_{h\to 0} \frac{\det\left(A^{-1}(t)\left(A(t) + \frac{dA}{dt}h + ...\right)\right)- 1}{h} = \lim_{h\to 0} \frac{\det \left(I + A^{-1}\frac{dA}{dt}h + ...\right) - 1}{h} $$
so I don't get to obtain the trace. Any help will be welcome. Thanks.
A:
Hint:
$$ \lim_{h\to 0} \frac{\det\left[A^{-1}(t)A(t + h)\right]- 1}{h} = \lim_{h\to 0} \frac{\det A^{-1}(t)\det A(t + h)- \det A^{-1}(t)\det A(t)}{h}$$
$$=\det A^{-1}(t)\lim_{h\to 0} \frac{\det A(t + h)- \det A(t)}{h}=\det A^{-1}(t)\dfrac{d}{dt}\det A(t).$$
As Clement C. pointed out using Jacobi's formula will result in:
$$\det A^{-1}(t)\dfrac{d}{dt}\det A(t)=\det A^{-1}(t)\operatorname{tr}\left[\operatorname{adj}A(t)\dfrac{dA(t)}{dt} \right].$$
The adjugate of $A(t)$ can be rewritten as $\operatorname{adj}A(t)=\det A(t)A^{-1}(t)$ and then we can extract $\det A(t)$ from the trace as it is a scalar. This leads to:
$$\det A^{-1}(t)\operatorname{tr}\left[\det A(t)A^{-1}(t)\dfrac{dA(t)}{dt} \right]=\operatorname{tr}\left[A^{-1}(t)\dfrac{dA(t)}{dt} \right].$$
A:
An intuitive way to proceed is to use the identity we are about to find.
For a $n$-dimensional square diagonalizable matrix:
$$
\rm{det}(A)=\prod_{i=1}^n\lambda_i
$$
with $\lambda_i $ eigenvalue for $A$
and if the eigenvalues are all positive (for the mixed case just factor signs away):
$$
\prod_{i=1}^n\lambda_i=\exp\left(\sum_{i=1}^n\log(\lambda_i)\right)=\exp\left(\rm{Tr}(\log(A))\right)
$$
so now for a diag matrix we have:
$$
\rm{det}(A)=\exp\left(\rm{Tr}(\log(A))\right)
$$
from this representation you can easily recover both Jacobi's identity and solve your problem (for this refer to MrYouMath answer).
Remark: This is not rigorous enough to be a proof, but it's easy to turn it into one.
A much simpler argument is to show that:
$$
\det(I+h\epsilon)=1+h \rm{Tr}(\epsilon)+O(h^2)
$$
you can show this using the identity above.
indeed:
$$
\rm{det}(I+h\epsilon)=\exp\left(\rm{Tr}(\log(I+h\epsilon))\right)\sim1+\rm{Tr}(\log(I+h\epsilon))\sim 1+h\rm{Tr}(\epsilon)
$$
The point of this answer is to provide an intuitive understanding and nothing more.
| {
"pile_set_name": "StackExchange"
} |
Q:
Design issue- should use seperate thread for GUI?
I'm building a little software in Java, with a GUI.
I have an algorithm which runs continuously (Almost 24/7) (I have a stop/start button in GUI)
This algorithm should update a list and show a log on the GUI.
The question is- should I create a separate class or thread for this procedure (algorithm),
1) If the answer is yes - Should I transfer the GUI elements that I should update as parameters to that procedure? Would it cause problems updating the GUI?
2) If not - how should I design it?
Many thanks in advance!
A:
You should use for heavy task SwingWorker, is designed for this situations. Here you have a nice article why do we need SwingWorker?.
You need this cause if your algorithm take for example 5 secs and you run in the same thread as gui, it's gonna to freeze your view until finish.
BTW all gui-components must be updated in the Event Dispatch Thread, so you don't have to update them in another thread cause they don't be updated.
| {
"pile_set_name": "StackExchange"
} |
Q:
QuickTime X Applescript
(Copying this from Stack Overflow, because this might be a better place to ask)
Looking for help (really to do) with a script/automator action for opening a files in QT X and using the export 720p command. I do not want to use the encode feature built into the finder. Using the "export" feature in QT X with the files I'm working does the trick and does not re-encode the files. I tried using automator but there is no "export" action only "encode" which re-encodes the files.
I see the command in the dictionary but can't seem to make it work.
I've started with this but I keep getting a permissions problem. A guy on Stack Overflow has noted the same problem.
tell application "Finder"
set savePath to "Macintosh HD:Users:WBTVPOST:Desktop"
end tell
tell application "QuickTime Player"
activate
tell application "QuickTime Player" to get the name of front window
set vidName to name
export (document 1) in savePath using settings preset "720p"
end tell
I've seen a lot of scripting help but mostly for QT 7 and Pro. Not so much for X
Is this possible?
Thanks in advance for your talent and skill,
Cheers!
A:
tell application "QuickTime Player"
set movieName to the name of the front document
set savePath to a reference to POSIX file ¬
("/Users/WBTVPOST/Desktop/" & movieName & ".mov")
export the front document in savePath using settings preset "720p"
end tell
System info: AppleScript version: 2.7 System version: 10.13.6
PS. User @wowfunhappy is absolutely correct in saying that the export command does re-encode a file. It has to in order to apply whatever settings are contained within the preset.
| {
"pile_set_name": "StackExchange"
} |
Q:
ddd no debug symbols are found
I build my project with "./configure CFLAGS=-g3" , also tried "make CFLAGS=-g3".
when I load slim.exe with ddd, it say no debug symbols are found.
How can I create slim.exe with debug symbols, and I load it to ddd and perform debugging?
is there any chance that debug is disabled in configure.ac ?
I am not familiar with automaketools and Linux, now using cygwin on windows.
I searched solutions, but failed.
could anyone point out my mistakes?
many thanks in advance
A:
Assuming your compiler is gcc, the option to enable debug output is -g, there's no number after it. It looks like you're confusing it with the optimization flag family -O1 and so on.
Also, to set the environment variable, you need to do it before running the command, in general:
$ CFLAGS=-g make
And with autoconfig, it's ususally an option:
$ ./configure --enable-debug
You can run ./configure --help to view the available options, and since configure will lead to Makefile(s) being created, you must always do it before trying to build the project by running make.
The sequence is, typically:
cd project
./configure --help to review the options, look for --enable-debug
./configure --enable-debug to run the autoconfig script, creating Makefile(s)
make
| {
"pile_set_name": "StackExchange"
} |
Q:
What kind of Arduino should I pick for a calculator?
I am planning to build a calculator using Arduino as the base. I already know C and I love low-level stuff, so I guess the software part won't be a problem.
However, I've been stuck with Arduino. What I need is something capable of doing math (as I'm not even sure if Arduino has a FPU), and it to have enough inputs for more than the basic 0-9 + - / * keys.
I am a real newbie when it comes to hardware. I don't even have the slightest clue where to start. I barely understand Arduino's specifications, which is why I'm asking here.
I want to do something more than the classic calculator, because the software part is not a problem. I just need help on which hardware should I choose; both on the 'which Arduino' and 'which accesories for the Arduino' parts.
P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?
A:
Start with the biggest (AVR) Arduino you can afford, and worry about miniaturizing it once you have the basics in place. You may find that you don't actually want an Arduino in the end, but something like the ATmega169PA instead so that you have native LCD support (instead of having to use a discrete LCD module).
P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?
Doesn't matter. Most of your x86 assembly experience will easily transfer to AVR (but not all, since the AVR core is simpler than x86).
A:
For the most part, none of the AVR based arduinos are any better at number crunching than any others. They all have a single AVR core running at 16Mhz. None have an FPU, but the software floating point code is very efficient and at the time scales you care about for a calculator, it really doesn't make much of a difference.
The biggest differences between models are memory and available IO, so the decision between AVR models should probably come from what kind of peripherals you want to plug in, not what you want to calculate.
That said, if you want to do a lot of high precision, numerical calculations (like numerical integration or something), you will probably want something with more memory, and floating point types larger than 32-bits. I don't have much experience with those models, but I'm pretty sure that a Yun or a Zero would be better suited for those kinds of calculations. They don't use AVR based main CPUs.
For IO there are too many options to enumerate here. Take a look at the usual suspect's pages (sparkfun, adafruit, etc...) for displays and buttons. These sites have good descriptions and example code for everything.
When picking devices, remember that you can have multiple I2C devices plugged in at once, but only one UART serial per port (uno/leonardo 1 port, mega 4). Software serial can give you more UARTs for low speed comms if need be.
If you want a lot of different individual buttons, there are ways to get more than 1 button per pin, but it would be a bit easier electrically to pick an arduino with as many pins as buttons. Some of the keypads available already have a special wiring scheme to get higher than 1-to-1 pin ratios and descriptions of how to use them, so they might be a good pick to get yourself started.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I check if a guessed character is in a string in this code?
What I'm trying to do is if the user guesses the correct letter in the correct spot, it will output the letter in green. If the user guesses the letter that's in the answer, but that's in the wrong spot, it will output in red. And if the user guesses a letter that's not in the answer it will output in black. I'm struggling to figure out how to make it so that it will check if the letter is in the code but not the right place.
<script>
var secret = 'OPIMNC';
function init(){
var button = document.getElementById('startButton');
button.onclick = myButtonClick;
}
function myButtonClick(){
var userTry = document.getElementById('userGuess').value;
var ul = document.getElementById('guessList');
var li = document.createElement('li');
for (var i=0; i < secret.length; i++) {
var found = false;
if ((userTry.charAt(i))===(secret.charAt(i))) {
li.innerHTML += userTry.charAt(i).fontcolor('green');
found = true;
}
//if character is in the code but in the wrong place, output the font in red
else if ???? {
for (var j=0; j < secret.length; j++) {
??????????????
}
found = true;
li.innerHTML += userTry.charAt(i).fontcolor('red');
else if (found===false) {
li.innerHTML += userTry.charAt(i).fontcolor('black');
}
}
ul.appendChild(li);
}
window.onload = init;
</script>
A:
var secret = 'ABCDEF';
function init() {
var button = document.getElementById('startButton');
button.onclick = myButtonClick;
}
function myButtonClick() {
var userTry = document.getElementById('userGuess').value;
if(userTry.length !== 6){
document.getElementById('error').innerHTML = "I need 6 characters !";
return;
}
document.getElementById('error').innerHTML = "";
var ul = document.getElementById('guessList');
ul.innerHTML = ""; //Clear list
for (var i = 0; i < secret.length; i++) {
var color;
if (userTry.charAt(i) === secret.charAt(i)) {
//Correct index
color = 'geen'
} else if (secret.indexOf(userTry.charAt(i)) !== -1) {
//Present but wrong index
color = 'red';
} else {
//Not present
color = 'black';
}
//Add letters to list with correct colors
var li = document.createElement('li');
li.innerHTML = userTry.charAt(i).fontcolor(color);
ul.appendChild(li);
}
}
window.onload = init;
<input type="text" id="userGuess" maxlength="6"/>
<button type="submit" id="startButton">Start</button>
<p style="color: red;" id="error"></p>
<ul id="guessList">
</ul>
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating 2D arrays and input values in it with a while loop?
So, I'm thinking of creating a 2D array where row represents city names (in integers of course) and column representing temperature.
days = int(input("Enter days: "))
city = int(input("Enter city: "))
array = [[0]* days]*city
i = 0
printing the array with input:
days = 3
city = 3
gives me something like:
[[0,0,0],[0,0,0],[0,0,0]]
but the problem I'm having now is, how to insert values into the array?
when i was working on 1D array, i used:
while i<days:
array[i] = int(input("temperature: "))
i+=1
which inserts the temperature into the array.
array = [1,2,3]
but now that it's 2D, I can't seem to figure it out. The rows now represent the city and the column represents the temperature. I want to have something like.
[[1,2,3],[4,5,6],[7,8,9]]
How would I modify my while loop to implement 2D arrays?
A:
To go over a 2D array you have to use two nested loops.
i = 0
j = 0
while (i < len(array)):
while(j < len(array[i]):
array[i][j] = value
j = j + 1
j = 0
i = i + 1
Those loops set in a 2D array each time value. value can be in this case whatever you want it to be. The first index determines the array in the array and the second index selects the value in the nested array. In your case when you have [[1, 2, 3], [4, 5, 6], [7, 8, 9]], array[1][2] == 6
This also works for arrays that are not symmetric.
| {
"pile_set_name": "StackExchange"
} |
Q:
Função para totalizar valores de input selecionados em checkbox
Boa tarde.
Tenho uma table na minha página com colunas de quantidade e valor do produto. Esses valores são retornados do meu BD, em cada linha tem um checkbox para seleção, já fiz uma função para calcular o total de cada produto (quantidade * valor). O que preciso é uma função para totalizar a soma dos produtos selecionados pelo checkbox.
HTML/PHP
<table id="produtos" class="table table-striped table-condensed table-bordered table-hover">
<thead>
<tr>
<th style="width:10%">Produto</th>
<th style="width:30%">Descricao</th>
<th>Quantidade</th>
<th>Valor Tabela</th>
<th>Ultima Compra</th>
<th style="width:5%">Emb.</th>
<th style="width:5%">Peso Bruto</th>
<th style="width:5%">Est. Casa</th>
<th style="width:10%">Est. Cliente</th>
<th style="width:10%">Qtd. Pedido</th>
<th style="width:10%">Valor compra</th>
<th style="width:20%">Total</th>
<th>Sel.</th>
</tr>
</thead>
<tbody>
<?php $i = 0;
do { ?>
<tr>
<td><?php echo $row_vendas['produto']; ?><input type="hidden" name="produto[]" value="<?php echo $row_vendas['id_produto'] ?>"></td>
<td><?php echo $row_vendas['descricao']; ?><input type="hidden" name="descricao[]" value="<?php echo $row_vendas['descricao'] ?>"></td>
<td><?php echo number_format($row_vendas['quantidade'],3,',','.'); ?></td>
<td><?php echo number_format($row_vendas['preco1'],2,',','.'); ?></td>
<td><?php echo date('d/m/Y', strtotime($row_vendas['ultima_compra'])); ?></td>
<td><?php echo $row_vendas['embalagem']; ?></td>
<td><?php echo $row_vendas['peso_bruto']; ?><input type="hidden" name="peso[]" value="<?php echo $row_vendas['peso_bruto'] ?>"></td>
<td><?php echo number_format($row_vendas['estoque'],3,',','.'); ?></td>
<td><input type="number" min="1" name="estoque" style="width:80%" autocomplete="off"></td>
<td><input type="number" min="1" name="qtd[]" id="qtd<?php echo $i ?>" style="width:80%" autocomplete="off" onChange="somaProduto(<?php echo $i; ?>)"></td>
<td>
<input type="text" name="valor[]" id="preco<?php echo $i; ?>" style="width:70%" value="<?php echo number_format($row_vendas['valor'],2,',','.') ?>" autocomplete="off" onkeypress="return SomenteNumero(this, event);" onChange="somaProduto(<?php echo $i; ?>)">
<input type="hidden" id="tolerancia<?php echo $i; ?>" style="width:80%" value="<?php echo $row_vendas['tolerancia_preco'] ?>" autocomplete="off">
<input type="hidden" id="valTabela<?php echo $i; ?>" style="width:80%" value="<?php echo $row_vendas['preco1'] ?>" autocomplete="off">
</td>
<td><input type="text" name="totalProduto" disabled class="disabled" id="totalProduto<?php echo $i?>" style="width:80%" autocomplete="off"></td>
<td><input type="checkbox" onClick="SomaTotais(<?php echo $i; ?>)" name="selecao[]" id="selecao<?php echo $i?>" value="<?php echo $i; ?>" style="width: 30px; height: 30px;"></td>
</tr>
<?php $i = $i+1; } while ($row_vendas = mysql_fetch_assoc($vendas));?>
</tbody>
</table>
JavaScript
function somaProduto(nro){
var qtd = $('#qtd'+nro+'').val();
var valUnit = DesFormataMoeda($('#preco'+nro).val());
total = qtd * valUnit;
$('#totalProduto'+nro+'').val(ConverteMoeda(total));
}
Fiz esta função, mas ainda não esta somando os valores:
function SomaTotais(nro){
var total = 0;
$("input:checkbox[data-id=selecao]:checked").each(function () {
var i = this.value;
var valor = DesFormataMoeda($('#totalProduto'+i).val());
total += valor
});
alert(ConverteMoeda(total));
}
A:
Resolvido aqui, alterei função e funcionou como queria.
function SomaTotais(){
var total = 0;
$("input:checkbox[data-id=selecao]:checked").each(function () {
var i = this.value;
var valor = Number(DesFormataMoeda($('#totalProduto'+i).val()));
total += valor;
$('#total').html(total);
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding element to a multidimensional array in PHP
I'm iterating over an array of courses, which all contain category IDs in the form of strings. I'm trying ro group them all by category using a matrix, but I'm having trouble doing that.
Here's an example of what I want:
$courses_by_code = [[2/11]=>[course1],[course2]], [[3/12]=>[course3], [course4]]
So my questions are:
How do I add an element that has a key that's already in the matrix to the array that corresponds to that key?
How do I create a new line in the matrix in case I find a new key?
A:
I am not sure I understood 100%, but from what I understood you should do something like:
$keyThatMightExist // '2/11' for example
if(isset($courses_by_code[$keyThatMightExist])) {
$courses_by_code[$keyThatMightExist][] = $newCourseToAdd;
} else {
$courses_by_code[$keyThatMightExist] = array($newCourseToAdd);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I safely use ADO.NET IDbConnection and IDbCommand to execute multiple database commands concurrently?
The Goal
Use an ADO.NET IDbConnection and IDbCommand to execute multiple commands at the same time, against the same database, given that the ADO.NET implementation is specified at runtime.
Investigation
The MSDN Documentation for IDbConnection does not specify any threading limitations. The SqlConnection page has the standard disclaimer saying "Any instance members are not guaranteed to be thread safe." The IDbCommand and SqlCommand documentation is equally un-informative.
Assuming that no individual instance member is thread-safe, I can still create multiple commands from a connection (on the same thread) and then execute them concurrently on different threads.
Presumably this would still not achieve the desired effect, because (I assume) only one command can execute at a time on the single underlying connection to the database. So the concurrent IDbCommand executions would get serialized at the connection.
Conclusion
So this means we have to create a separate IDbConnection, which is ok if you know you're using SqlConnection because that supports pooling. If your ADO.NET implementation is determined at runtime, these assumptions cannot be made.
Does this mean I need to implement my own connection pooling in order to support performant multi-threaded access to the database?
A:
You will need to manage thread access to your instance members, but most ADO implementations manage their own connection pool. They generally expect that multiple queries will be run simultaneously.
I would feel free to open and close as many connections as is necessary, and handle an exceptions that could be thrown if pooling were not available.
Here's an article on ADO connection pooling
| {
"pile_set_name": "StackExchange"
} |
Q:
How to show pdf file in GridView as thumbnail
I want to show some bunch of pdf file in my android application as GridView. Pdf file should be present as image in gridview as thumbnail. After clicking on that file, view should be generate as sliding navigation from pdf pages. For better understanding i am including two image here.
Any idea will be highly appriciated.
A:
You'd need to use a 3rd party library and open the pdf for display. Parsing and displaying PDFs is a time consuming activity. The usual way of getting around that for displays like this is to pre-render a thumbnail image of the pdf and download that over the net (or have it preinstalled in the apk) and display the pre-rendered thumbnail instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
VB.net Using a string to change something.Text
I need to work in VB.net for school and have encountered a problem.
The program works like this:
I've got a store page with buttons to buy them, they each have a name with the item and "_buy" after it. So if I wanted to buy a laptop, I'd press a button named laptop_buy.
What I want then is to make the event call the fuction Buy(laptop), so I can use the laptop ID later on.
I also have things named like laptop_level and laptop_price. I want to change them when I click the button. So I created this function:
Private Sub laptop_buy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles laptop_buy.Click
Buy("laptop")
End Sub
And
Function Buy(ByVal item)
Dim itemlevel As String = item + "_level.Text"
itemlevel += 1
End Function
So this should change the laptop_level.Text when I click laptop_buy.
But it isn't working.
Help is greatly appriciated!
A:
You can use ControlCollenction.Find method to get your label.
Then you need to cast it's text value to Integer (I recommend using Int32.TryParse method for that) and then add 1 and return the result to the label text. Something like this should do the trick.
Sub Buy(ByVal item As String)
Dim level As Inetger
Dim ItemLabel as Label;
Dim ChildControls As Control() = Me.Controls.Find(item & "_level", True)
If ChildControls.Length > 0 Then
ItemLabel = ChildControls(0)
End If
If not isNothing(ItemLabel) AndAlso Int32.TryParse(ItemLabel.Text, level) Then
ItemLabel.Text = (Level + 1).ToString
End If
End Sub
Note: Code was written directly here, and it's been a long time since my vb.net days, so there might be some mistakes in the code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento - Custom subject of order email
I have a service in PHP which interacts with a Magento website. I can't access the source code of this website. So I can use service to order a product and send a mail. When I call
$order->sendNewOrderEmail();
an email will be send to my email-id with subject Nuovo ordine # XXXXXXXXX.
Now I want add a string to this subject: TEST - Nuovo ordine # XXXXXXXXX.
How I can do it?
A:
In app/code/core/Mage/Sales/Model/Order.php find sendNewOrderEmail() method. Then find
$mailer->setTemplateParams(array(
'order' => $this,
'billing' => $this->getBillingAddress(),
'payment_html' => $paymentBlockHtml
)
);
Here is array of variables from template. Add one new param for test:
'test' => $is_test ? $is_test : ''
Change $is_test to your condition. For example:
public function sendNewOrderEmail($is_test = FALSE)
Now open your template file app/locale/en_US/template/email/sales/order_new_guest.html (for example).
Find subject variable on the first line: <!--@subject Nuovo ordine # {{var order.increment_id}} @--> or something like this.
Make changes:
<!--@subject {{var is_test}}Nuovo ordine # {{var order.increment_id}} @-->
Call method:
$order->sendNewOrderEmail('TEST - ');
| {
"pile_set_name": "StackExchange"
} |
Q:
Xpath - select nodes depending on preceding-siblings and following-siblings
I have a xml like this,
<doc>
<p><c type="changeStart"/><style type="underline">text</style><c type="changeEnd"/><t/>In addition
to voting Finance Company and Business Company, Inc.: (i) the name
of the <c type="changeStart"/>new public entity<c type="changeEnd"/> will be “Finance Company.”
as Finance Company’s corporate existence is perpetual as opposed to Business Company, Inc.’s corprate
existence terminating <c type="changeStart"/> <c type="changeEnd"/>
</p>
</doc>
I need to select the nodes exist between <c type="changeStart"/> and <c type="changeEnd"/>. So in above xml following nodes should be selected,
<style type="underline">text</style>
new public entity
two white spaces (' ')
I've written following xpath for that,
//*[preceding-sibling::c[@type = 'changeStart'] and following-sibling::c[@type = 'changeEnd']][not(c [@type="changeStart"])]
But it does not select the correct nodes. any suggesion how can I modify my xpath to select what I need?
A:
This is one possible XPath :
//node()[
preceding-sibling::*[1][self::c/@type='changeStart']
and
following-sibling::*[1][self::c/@type='changeEnd']
]
The above XPath select nodes that :
directly preceded by <c type="changeStart"/>, and..
directly followed by <c type="changeEnd"/>
| {
"pile_set_name": "StackExchange"
} |
Q:
With regards to Java Sets, how can you remove an element by its properties?
I have a HashSet in my code that uses a custom type, Line, where Line has four integer fields (x1, y1, x2, y2; all representing coordinates of start and end points of the line). I populate the HashSet with a large number of these Lines. I then want to later remove specific Lines. I tried calling HashSet.remove(new Line(correct properties)), but that failed. Any ideas on how I could go about doing this?
Attached is the code for reference. The class is attempting to implement an Aldous-Broder maze generator, such that initially all walls are populated into the set, and then walls are removed (as the method carves the maze paths), before being passed to the drawing mechanics.
package tests;
import java.util.HashSet;
import java.util.Random;
public class AldousBroderTest {
static HashSet<Line> walls = new HashSet<Line>();
static Random rn = new Random();
public static void generateWalls(int x1, int y1, int x2, int y2){
for (int i = x1; i < x2; i += 10){
for (int j = y1; j < y2; j += 10){
walls.add(new Line(i, j, i + 10, j));
walls.add(new Line(i,j,i,j+10));
}
}
walls.add(new Line(x1, y1, x1, y2));
walls.add(new Line(x1, y1, x2, y1));
walls.add(new Line(x2, y1, x2, y2));
walls.add(new Line(x1, y2, x2, y2));
}
public static void generateMaze(int x1, int y1, int x2, int y2){
boolean[][] visited = new boolean[x2-x1][y2-y1];
int counter = 1;
int currentx = rn.nextInt((x2-x1)/10)*10;
int currenty = rn.nextInt((y2-y1)/10)*10;
visited[currentx][currenty] = true;
int cellcount = (x2-x1)/10 * (y2-y1)/10;
System.out.println(cellcount);
while (counter < cellcount){
int direction = rn.nextInt(4);
switch (direction){
case 0:
if(currenty == y1){break;}
currenty -= 10;
if(visited[currentx][currenty] == false){
visited[currentx][currenty] = true;
counter++;
walls.remove(new Line(currentx, currenty+10, currentx+10, currenty+10));
}
break;
case 1:
if(currentx+10 == x2){break;}
currentx += 10;
if(visited[currentx][currenty] == false){
visited[currentx][currenty] = true;
counter++;
walls.remove(new Line(currentx, currenty, currentx, currenty+10));
}
break;
case 2:
if(currenty+10 == y2){break;}
currenty += 10;
if(visited[currentx][currenty] == false){
visited[currentx][currenty] = true;
counter++;
walls.remove(new Line(currentx, currenty, currentx+10, currenty));
}
break;
case 3:
if(currentx == x1){break;}
currentx -= 10;
if(visited[currentx][currenty] == false){
visited[currentx][currenty] = true;
counter++;
walls.remove(new Line(currentx+10, currenty, currentx+10, currenty+10));
}
break;
}
}
}
public static void main(String[] args){
generateWalls(0,0,50,50);
generateMaze(0,0,50,50);
Frame frame = new Frame(walls);
}
}
A:
In class Line, override equals and hascode methods.
@Override
public boolean equals(Object obj) {
// equals code
}
@Override
public int hashCode() {
// hascode method
}
And here you can find the explanation of "why to implement these two methods" Why do I need to override the equals and hashCode methods in Java?
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove a member from a group using Microsoft Graph .NET Client Library
What is the correct way to remove a member from a group using the Microsoft Graph .NET Client Library?
Adding a member can be done like this:
client.Groups["groupid"].Members.References.Request().AddAsync(objToAdd);
So i expected that there is something like:
client.Groups["groupid"].Members.References.Request().RemoveAsync(objToRemove);
The same question also applies to client.Groups["groupid"].Owners.References.
A:
Try this way:
client.Groups["group_id"].Members["member_id"].Reference.Request().DeleteAsync();
The API to remove a member is:
DELETE /groups/<id>/members/<id>/$ref
The DirectoryObjectReferenceRequest.DeleteAsync() method will use DELETE method to send the request.
| {
"pile_set_name": "StackExchange"
} |
Q:
Qt. Making a QGraphicsItem follow cursor at all times
I wish to make a custom graphics item to follow the cursor without needing to be clicked on. My view has setMouseTracking(true), my graphics item has setFlag(ItemIsMovable, true); setAcceptHoverEvents(true);, but it doesn't track the cursor, I have to click and drag it. What is the proper way to make a QGraphicsItem follow the cursor?
A:
You can only capture mouse event on an item if your cursor pass above it. For example, instead of clicking on the item, you can react on mouseMove events.
But you seem to want a more global behaviour. You could track mouseMoveEvent directly on your QGraphicsView (or on your QGraphicsScene if you have multiple views) (see mouseMoveEvent). After that, just keep a reference on your item and make it move each time you intercept an event
| {
"pile_set_name": "StackExchange"
} |
Q:
editor template align two components
I have an editor template for a grid using Telerik MVC grid and I have two kendo ui components in a grid cell. How can I get them to align next to each other i.e. side by side.
I have tried some css and placing them in div and align float but they render in separate spans and unsure on how to get them side by side any ideas?
Currently the search button is underneath the autocomplete textbox.
@model object
@*@Html.Kendo().AutoComplete().Name("LocationSearch").Placeholder("Type in your search item . . ").Filter("startswith").BindTo(new string[] { "UK","USA","FR","ES","TR","RU","PT"}).Separator(",")*@
@(Html.Kendo().AutoComplete()
.Name("DepartmentSearch")
.Filter("startswith")
.Placeholder("Type in your search item")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetDepartments", "Home");
})
.ServerFiltering(false);
})
)
@(Html.Kendo().Button()
.Name("Search")
.HtmlAttributes(new { type = "button", style="min-width:20px !important;"})
.Content("...")
)
A:
The autocomplete widget is created in a span added inline width via jquery and this worked. $("#DepartmentSearch").first().css('width', '65%');
| {
"pile_set_name": "StackExchange"
} |
Q:
How to match a pattern in the middle of another text?
I want to use java regex to fetch a number from a given URL.
The problem is the pattern should appear in the middle of the URL.
How can I fix my regex?
Pattern p = Pattern.compile("[.w]*/pins/[.d]+/edit");
Matcher m = p.matcher("https://mysite.com/providers/271/pins/4997/edit");
while (m.find()) {
String id = m.group();
}
A:
If you're looking to match 4997 and have no restrictions in your Pattern to validate the URL (which shouldn't be done with regex anyway), then you can use a simple solution based on "lookarounds":
String url = "https://mysite.com/providers/271/pins/4997/edit";
// | preceded by "pins/"
// | | 1 or more digits
// | | | followed by "/edit"
Pattern p = Pattern.compile("(?<=pins/)\\d+(?=/edit)");
Matcher m = p.matcher(url);
if (m.find()) {
// | whole group will only capture "\\d+"
System.out.println(m.group());
}
Output
4997
| {
"pile_set_name": "StackExchange"
} |
Q:
Highcharts component that creates secondary yAxis based on props.boolean
I'm creating a Highstock component with Highcharts using react wrapper. I want to enable a parameter to add a secondary yAxis. This is how my component is structured:
class BasicSeriesChart extends Component {
constructor(props) {
super(props);
const { data } = this.props;
const doubleYAxis = this.props;
}
const secondaryYAxis = { // Secondary yAxis
id: 1,
};
this.state = {
chartOptions: {
series: data.map((set, index) => ({
...set,
yAxis: doubleYAxis ? secondaryYAxis.id: 0,
})
}
};
render() {
const { chartOptions } = this.state;
return (
<HighchartsReact
highcharts={Highcharts}
constructorType="stockChart"
options={chartOptions}
allowChartUpdate
/>
);
}
}
BasicSeriesChart.propTypes = {
data: PropTypes.array.isRequired,
doubleYAxis: PropTypes.bool,
};
export default BasicSeriesChart;
I'm calling it on a separate file:
const doubleYAxis = true;
const chartData = mockData.map((series) => ({
...series,
}));
function HighStock() {
return(
<BasicSeriesChart
data={chartData}
doubleYAxis={doubleYAxis}
/>
);
}
export default HighStock;
To enable a secondary yAxis I know I can define chartOptions.yAxis with an array of objects instead of a single object, but I need to make it refactorable, my approach is to call the addAxis method.
My logic is, check the doubleYAxis and if true add the secondary Axis chart.addAxis(secondaryYAxis);, but where should I call that function on my component?
A:
You can use setState to manipulate the number of axes, for example:
toggleAxis(){
this.setState({
chartOptions: {
yAxis: this.state.chartOptions.yAxis.length === 2 ?
[{}] :
[{}, {}]
}
});
}
Live demo: https://codesandbox.io/s/highcharts-react-demo-5q9db
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ Vector Template operator []
Firstly I wanted to say this is a HW assignment and I just have questions in regards to the errors I'm facing
I made a vector template with an insert function that adds a data_type to the end of a dynamic array. This is what I have currently.
// Insert the value at the specified index by moving the tail
// when Size = Capacity the Vector has to be reallocated first
// to accomate the new element
void Insert(const DATA_TYPE& value, int index){
// If the Capacity is not large enough then ...
// allocate large vector
if (Size >= Capacity){
// 0. Let's boost the capacity
Capacity += CAPACITY_BOOST;
// 1. Allocate new larger vector
DATA_TYPE* newData = new DATA_TYPE[Capacity];
// 2. Copy from old Data into the newData
for( int i=0; i< Size; i++)
newData[i] = Data[i];
// 3. Delete the old Data
delete[] Data;
// 4. Replace old Data-pointer with the newData pointer
Data = newData;
}
// Move the tail
for(int i=index; i<Size;i++){
Data[i+1] = Data[i];
}
// Insert
Data[index] = value;
Size++;
}
DATA_TYPE& operator[] (int index) const{
return *this[index];
}
Note: Using Private Variables: Size, Capacity, Data(stores the dynamic array)
I'm pretty sure I've implemented the add or push_back function correctly. The problem is when ever I try to cout something like "cout << a[1]; " I get an error.
while compiling class template member function 'int &Vector<DATA_TYPE>::operator [](int) const'
with
[
DATA_TYPE=int
]
see reference to class template instantiation 'Vector<DATA_TYPE>' being compiled
with
[
DATA_TYPE=int
]
error C2440: 'return' : cannot convert from 'const Vector<DATA_TYPE>' to 'int &'
with
[
DATA_TYPE=int
]
A:
There should be 2 versions of your operator[]:
const DATA_TYPE& operator[] (int index) const;
DATA_TYPE& operator[] (int index);
What you have is a weird combination of the two.
You should also be returning
return Data[index];
Returning (*this)[index]; would result in an infinite recursive call (well, not infinite, you'll get a stackoverflow before that).
| {
"pile_set_name": "StackExchange"
} |
Q:
programatically duplicate xaml control in WP
I'm not getting how I could duplicate a XAML element pgrogramatically. For example if I define on XAML a rectangle om the middle of the screen, the user presses a button and I would like to duplicate this rectangle with all properties of it and then put it to the right of the first one, should this be possible?
A:
Sure - just do a deep copy of the properties you want inserted and then add it to the panel. Assuming your controls are in a StackPanel with horizontal orientation:
Rectangle newRect = new Rectangle()
{
Width = oldRect.Width,
Height = oldrect.Height,
Stroke = oldRect.Stroke,
// repeat for other values you want the same
};
myStackPanel.Children.Add(newRect);
| {
"pile_set_name": "StackExchange"
} |
Q:
As a postdoc with a one-year contract in Switzerland, am I allowed for a B visa?
I worked for a year in Switzerland, but I have been given an L visa, even as a European. This has strong limitations in terms of rentals and bank services. Other people got a B visa for the same contract. Was this a mistake, and how can my university enforce a request for a B visa ?
A:
When did you graduate? A new law came into effect in 2010 which requires that all new postdoc hires of individuals who held a PhD for more than 2 years at the start of the contract be only given L permits. (I only found out after I had a similar discussion with human resources a few weeks ago.)
If you have had your degree for less than 2 years, it is possible your university can sort it out for you. If you have had your degree for more than 2 years, there's pretty much nothing the universities can do (aside for lobbying for a change of the law).
In regards to bank services: for a place to put your money, try PostFinance for which you can open an account at most post offices. They care a bit less about the issue with the permits. The main problem with having an L instead of a B permit, with regards to banking in general, is that they may be unwilling to give you a credit card or extend you a loan; you shouldn't have problem getting a place to put your money.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamically change GSP template in view
I'd like to refresh a template according to a value selected in a select component.
Typically, I have 3 templates that I want to load in my view :
_templateA.gsp
_templateB.gsp
_templateC.gsp
In my GSP view, I have a select component with 3 choices:
A
B
C
How can I dynamically change the template loaded in the code :
<g:render template="*myTemplate*"/>
On the onChange event of the select component? (if I select "A", templateA is loaded, then if I select "B", templateA is removed and templateB is loaded)
A:
In the example below we're POSTing the form contents using serialize to the /myController/myAction action.
Then based on the selected option we render the appropriate template and update the myDiv div in the view.
gsp:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
$( document ).ready( function() {
$( '#mySelect' ).on( 'change' , function (event) {
$.ajax({
url: "/myController/myAction",
type: "POST",
data: $( '#myForm' ).serialize(),
success: function ( data ) {
$( '#myDiv' ).html( data );
},
error: function( j, status, eThrown ) { console.log( 'Error ' + eThrown ) }
});
});
});
</script>
</head>
<body>
<g:form name="myForm">
<g:select name="mySelect" from="${['A', 'B', 'C']}" />
</g:form>
<div id="myDiv"></div>
</body>
</html>
controller:
def myAction() {
render template: "template${params.mySelect}"
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to manage endless variations of a question with LUIS?
The bot will ask the following:
-"How many people will stay in the apartment? And how many rooms do the apartment have?"
If the user replies the following:
-"3 people will stay in my 2 bedroom apartment."
Then it´s easy to extract the information I need by the use of 1 Simple Entity with 2 Roles (AmountOfPeople and RoomsInApartment).
However, the user can reply to the questions in many different ways. For e.g:
-"3 people and one dog will stay in my 2 bedroom apartment."
Or
-"3 people will stay in my friend´s 2 bedroom cottage."
Or
-"3 people will not stay in my 2 bedroom apartment."
In these cases there are so much more information that needs to be taken into account. I just care about how many people will stay, which animals will stay is just noise. And if they will stay in their friend´s place I need to extract that info so I can take some action in my bot. The problem is that there are endless of variations of how the user can reply to the bot´s question in this situation.
I have gone through all the LUIS documentation on Microsofts site, however it only covers very simple utterances, so I dont find much guidance there.
I have made my best try to put this up in LUIS. See the pictures below (Here I use 1 Simple Enttiy and 7 Roles).
i´m not sure if this is the correct approach? I´m I really supposed to label every word with a enttiy as I am doing?
A:
A couple of suggestions:
No you do not need to label every word in an utterance with an entity. You should only label the significant parts such as the number of people, how many rooms there are, and the accommodation type. From these you an infer and relay to the user information e.g. if you're using Accomodation:AmountPersons then you know you're talking about people, so you only need to extract the number, not the subject and action.
Investigate patterns to simplify your variations.
Start simple then build on what you have later:
I don't know if in your scenario that additional "beings" such as pets is critical but I would start by stripping it right back to only supporting the base scenario - which is people staying.
Is the room type critical for your scenario? Presumably people are booking a room rather than sleeping on a couch. ;-) Again I would just go with accomodation type (apartment, cottage etc).
Break up your bot's question into two parts - first ask how many people are staying, then where they are staying. This will make your life easier in terms of adding utterances and patterns, again you can build on this functionality later if you want to support users entering one line.
I'm not sure if LUIS alone is the best tool for this, the Bot Framework supports dialogs and waterfall dialogs seem perfect for what you want. There is a sample project available in C# and NodeJS which should give you something to build from.
| {
"pile_set_name": "StackExchange"
} |
Q:
Framework7->CSS: How to make tabs under popover scrollable
My question pertains to framework7 implementation, but is basically a CSS question:
I have tabs under a popover. I need to make these tabs content vertically scrollable. The default implementation of tabs has scrolling enables, but when these tabs are placed under popover (modal if you like) then these tabs stop being scrollable.
I have made a basic fiddle, to better explain the issue. In the fiddle, if you click "Click Me" and then go to "Account" tab you will notice that the tab is not scrollable.
THanks
A:
There you go, fixed: https://jsfiddle.net/xbvqksu8/3/
This CSS was added:
.popover-inner {
max-height:100vh !important;
}
.list-block ul {
overflow-Y:auto;
}
If you want your menu to fit in the screen better change the 100vh to something lower. Good luck!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change the accent color on my Android app from blue to something else
All I want to do is change the accent color of my android app, but I'm having a tough time figuring out how to do that. The default for android is blue now, but I want to make it orange.
By accent color, I mean the accent of navigation tabs, the color that highlights when you hit lists, the accent color in pop up dialogs, etc.
I'm using actionbarsherlock if that matters.
Here is an image. I'd like to change the color of that blue accent throughout the app:
A:
It's been some time since you asked this question but now that google has released a new AppCompat version you can do what you want to achieve quite simply. The answer I'm giving you is inspired from android developer blog support library 2.2.1.
Add the support library to your project (I am assuming you are using Android Studio).
For that add these lines to the app.graddle file (assuming your module is named app).
dependencies {
compile 'com.android.support:appcompat-v7:22.2.0'
}
Set the theme of your application
These lines are to be added to your styles.xml file. As you can see there are a few items in this style. If you want to know what element they correspond to go check customize android status bar with material.
colorAccent is the color you want to change in the first place.
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat">
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primaryDark</item>
<item name="colorAccent">@color/accent</item>
<item name="android:textColorPrimary">@color/textColorPrimary</item>
<item name="android:windowBackground">@color/windowBackground</item>
<item name="android:navigationBarColor">@color/navigationBarColor</item>
</style>
You will also need to set your application theme in the Android manifest
<application
android:theme="@style/AppTheme" >
...
</application>
Change From Activity / ActionBarActivity to AppCompatActivity in your classes.
public class MainActivity extends AppCompatActivity
{
....
}
You will probably need to change some methods due to the AppCompatActivity. Look at the video in the first link to better understand that :)
Change your widgets to the AppCompat ones
<LineareLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.AppCompatTextView
android:id="@+id/text"
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v7.widget.AppCompatButton
android:id="@+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btn_start" />
</RelativeLayout>
Et voilà ! That's it you're all set :) You can now change the Accent color easily.
| {
"pile_set_name": "StackExchange"
} |
Q:
Defining scripted field based on nested object Array
I have index mapping like this:
{
"mappings": {
"session": {
"dynamic_templates": [
{
"string_fields": {
"match": "*",
"match_mapping_type": "string",
"mapping": {
"norms": "false",
"type": "keyword"
}
}
}
],
"properties": {
"applicationType": {
"type": "keyword"
},
"appVersion": {
"type": "keyword"
},
"bounce": {
"type": "boolean"
},
"browserFamily": {
"type": "keyword"
},
"browserMajorVersion": {
"type": "keyword"
},
"browserMonitorId": {
"type": "keyword"
},
"browserMonitorName": {
"type": "keyword"
},
"browserType": {
"type": "keyword"
},
"carrier": {
"type": "keyword"
},
"city": {
"type": "keyword"
},
"clientTimeOffset": {
"type": "integer"
},
"clientType": {
"type": "keyword"
},
"continent": {
"type": "keyword"
},
"connectionType": {
"type": "keyword"
},
"country": {
"type": "keyword"
},
"dateProperties": {
"type": "nested",
"properties": {
"value": {
"type": "date"
}
}
},
"device": {
"type": "keyword"
},
"displayResolution": {
"type": "keyword"
},
"doubleProperties": {
"type": "nested",
"properties": {
"value": {
"type": "double"
}
}
},
"duration": {
"type": "integer"
},
"endReason": {
"type": "keyword"
},
"endTime": {
"type": "date"
},
"events": {
"type": "nested",
"properties": {
"application": {
"type": "keyword"
},
"internalApplicationId": {
"type": "keyword"
},
"name": {
"type": "keyword"
},
"startTime": {
"type": "date"
},
"type": {
"type": "keyword"
}
}
},
"errors": {
"type": "nested",
"properties": {
"application": {
"type": "keyword"
},
"internalApplicationId": {
"type": "keyword"
},
"name": {
"type": "keyword"
},
"startTime": {
"type": "date"
},
"type": {
"type": "keyword"
}
}
},
"hasCrash": {
"type": "boolean"
},
"hasSessionReplay": {
"type": "boolean"
},
"internalUserId": {
"type": "keyword"
},
"ip": {
"type": "ip"
},
"isp": {
"type": "text"
},
"longProperties": {
"type": "nested",
"properties": {
"value": {
"type": "long"
}
}
},
"manufacturer": {
"type": "keyword"
},
"matchingConversionGoals": {
"type": "keyword"
},
"networkTechnology": {
"type": "keyword"
},
"newUser": {
"type": "boolean"
},
"numberOfRageClicks": {
"type": "integer"
},
"osFamily": {
"type": "keyword"
},
"osVersion": {
"type": "keyword"
},
"region": {
"type": "keyword"
},
"replayStart": {
"type": "date"
},
"replayEnd": {
"type": "date"
},
"screenHeight": {
"type": "integer"
},
"screenOrientation": {
"type": "keyword"
},
"screenWidth": {
"type": "integer"
},
"startTime": {
"type": "date"
},
"stringProperties": {
"type": "nested"
},
"syntheticEvents": {
"type": "nested",
"properties": {
"errorCode": {
"type": "short"
},
"errorName": {
"type": "keyword"
},
"name": {
"type": "keyword"
},
"sequenceNumber": {
"type": "integer"
},
"syntheticEventId": {
"type": "keyword"
},
"timestamp": {
"type": "date"
},
"type": {
"type": "keyword"
}
}
},
"tenantId": {
"type": "keyword"
},
"totalErrorCount": {
"type": "integer"
},
"totalLicenceCreditCount": {
"type": "integer"
},
"userActionCount": {
"type": "integer"
},
"userActions": {
"type": "nested",
"properties": {
"apdexCategory": {
"type": "keyword"
},
"application": {
"type": "keyword"
},
"cdnResources": {
"type": "integer"
},
"cdnBusyTime": {
"type": "integer"
},
"documentInteractiveTime": {
"type": "integer"
},
"domCompleteTime": {
"type": "long"
},
"domContentLoadedTime": {
"type": "long"
},
"domain": {
"type": "keyword"
},
"duration": {
"type": "integer"
},
"endTime": {
"type": "date"
},
"errorCount": {
"type": "integer"
},
"failedImages": {
"type": "integer"
},
"failedXhrRequests": {
"type": "integer"
},
"firstPartyBusyTime": {
"type": "integer"
},
"firstPartyResources": {
"type": "integer"
},
"frontendTime": {
"type": "integer"
},
"hasCrash": {
"type": "boolean"
},
"httpRequestsWithErrors": {
"type": "integer"
},
"internalApplicationId": {
"type": "keyword"
},
"internalKeyUserActionId": {
"type": "keyword"
},
"keyUserAction": {
"type": "boolean"
},
"loadEventEnd": {
"type": "double"
},
"loadEventStart": {
"type": "double"
},
"name": {
"type": "keyword"
},
"navigationStart": {
"type": "long"
},
"networkTime": {
"type": "integer"
},
"requestStart": {
"type": "long"
},
"responseEnd": {
"type": "long"
},
"responseStart": {
"type": "long"
},
"serverTime": {
"type": "integer"
},
"speedIndex": {
"type": "long"
},
"startTime": {
"type": "date"
},
"syntheticEvent": {
"type": "keyword"
},
"syntheticEventId": {
"type": "keyword"
},
"targetUrl": {
"type": "keyword"
},
"thirdPartyBusyTime": {
"type": "integer"
},
"thirdPartyResources": {
"type": "integer"
},
"type": {
"type": "keyword"
},
"visuallyCompleteTime": {
"type": "long"
}
}
},
"userExperienceScore": {
"type": "keyword"
},
"userId": {
"type": "keyword"
},
"userSessionId": {
"type": "keyword"
},
"userType": {
"type": "keyword"
}
}
}
}
}
As you can see there is nested array of userAction objects. Each user action has name. What I wan't to get is visualisation that presents top user actions that were last for users. In such case, it should be easy to create script field that will iterate over array and pick the last one. After that I should be able to chart name of this action because it should appear in root of my document. The problem is that I can do anything I want in painless editor and I will result with empty data.
doc['userActions.name'].values.length
Such query will return this:
[
{
"_id": "f2846475-da35-410f-a277-a9c780505c7b-2321974068_90-1592566612368",
"leaveAction": [
0
]
},
{
"_id": "f2846475-da35-410f-a277-a9c780505c7b-PSMRABCFTIKAAPHTBRCWFCUHIFKVRCAI-0-1592566070043",
"leaveAction": [
0
]
},
{
"_id": "f2846475-da35-410f-a277-a9c780505c7b-VHNFKTGJAKAUITINTQBLQTTABMOPRCQG-0-1592549380378",
"leaveAction": [
0
]
},
{
"_id": "f2846475-da35-410f-a277-a9c780505c7b-IPJMSOAHLRFTLOTUQFLSACMEUQPVNSUK-0-1592564823345",
"leaveAction": [
0
]
},
{
"_id": "f2846475-da35-410f-a277-a9c780505c7b-2407681831_23-1592566608240",
"leaveAction": [
0
]
},
{
"_id": "f2846475-da35-410f-a277-a9c780505c7b-AKLKLLJAUJMECTPUMFQCEFMIMRDLLBMF-0-1592566679605",
"leaveAction": [
0
]
},
{
"_id": "f2846475-da35-410f-a277-a9c780505c7b-CSCJIRGURTMMDKHRUTKIOHFBCDCTNKMM-0-1592566670783",
"leaveAction": [
0
]
},
{
"_id": "f2846475-da35-410f-a277-a9c780505c7b-UMRNDMCUEPMPELFAPOGLKUUPWJSJHCMG-0-1592566704280",
"leaveAction": [
0
]
},
{
"_id": "f2846475-da35-410f-a277-a9c780505c7b-CQSIAUKAAHHDAMTHCRMVUARHQAUQFMGB-0-1592566709232",
"leaveAction": [
0
]
},
{
"_id": "f2846475-da35-410f-a277-a9c780505c7b-SFMSPRJHUUDWHUHRKQCFPFTPRUNFGDVW-0-1592566721460",
"leaveAction": [
0
]
}
]
so even if there are user actions, I cannot count them (there is no user session without any action).
In general this should return what I need:
doc['userActions.name'].values[doc['userActions.name'].values.length - 1];
But I receive null values. I've check that this field is searchable and aggregatable, but nothing works here. I'm using ELK and Kibana in 6.8 version.
Kind regards,
Sebastian
A:
{
"script_fields": {
"userActions": {
"script": {
"source":
"""
def actions = params['_source']['userActions'];
return actions[actions.length- 1].name;
""",
"lang": "painless"
}
}
}
}
It will work for you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Generation of MD5 is slow and missing first char
Currently I am trying to generate an MD5 of a large data file (10mb+). My current logic generates an MD5 but is cutting off the first character of the MD5. Also, the process is fairly slow, taking at least thirty seconds maybe more.
How do I not get it to cut off first char of MD5?
How can I speed the generation process up?
UPDATED Current code:
File PATH = Environment.getExternalStorageDirectory();
File DATAFILE = new File(PATH + "/stuff/content/" + FILE);
Context context = MyApp.getAppContext();
MessageDigest md = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream(DATAFILE);
BufferedInputStream in = new BufferedInputStream(fis);
// generate MD5
byte[] dataBytes = new byte[1024];
int byteCount;
while ((byteCount = in.read(dataBytes)) > 0) {
md.update(dataBytes, 0, byteCount);
}
byte[] digest = md.digest();
// convert to readable string
String MD5;
StringBuffer hexString = new StringBuffer();
for (int i=0; i<digest.length; i++)
hexString.append(Integer.toHexString(0xFF & digest[i]));
MD5 = hexString.toString();
Log.i("GENERATED MD5", MD5);
Result:
02-19 15:44:59.528: I/GENERATED MD5(24222): cd8f8438957ea9db758ddd12d86e2ca
Should be:
"md5":"0cd8f8438957ea9db758ddd12d86e2ca"
Thanks.
A:
You (were) calling BuffererdInputStream.read() and MessageDigest.update() once for each byte in the input data.
Instead use a byte array as a buffer and call the array forms of these functions, it'll probably be faster.
Edit:
The reason your strings don't match is because the top bits of the first byte are 0, so Integer.toHexString() is returning "c" when you expect "0c".
You can fix this by using String.format to pad the hex digits with zeros.
Change your code from:
hexString.append(Integer.toHexString(0xFF & digest[i]));
To this (the 0xFF & isn't needed since you're working with bytes already):
hexString.append(String.format("%02x", digest[i]));
| {
"pile_set_name": "StackExchange"
} |
Q:
Developer Story thinks my work experience is incomplete
Trying out the Beta without doing much pre-reading. I noticed that it complained that "Work experience / education" was incomplete (see screenshot) so I filled it in. It still thinks it's missing though. A bug?
A:
I RTFM'ed and see that I didn't fill in "2 technologies" or fill in "150 char for responsibilities". I was planning to just keep it Title-Only, but I'll put them in to make Dev Story happy.
| {
"pile_set_name": "StackExchange"
} |
Q:
Problems with spacing in lstlisting with escaped code
Consider the following code:
\documentclass{beamer}
\usepackage{listings}
\begin{document}
\begin{frame}[fragile]{title}
\begin{lstlisting}[escapeinside={!*}{*!},]
int add
int !*\color{red}add*!
\end{lstlisting}
\end{frame}
\end{document}
As you can see, the spacing (or the font) in the word inside the escaped code changes. How can I make it to look the same?
I need to change specific parts inside the listing, but the spacing inconsistencies is a problem.
A:
In case what you want to highlight is part of the code, my suggestion would be, not to define !* and *! as escape-to-LaTeX delimiters, but to simply define them as "invisible" delimiters that highlight their content in red, instead. That way, you don't get any discrepancy in column alignment between the normal code and the highlighted code. See my MWE below.
In case the highlighted bit is not code, then I don't think you should concern yourself about such a discrepancy in column alignment. For instance, have a look at the bottom screenshot on this answer; do you find anything shocking?
\documentclass{beamer}
\usepackage{listings}
% Definition of custom delimiters
% (the `i' means the delimiters themselves don't get printed)
\lstset{moredelim=[is][\color{red}]{!*}{*!}}
\begin{document}
\begin{frame}[fragile]{title}
\begin{lstlisting}
int add
int !*add*!
\end{lstlisting}
\end{frame}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
You must log in to ask a question
Possible Duplicate:
Encouraging users to create an account (and keep it)
Is this now a feature - you can only ask a question if you signup for an account?
Are anonymous user questions now banned on SO?
A:
From the FAQ:
Do I have to login?
Hope that helps!
A:
Yes, it's a new policy.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mysql2::Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock'
When running rake db:migrate, I get this error:
Mysql2::Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
I've looked at other people's questions on here and none of their solutions have helped me, for example:
Solution One
mysql.server start
returns:
Starting MySQL
. ERROR! The server quit without updating PID file (/usr/local/var/mysql/something.pid).
Solution Two
mysqladmin variables | grep socket
returns:
error: 'Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)'
Check that mysqld is running and that the socket: '/tmp/mysql.sock' exists!
Further notes:
I tried reinstalling mysql using homebrew, which was successful, and I'm still receiving the same errors:
Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
A:
I solved it!
First, go to database.yml
Change host: localhost to host: 127.0.0.1
That's it!
Edit: This works temporarily, but when I restarted my computer today it began throwing up the same errors. The fix was to just install mysql from the website, then my application could successfully connect to mysql again.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why can I not use math (subtraction) in a for-loop condition?
I have two lists of strings, listA and listB. listA is longer, and I want to make listB the same size by adding empty strings to it.
This works:
int diff = listA.size() - listB.size()
for (int i = 0; i < diff; i++) {
listB.add("");
}
But this doesn't:
for (int i = 0; i < (listA.size() - listB.size()); i++) {
listB.add("");
}
Why is that?
A:
The first example the variable diff is constant whereas the second example the condition is evaluated on each iteration of the loop and therefore since you're adding objects during iterations the size of the list will change hence why both code snippets don't do the same thing.
I'd recommend you proceed with the first approach i.e caching the limit for the loop condition beforehand and not re-evaluating it during each iteration.
| {
"pile_set_name": "StackExchange"
} |
Q:
Matlab: How to factorize transfer function
I need to divide my transfer function into 2 transfer functions in such way that S2 = S1'
Actually I have product of S2*S1
s = tf('s')
Suu = -1.6/((s-4)*(s+4))
Sux = -0.8/((s+4)*(s-4)*(s^2 + 0.1*s + 1))
Sxx = 0.3*(s - 4.163)*(s + 4.163)/((s+4)*(s-4)*(s^2 - 0.1*s + 1)*(s^2 + 0.1*s + 1))
Sxu = Sux'
SxdSdx = Sxx - (Sxu*Sux)/Suu
How to determine Sxd and Sdx if Sxd = Sdx' ?
Anybody can help me?
A:
What you are looking to do is called spectral factorization. A good survey paper on spectral factorization algorithms is A. H. Sayed and T. Kailath, "A survey of Spectral Factorization Methods", Numer. Linear Algebra Appl., vol. 8, pp. 467-496, 2001.
If your transfer function is expressible as a rational function (i.e., a ratio of polynomials in s) that you can factor then you can choose S1 to be the rational function whose zeros (roots of the numerator polynomial) and poles (roots of the denominator polynomial) are all in the left half-plane (i.e., have real parts less than zero). If there are real roots these must come in pairs and you can assign one member of each pair to S1. If you do this then S1*conj(S1) will be the original transfer function.
The numerical method by which you factor your transfer function depends on the nature of your transfer functions poles and zeros (how many are there, how close are they, etc.), how you know your transfer function (do you know it via its polynomial coefficients? do you know it via its value at selected points in s space?), how accurately you know it (how accurately do you the transfer function coefficients), and how accurate you want your factorization to be.
| {
"pile_set_name": "StackExchange"
} |
Q:
Draw Rectangle in View
I want to draw a rectangle in my ViewController2.
I read that I can use CGRect but I can't find how to do it.
I want to represent a room, so i can place a dot in the position where i am in the room.
I've already tried to override drawRect method but i had some errors
I tried with this code:
// rectangle.h
#import <UIKit/UIKit.h>
@interface Rectangle : UIView
@property (nonatomic, assign) CGRect myRect;
@end
// rectangle.m
#import "rectangle.h"
@implementation Rectangle
@synthesize myRect;
- (void)drawRect:(NSRect)rect {
// Drawing code here.
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(c, 1.0, 0.0, 0.5, 1.0);
CGContextFillRect(c, myRect);
}
@end
// ViewController2.m
#import "ViewController2.h"
#import "rectangle.h"
@implementation ViewController2
// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad {
[super viewDidLoad];
if(![self.view isKindOfClass:Rectangle])
{
Rectangle *view = [[Rectangle alloc] initWithFrame:self.view.bounds];
self.view = view;
}
[(rectangle*)self.view setMyRect:CGRectMake(120, 120, 80, 80)];
[self.view setNeedsDisplay];
}
@end
But this doesn't work
A:
First of all I don't think you understand CGRect is a struct and not an object. It defines a rectangles point of origin and size which you need to then use with a UIView or another UI class.
Drawing a rect as @user2277872 has indicated takes a CGRect as its frame - Assigning it's point of origin in the view (x.y) and it's width and height (w,d)
to get that on to your view controller view you'll need to add it as a subview.
CGRect frame = CGRectMake(0, 0, 200, 400);
then do UIView *v = [[UIView alloc] initWithFrame:frame];
again as @user2277872 has indicated you can do this in the viewdidload method
only think he didn't tell you is that you should the write
[self.view addSubview: v];
another point to note is the view is usually white by default so you'll need to set the background colour if you want to see it
[v setBackgroundColor: [UIColor redColor]];
You should see a rectangle at the top of the view.
As you're using storyboards you could just drag a view on to the view controller and set it's colour and size there.
| {
"pile_set_name": "StackExchange"
} |
Q:
HTTP Auth request fails in browser due to CORS, ok in Node
I'm stuck trying to diagnose a problem where a GET request with HTTP Basic Auth succeeds in Node, but fails in the browser. The problem manifests directly as a CORS failure (there's no Access-Control-Allow-Origin on the 401 page).
request.js:119 OPTIONS http://HOST?PARAMS 401 (Unauthorized)
ClientRequest._onFinish @ request.js:119
(anonymous) @ request.js:61
...
17:53:59.170 localhost/:1 Failed to load http://HOST?PARAMS: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9966' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
The request looks like this:
const request = require("request-promise");
const options = {"url":"http://...?","auth":{"user":"...","pass":"..."},"json":true,"qs":{...},"headers":{},"resolveWithFullResponse":true}
request.get(options).then(...);
How this request shows up in Chrome:
What's surprising here to me:
The method is OPTIONS, not GET. (Which I didn't explicitly ask for.)
My auth credentials are not included in the headers (even though I haven't set sendImmediately: false
The "Provisional headers are shown" warning.
What I would like to know:
Is this expected behaviour?
If not, what's going wrong?
If yes, what's going wrong? :)
Running what would be the equivalent request on the command line seems to work fine:
curl -I 'http://MYUSERNAME:MYPASSWORD@SAMEURL?SAME=PARAMETERS' -H 'Origin: http://localhost:4466' -X OPTIONS
HTTP/1.1 200 OK
Date: Wed, 20 Jun 2018 07:29:28 GMT
Server: Apache-Coyote/1.1
Access-Control-Allow-Origin: http://localhost:4466
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: Access-Control-Allow-Origin,Access-Control-Allow-Credentials
Vary: Origin
X-Frame-Options: SAMEORIGIN
Allow: GET,HEAD,POST,OPTIONS
Content-Length: 0
However I notice that without the credentials supplied in the URL, there are no CORS headers on the response:
HTTP/1.1 401 Unauthorized
Date: Wed, 20 Jun 2018 07:45:26 GMT
Server: Apache/2.4.29 (Unix) OpenSSL/1.0.2l
WWW-Authenticate: Basic realm="Authentication Required"
Content-Length: 381
Content-Type: text/html; charset=iso-8859-1
Is that the correct behaviour?
Hypothesis
I suspect:
The browser is sending the OPTIONS "pre-flight" request because it has to, because the request is not a "simple request". (Not totally clear if this is the request library or the browser itself doing this)
The server is responding 401 because credentials weren't supplied, but isn't adding the CORS headers that it should.
Without the CORS headers the browser prevents the Request library accessing the result, so it can't complete the authentication.
What I'm not sure about:
Is the server misconfigured?
Is Request failing to pass credentials in the OPTIONS preflight request?
A:
The server is misconfigured. It’s not properly CORS-enabled. To be properly CORS-enabled it must respond to unauthenticated OPTIONS requests with a 200 or 204 status code.
Request isn’t “failing” to pass credentials in the OPTIONS preflight request. Request isn’t even making the the OPTIONS request. Instead the browser engine is, on its own.
And specifying the credentials flag for the request in your own code doesn’t cause credentials to get added to the preflight OPTIONS request. Instead, credentials only get added to the GET request from your own code — that is, if the preflight has succeeded and the browser actually ever moves on to making that GET request.
That’s because the CORS-protocol requirements in the Fetch specify that browsers must omit all credentials from preflight OPTIONS requests.
See https://fetch.spec.whatwg.org/#ref-for-credentials%E2%91%A5:
a CORS-preflight request never includes credentials
So the behavior you’ve encountered is intentional, by design.
For a related explanation in more detail, see the answer at HTTP status code 401 even though I’m sending an Authorization request header.
| {
"pile_set_name": "StackExchange"
} |
Q:
Memory leak by using observeEvent
I get cumulating memory using the following code. Every time I switch between the action button 1 and 2 the used memory increases.
library(ggplot2)
library(shiny)
library(lobstr)
ui <- navbarPage("Test",fluidPage(fluidRow(
column(width = 1, actionButton("action_input_1", label = "1")),
column(width = 1, actionButton("action_input_2", label = "2")),
column(width = 10, plotOutput("plot", width = 1400, height = 800)))))
server <- function(input, output) {
# 1
observeEvent(input$action_input_1, {
output$plot <- renderPlot({
plot(rnorm(100))
})
print(cat(paste0("mem used 1: ", capture.output(print(mem_used())),"\n")))
})
# 2
observeEvent(input$action_input_2, {
output$plot <- renderPlot({
plot(rnorm(1000))
})
print(cat(paste0("mem used 2: ", capture.output(print(mem_used())),"\n")))
})
}
shinyApp(ui, server)
Due to a suggestion in this post, I have tried not to use observeEvent. Here is the server function:
server <- function(input, output) {
# 1
output$plot <- renderPlot({
input$action_input_1
plot(rnorm(100))
print(cat(paste0("mem used 1: ", capture.output(print(mem_used())),"\n")))
})
# 2
output$plot <- renderPlot({
input$action_input_2
plot(rnorm(1000))
print(cat(paste0("mem used 2: ", capture.output(print(mem_used())),"\n")))
})
}
Here the memory does not increase, but only the second action button (=the last block of code?) is working. Is there a solution to prevent memory leak and get both buttons working?
A:
How about using reactiveVal :
reactiveData <- reactiveVal(NULL)
observeEvent(input$action_input_1, reactiveData(rnorm(100)))
observeEvent(input$action_input_2, reactiveData(rnorm(1000)))
output$plot <- renderPlot(plot(reactiveData()))
Reactive values have a little different syntax:
reactiveData <- reactiveValues(rnorm = NULL, bool_val = NULL)
observeEvent(input$action_input_1, {# reactiveData(rnorm(100), bool_val <- TRUE))
reactiveData$rnorm <- rnorm(100)
reactiveData$bool_val <- TRUE
})
observeEvent(input$action_input_2, { #reactiveData(rnorm(1000), bool_val <- FALSE))
reactiveData$rnorm <- rnorm(1000)
reactiveData$bool_val <- FALSE
})
output$plot <- renderPlot(plot(reactiveData$rnorm))
Though your variables are changing in concert, so you could technically still use reactiveVal
reactiveData <- reactiveVal(list(rnorm = NULL, bool_val = NULL))
observeEvent(input$action_input_1, reactiveData(list(rnorm = 100, bool_val = TRUE)))
observeEvent(input$action_input_2, reactiveData(list(rnorm = 1000, bool_val = FALSE)))
output$plot <- renderPlot(plot(reactiveData()$rnorm))
| {
"pile_set_name": "StackExchange"
} |
Q:
Ajax response undefined on .keyup operation
I have created a input formfield for a user to type in a captcha that they see from an image created by Coldfusion's cfimage tag and stored in a session var. When the user types in the captcha into the input formfield, jQuery calls a Coldfusion CFC to check if the captcha the user entered matches the session var. If the user matches the captcha, the submit button is shown. All seems to working fine until the response comes back. Here is my code.
HTML
<input type="text" id="mailform-input-captcha" name="captcha" placeholder="Type in Captcha *" data-constraints="@NotEmpty"/>
jQuery
$(document).ready(function() {
$('#mailform-input-captcha').keyup(function(){
var captcha = $('#mailform-input-captcha').val();
$.ajax({
type: "POST",
url: "cfc/handy.cfc?method=chk_captcha&returnformat=json",
datatype: "json",
data: {
captcha: captcha
},
cache: false,
success:function(data) {
if(data && data.length) { // DO SOMETHING
$.each(data, function(i, val) {
console.log(val);
console.log(data[i].status);
// *** SUCCESS ***
if(status == "SUCCESS") { // DO SOMETHING
$('.btn').show();
alert(status);
// *** FAIL ***
} else if(status == "FAIL"){ // DO SOMETHING
$('.btn').hide();
}
});
}
}
});
});
If I type letters in the input formfield, the response comes back as an array of structures from the CFC. Here is an example of the response.
Response
[{"STATUS":"FAIL"}]
When I look in the chrome debugger I see the following:
console.log(val); logs each individual character in the array
instead of each structure.
console.log(data[i].status); logs as "undefined".
The site is utilizing jQuery 1.7.1 I have tried a newer version of jQuery and did not see a change. This script has worked on other sites just fine. Thank you for any input you may have.
A:
You have a typo in datatype which should be dataType
Also a good idea to return appropriate Content Type header. Since dataType is not set and header isn't application/json it seems to be treating the response as text
Also note that javascript is case sensitive so you need to check data[i].STATUS or change the output
| {
"pile_set_name": "StackExchange"
} |
Q:
How to go new line when table cell characters reached 10 charachers in html
I don't know how to go new line with limited characters.
Help me!
<table >
<tr>
<th>Date</th>
<th>Name</th>
<th>Comment</th>
</tr>
<tr>
<td>2017/08/25</td>
<td>Jackson</td>
<td>commentcommentcommentcommentcommentcommentcommentcommentcomment</td>
</tr>
</table>
A:
<table >
<tr>
<th>Date</th>
<th>Name</th>
<th>Comment</th>
</tr>
<tr>
<td>2017/08/25</td>
<td>Jackson</td>
<td style="word-break: break-all">commentcommentcommentcommentcommentcommentcommentcommentcomment</td>
</tr>
</table>
Use word-break:break-all;
| {
"pile_set_name": "StackExchange"
} |
Q:
Java: Hashmap with contents compiled
I am looking to implement a HashMap with its contents in the bytecode. This would be similar to me serializing the content and then reading it in. But in my experience serialization only works with saving it to a file and then reading it in, I would want this implementation to be faster than that.
A:
But in my experience serialization only works with saving it to a file and then reading it in, I would want this implementation to be faster than that.
Serialization works with streams. Specifically, ObjectOutputStream can wrap any OutputStream. If you want to perform in-memory serialization, you could use ByteArrayOutputStream here.
Similarly on the input side.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does using the Rules as Written tag restrict answers to only using RAW?
It has come up several times in the last couple days that people have told posters not to add or to remove rules-as-written to/from their answers because it would force answerers to only use RAW.
For example (from this question):
Person A: Might I suggest adding the 'rules-as-written' tag, just to make it clear that you are looking for an exact-words reading of the rules based answer
Person B: Might I suggest not adding that [RAW] tag unless you have
some specific, explained reason for wanting a RAW answer?
And from this question:
As you point out, the RAW is in conflict with itself. Thus we cannot give a RAW compliant answer. You should remove the [RAW] tag.
But my reading of the tag description does not read that way at all:
Questions that are about the logical interactions of a game's rules under a strictly literal reading. Not for questions about normal clarifications of the written rules. Answering rules questions with house-rules and opinions will already be restricted by our site's rules.
So, does using the rules-as-written actually restrict answers to using a strictly RAW interpretation? Can you not answer with a well-sourced Rules as Intended answer for example?
Note: I am aware this was a matter of quite a bit of drama on this site historically. My intent is not to dredge this up, but it is clear that there is confusion about the matter and I was not able to find a clear and definitive answer by digging through all the old posts.
A:
The tag itself means nothing.
Using the rules-as-written tag means and does nothing. It is just a tag. It exists solely to categorise and describe the question based on content already found in the question itself. It introduces no magical rules or restrictions and no new information, and implies nothing whatsoever not already found in the question text.
All of this is true for all tags. Game system tags are the one and only exception where we might introduce altogether new information in tags alone.
This means if the question does not appear to be laying down any requirements for rules-as-written or legalistic interpretations, rules-as-written should not be tagged on the question. If the question is clearly requesting RAW (or otherwise requesting strict legalistic rules interpretation) it should be tagged rules-as-written. Add or remove the tag as necessary so as to meet these guidelines.
These things were not always the case for the rules as written tag: it used to introduce magical rules all on its own by the mere fact of being present, but that did not work very well for us, and we walked that back to this current state (the default state) 2½ years ago in A low-intervention approach [rules-as-written]: back to tagging basics.
Focus on the question content, not on the tag. Tag to describe and categorise based on the question content.
If someone's asking for RAW information, that doesn't mean only RAW is allowed.
Let's be clear: if someone's asking about how the RAW works, they are seeking that information and answers should be telling them how the RAW works. Answers not telling them that are probably unhelpful.
However:
It is perfectly OK to talk about RAW, but then also talk about other stuff. It is fairly normal for a RAW answer to explain the RAW itself... then also explain problems with it, introduce Good Subjective expertise to advise how to better handle the situation, or so on. This is common, normal, and good practice when relevant and helpful. We're fine with doing this.
Declining to answer with the RAW and instead answering another way is also an option. It's a form of frame challenge. Much like any frame challenge this is risky. The answer might be helpful, but it might not and instead get strongly downvoted. Proceed at your own risk.
Focus on the querent's problem and their situation and provide a helpful response that helps them figure out their problem. Their problem involves wanting to understand RAW, so respect that in your answer and help them find that understanding (or don't at your own risk). This is no different from what we'd do with any other kind of question in any other tag.
On the situations you cited
Person A: Might I suggest adding the 'rules-as-written' tag, just to make it clear that you are looking for an exact-words reading of the rules based answer
Person B: Might I suggest not adding that [RAW] tag unless you have some specific, explained reason for wanting a RAW answer?
Person A is correct to suggest the RAW tag be added, but for the wrong reasons. The question is already clearly requesting RAW. This alone means we should tag it with RAW. That it draws attention to this question being about RAW is a side benefit but isn't the reason to tag in and of itself.
Person B is incorrect to request the tag not be added: we don't need someone to explain their reasoning before a tag gets applied. It's valid to ask for reasoning, but as far as tagging is concerned, we don't care whether or what reasoning is present. The tag fits, so add it. Go ahead and leave a comment requesting clarification about their reasoning if you feel it's material to the question, though.
As you point out, the RAW is in conflict with itself. Thus we cannot give a RAW compliant answer. You should remove the tag.
This line of reasoning is invalid and I've removed this comment. The querent is asking for rules as written information. Also, as stated, the tag doesn't mean anything, so fussing about the tag is pointless.
If the RAW is invalid, answer with that and show that. It's not unusual for RAW to look a bit like nonsense once we scrutinise it legalistically.
Most important takeaway:
rules-as-written is just a tag, nothing else. Focus on the question content. Tag according to question content. Don't focus on the tag this much. It does nothing other than be a tag. It has no rules attached. We wouldn't fuss about spells like this, we shouldn't fuss about rules-as-writen any moreso.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does C# Stopwatch pause when my computer goes to sleep?
I'm measuring the runtime of my program (written in C#) with Stopwatch. My computer went sleep, and I don't know that the time data it shows is correct or not. So is Stopwatch measuring the sleep time too or it was paused then continued?
A:
According to source code for StopWatch the method Start looks like this:
public void Start() {
// Calling start on a running Stopwatch is a no-op.
if(!isRunning) {
startTimeStamp = GetTimestamp();
isRunning = true;
}
}
The method Stop looks like this:
public void Stop() {
// Calling stop on a stopped Stopwatch is a no-op.
if( isRunning) {
long endTimeStamp = GetTimestamp();
long elapsedThisPeriod = endTimeStamp - startTimeStamp;
elapsed += elapsedThisPeriod;
isRunning = false;
if (elapsed < 0) {
// When measuring small time periods the StopWatch.Elapsed*
// properties can return negative values. This is due to
// bugs in the basic input/output system (BIOS) or the hardware
// abstraction layer (HAL) on machines with variable-speed CPUs
// (e.g. Intel SpeedStep).
elapsed = 0;
}
}
}
So the answer of your question is: It measures the duration by using two timestamps which leads to the conclusion that it doesn't matter whether your computer goes to sleep or not.
Update (thanks Mike and Joe):
However, if your computer is sleeping, it cannot run your program - so the measured duration would be the sum of the duration the program has been running and the duration where the computer has been sleeping.
TotalDuration = CalculationDuration + SleepDuration.
A:
The stopwatch does not pause when the computer enters sleep.
It uses the Windows API QueryPerformanceCounter() function, which does not reset the count when the computer goes to sleep:
"QueryPerformanceCounter reads the performance counter and returns the
total number of ticks that have occurred since the Windows operating
system was started, including the time when the machine was in a sleep
state such as standby, hibernate, or connected standby."
| {
"pile_set_name": "StackExchange"
} |
Q:
Help on proving that $\{x:f(x)>\alpha\}=\bigcup_{n=1}^{\infty}\{x:f(x)\geq \alpha+\frac{1}{n}\}$.
I am currently studying Real Analysis by Royden. In one of the proof of an important theorem on measurable functions, it was stated that:
$\{x:f(x)>\alpha\}=\bigcup_{n=1}^{\infty}\{x:f(x)\geq \alpha+\frac{1}{n}\}$.
But the book did not show that indeed the statement is TRUE. In showing that the statement is TRUE, one must use double set inclusion. Here is what I have done.
Let $z\in \bigcup_{n=1}^{\infty}\{x:f(x)\geq \alpha+\frac{1}{n}\}$. Then there is an index $n$ such that $z\in \{x:f(x)\geq \alpha+\frac{1}{n}\}$. That is, for that $n$ we have $f(z)\geq \alpha+\frac{1}{n}$. But $f(z)\geq \alpha+\frac{1}{n}$ means that $f(z)>\alpha$. Thus $z\in \{x:f(x)>\alpha\}$.
Is this correct? Also, how do we show the reverse inclusion? Lastly if $\alpha<\beta<\alpha +\frac{1}{n}$, is it true that $\bigcup_{n=1}^{\infty}\{x:f(x)\geq \alpha+\frac{1}{n}\}=\bigcup_{n=1}^{\infty}\{x:f(x)> \beta\}$?
Thanks for the help.
A:
Your proof is correct. As for your last question, $\beta$ is fixed so the latter union is just $\{f > \beta \}$ which in general will not coincide with $\{f > \alpha\}$.
Regarding the proof in the other direction: suppose that $x \in \{f > \alpha\}$, that is, $f(x) > \alpha$. In paticular, $0 < f(x) - \alpha$ and so by archimedianity, there exists $n \in \mathbb{N}$ such that $\frac{1}{n} < f(x) - \alpha$, which is equivalent as saying $\alpha + \frac{1}{n} < f(x)$, i.e. $x \in \{f > \alpha + \frac{1}{n}\} \subseteq \bigcup_{n \in \mathbb{N}}\{f > \alpha + \frac{1}{n}\}$.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to use asyncio and multiprocess.map to get data
I am using asyncio to get the webpage.
However, the speed is not very high.
Here is the code:
async def get_page_url(url, session):
res = await session.request(method="GET", url=url)
return await res.text()
async def main_get_page_url(urls):
async with ClientSession() as session:
tasks = [get_page_url(url, session) for province, url in urls]
result = await asyncio.gather(*tasks)
return result
if __name__ == '__main__':
urls = ['http://www.cnn.com', 'http://www.bbc.com']
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
loop = asyncio.get_event_loop()
df = loop.run_until_complete(main_get_page_url(urls))
I want to use multiprocessing.pool and map to increase the speed.
I have searched the web but cannot find any good method.
How to modify the code?
Any other better approach?
Thank you very much
A:
You won't achieve anything using more processes. 99% of script execution time takes network I/O which you already handle using asyncio.gather. Only 1% of time takes CPU. Optimizing it already isn't worth investing time and increasing code complexity. If fact cost of spawning multiple processes may instead slowdown your script.
If you think your code runs slow than it should you should find a bottleneck in the first place and try to optimize it. Can't help you much more without fully reproducible example with actual code, urls and time measurements.
Disclaimer:
99% of script execution time takes network I/O
It's very rough approximation, but it's fair, take a look at this answer and especially at results at the very end of it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Django cannot assign, "Rating.exercise" must be a "Exercise" instance
Localhost Screenshot
I have following requirement:
There are exercises and there are ratings
An exercise can have multiple ratings
My goal is to add ratings to the exercises dynamically i.e. I have created all the exercises before hand and rating to a particular exercise I should be able add afterwards calling some function. When I hit 'save_rating' view I get the error "Cannot assign "[]": "Rating.exercise" must be a "Exercise" instance."
What am I doing wrong?
My models.py looks like following
class Exercise(models.Model):
#Field for storing exercise type
EXERCISE_TYPE_CHOICES = (
('BS', 'Best stretch'),
('BR', 'Butterfly reverse'),
('SR', 'Squat row'),
('PL', 'Plank'),
('PU', 'Push up'),
('SP', 'Side plank'),
('SQ', 'Squat'),
)
exercise_type = models.CharField(max_length=5,choices=EXERCISE_TYPE_CHOICES)
#Field for storing intensity level
INTENSITY_LEVEL_CHOICES = (
(1, 'Really simple'),
(2, 'Rather Simple'),
(3, 'Simple'),
(4, 'Okay'),
(5, 'Difficult'),
(6, 'Rather Difficult'),
(7, 'Really Difficult'),
)
intensity_level = models.IntegerField(choices=INTENSITY_LEVEL_CHOICES)
#Field for storing video url for a particular exercise
video_url = models.URLField()
#Field for storing description of the exercise
description = models.CharField(max_length=500)
class Rating(models.Model):
#Field for storing exercise type
exercise = models.ForeignKey(Exercise, related_name='ratings', blank=True, null=True)
#Field for storing rating
RATING_CHOICES = (
('H', 'Happy'),
('N', 'Neutral'),
('S', 'Sad'),
)
value = models.CharField(max_length=1,choices=RATING_CHOICES)
I have defined my serializer like following:
class RatingSerializer(serializers.Serializer):
class Meta:
model = Rating
fields = ('value')
class ExerciseSerializer(serializers.Serializer):
pk = serializers.IntegerField(read_only=True)
exercise_type = serializers.CharField(required=True, allow_blank=False)
intensity_level = serializers.IntegerField(required=True)
video_url = serializers.URLField(required=True)
description = serializers.CharField(required=True, allow_blank=False)
ratings = RatingSerializer(many=True, read_only=True)
My views:
def exercise_list(request):
"""
List all exercises.
"""
if request.method == 'GET':
exercises = Exercise.objects.filter(exercise_type='BS', intensity_level=1)
serializer = ExerciseSerializer(exercises, many=True)
return JSONResponse(serializer.data)
def save_rating(request):
"""
Save a rating for a specific exercise.
"""
#Get a specific exercise for which you want to save the rating
specificExercise = Exercise.objects.filter(exercise_type='BS' , intensity_level=1)
#Create a rating and pass the specific exercise reference to it
Rating.objects.create(exercise = specificExercise, value='H')
#serializer = ExerciseSerializer(rating, many=True)
serializer = ExerciseSerializer(instance=specificExercise)
return JSONResponse(serializer.data)
A:
In your function save_rating, you are having specificExercise as a queryset not one Exercise instance, so when you do:
Rating.objects.create(exercise=specificExercise, value='H')
You try to assign a queryset to your exercise field, which of course doesn't work.
Simple fix would be using get instead of filter so you got one instance. But you also have to make sure the get query doesn't throw DoesNotExist exception, so a simple try except would do.
Edit:
def save_rating(request):
"""
Save a rating for a specific exercise.
"""
# Get a specific exercise for which you want to save the rating
try:
specificExercise = Exercise.objects.get(exercise_type='BS',
intensity_level=1)
# Create a rating and pass the specific exercise reference to it
Rating.objects.create(exercise = specificExercise, value='H')
# serializer = ExerciseSerializer(rating, many=True)
serializer = ExerciseSerializer(instance=specificExercise)
return JSONResponse(serializer.data)
except Exercise.DoesNotExist:
# TODO: you need to return some error indication that there's no such exercise
return None
Please read django doc about making queries.
| {
"pile_set_name": "StackExchange"
} |
Q:
My hot water boiler failed **On** - what would cause that?
I arrived back from holiday to find the house like a sauna, everything in the kitchen too hot to touch, cutlery scalding hot etc. My central heating was on full, and must have been for some days.
Quick check of the thermostat showed it was working fine, but turning the central heating timer on or off had no effect. I have had to remove the fuse to the boiler power. Two days later with all windows open 24 hours a day it is still unbearably hot.
I had a look at this question, but the symptoms don't seem to match. If I pop the fuse back I have scalding hot water and radiators no matter what the settings on my central heating.
A:
Despite scouring the Internet, I didn't find the solution - the gas man came today and after describing the symptoms to him he identified it immediately:
Faulty zone valve contact switch
Basically, the sequence is as follows:
Timer turns on - sends current to thermostat
Temperature is too low - thermostat relay sends current to zone valve
Zone valve turns fully on - contact switch triggers to instruct boiler to fire up
Timer turns off or temperature reaches threshold - current no longer passed to zone valve
Zone valve turns off - But faulty return spring kept switch on instructing boiler to remain on
It turns out that these zone valves have a plastic casing, rather than a metal one, so the return spring hooks around a small plastic spur... which just snapped off.
The fix: popping in a small screw to hook the spring round
Callout charge: £90
| {
"pile_set_name": "StackExchange"
} |
Q:
How do protect yourself against SQL injection when using prepared statements/store procedures in PHP?
I've been looking at how best to protect against sql injection in PHP/mysql beyond just using the mysqli/mysql real escape since reading this Is mysql_real_escape_string enough to Anti SQL Injection?
I have seen this very good thread How can I prevent SQL injection in PHP?
I use to do alot of ms sql server stuff on the desktop/internal tools, we always wrote stored procedures to protect against this so I read up on the equivalent in PHP/mysql using PDO http://php.net/manual/en/pdo.prepared-statements.php
In the above there is the line :
The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).
I've been lead to believe that PDO do protect against sql injection attacks so can anyone provide a instance where PDO isnt sufficient from a security standpoint?
A:
You can still get SQL injections from stored procedures which are internally using the PREPARE syntax (in MySQL) to create dynamic SQL statements.
These need to be done with extreme care, using QUOTE() as necessary.
Ideally, we should not need to use PREPARE in stored routines, but in certain cases it becomes very difficult to avoid:
Prior to MySQL 5.5, the LIMIT clause cannot use non-constant values.
Lists used in an IN() clause cannot be (sensibly) parameterised, so you need to use dynamic SQL if this pattern is used
It is sometimes desirable to use dynamically generated ORDER BY clauses.
etc
In the case where it is necessary to use PREPARE, then I would recommend, in order of preference:
If something is an INT type (etc) it is not susceptible to SQL injection, and you can place the value into the query without a problem (e.g. for LIMIT)
String values can be placed into an @variable before the EXECUTE, or passed in to the EXECUTE clause
List-values (for example for IN()) need to be checked for validity.
Finally, QUOTE() can be used to quote string values, which can be useful in some cases
| {
"pile_set_name": "StackExchange"
} |
Q:
Enviar email uma vez por dia
Boa Tarde,
Como eu faço para enviar email uma vez por dia. Eu utilizo o phpmailer.
Eu tentei usar o while, porém não sei que função determina a quantidade de a cada 24 horas.
meu código:
$assunto = "[RemocenteR] Nova Tarefa Cadastrada!";
$mensagem = "Prezado usuário, foi enviada uma tarefa pelo sistema remocenter para você. Acesse o menu e verique as tarefas pendentes";
$dadosDaTarefa = '<br><br>';
$dadosDaTarefa .= '<strong>Dados da Tarefa</strong>';
$dadosDaTarefa .= '<br>';
if($TA_TAREFA != ""){
$dadosDaTarefa .= 'Tarefa: ' . $TA_TAREFA;
$dadosDaTarefa .= '<br>';
}
if($TA_DESCRICAO != ""){
$dadosDaTarefa .= 'Descrição: ' . $TA_DESCRICAO;
$dadosDaTarefa .= '<br>';
}
if($TA_PRAZO != ""){
$dadosDaTarefa .= 'Prazo: ' . $TA_PRAZO_BR;
$dadosDaTarefa .= '<br>';
}
if($TA_PRIORIDADE != ""){
$dadosDaTarefa .= 'Prioridade: ' .$TA_PRIORIDADE;
$dadosDaTarefa .= '<br>';
}
if($TA_SOLICITANTE != ""){
$dadosDaTarefa .= 'Soliciante: '. $TA_SOLICITANTE;
$mensagem .= $dadosDaTarefa;
}
$mensagem .= '<br><br>';
$mensagem .= 'Mensagem gerada automaticamente pelo Sistema!';
if(sendMail('[email protected]',$FET_USUARIO['US_EMAIL'], $mensagem, $assunto)){
echo '<script language = "javascript">alert("Tarefa registrada, foi enviado um e-mail para notificar o solicitado!")</script>';
}
echo ("<script language='javascript'>location.href='tarefas.php'</script>");
}
Obrigada pela força
A:
Da forma que está tentando fazer não irá funcionar. PHP é diferente de outras linguagens que fica rodando de forma intermitente no servidor. Ele possui um ciclo de começo, meio e fim. E o fim é o fim mesmo.
Para resolver o seu problema, você pode utilizar CronJobs (Linux) ou o Agendador de tarefas (windows).
A definição é simples: agende a execução diária do seu script. Pode ser programado para rodar a cada 24 horas ou em outros intervalos.
Sendo assim, a cada 24 horas o seu script será chamado e enviará os emails.
Para Cron, pode olhar no link abaixo:
Como rodar cron job no servidor
Cron (ambientes Linux):
1 2 3 4 5 /root/script.php
Para o agendador de tarefas, pode utilizar o link abaixo:
Executar script PHP no agendador de tarefas do Windows
Agendador de tarefas (Task Scheduler - ambientes Windows):
c:/caminhocorreto/php [ -f ] c:/caminho/para/o/script.php
Além do que, o Agendador de Tarefas é visual.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get the selected value from a springform:select and use it as a parameter href
I wanna know how can I get the selected value from
<springform:select id="novoPlastico" class="input" path="novoPlastico.codPlastico" value="${form.novoPlastico.codPlastico}">
<option value=-1>Selecione</option>
</springform:select>
And
<td><springform:select id="grupoAfinidade" class="input" path="grupoAfinidade.grp" value="${form.grupoAfinidade.grp}" onchange="carregarNovosPlasticos();">
<option value=-1>Selecione</option>
</springform:select></td>
And use these values in the following href
<a href="${pageContext.request.contextPath}/parametros/migrCanais.do?plastNovo=${
--HERE I WANT THE FIRST SELECTED VALUE -- }&grp=${ -- HERE I WANT THE SECOND SELECTED VALUE --}" class="bt"><span>Go!</span></a>
EDIT1:
<script type="text/JavaScript" language="JavaScript" src="${pageContext.request.contextPath}/js/jquery-2.1.4.min.js"></script>
jQuery. noConflict();
jQuery("#btConfirma").on("click", function(e) {
e.preventDefault();
var value1 = jQuery("#novoPlastico").val();
var value2 = jQuery("#grupoAfinidade").val();
window.location.href = ctx + "/parametros/migrCanais.do?plastNovo=" + value1 + "&grp=" + value2;
});
<a id="btConfirma" class="bt" href="#"><span>Confirmar migração de canais de venda</span></a>
A:
First add this inside your jsp head element:
<script type="text/javascript">var ctx = "${pageContext.request.contextPath}"</script>
After that try with following javascript code:
$(".bt").on("click", function(e) {
e.preventDefault();
var value1 = $("#novoPlastico").val();
var value2 = $("#grupoAfinidade").val();
window.location.href = ctx + "/parametros/migrCanais.do?plastNovo=" + value1 + "&grp=" + value2;
})
| {
"pile_set_name": "StackExchange"
} |
Q:
Confused in my Left Join
I'm wracking my brain on this one and I think it is not quite as challenging as I'm making it out to be. Effectively what I am trying to do is:
Calculate the monthly average of sales while excluding the days that are holiday type 1 which apply to all regions (I can change this to Type 2 for a specific region, for example).
SELECT Year(Date) AS Year, Month(Date) AS Month, Avg(tblSales.Sales) AS AvgSales
FROM tblSales
LEFT JOIN tblHolidays
ON tblSales.[Date] >= tblHolidays.[Date From] AND tblSales.[Date] <= tblHolidays.[Date To]
WHERE tblHolidays.[Date From] Is Null AND tblHolidays.[Type]<> 1 AND tblHolidays.[Region]<>"All"
GROUP BY Year(Date), Month(Date);
Right now I'm not sure that I understand whether or not this is working, while it does produce results. What I'm not seeing is where it is telling tblHolidays not to use Type 2 and Type 3 holidays, or holidays that apply to specific regions when comparing to tblSales.[Date].
Any ideas?
A:
This is really what you mean.
SELECT Year(Date) AS Year, Month(Date) AS Month, Avg(tblSales.Sales) AS AvgSales
FROM tblSales
LEFT JOIN tblHolidays
ON tblSales.[Date] >= tblHolidays.[Date From]
AND tblSales.[Date] <= tblHolidays.[Date To]
AND tblHolidays.[Type] = 1 AND tblHolidays.[Region] = "All"
WHERE tblHolidays.[Date From] Is Null
GROUP BY Year(Date), Month(Date);
The LEFT JOIN serves to bring in matches from tblHolidays where it matches tblSales on ALL the conditions in the ON clause. In this case, it's saying:
Find holidays that covered the sales date, that are of type 1 and affect "all" regions.
Because of the LEFT JOIN nature, it will preserve all rows from tblSales even if no matches were found from tblHolidays. Next, where the matches were found, we strike them off by using the filter tblHolidays.[Date From] Is Null. Because tblHolidays.[Date From] is not null where the holiday condition was found.
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditional SELECT in Lambda expression LINQ
I'd appreciate if someone could advise on the following:
I need to select different values (in my case Adapters) based on different conditions, I tried like this:
return this.WrappedEntity.human_screen.SelectMany(e => e).Select(e =>
{
AHuman human = _unitOfWork.HumansRepo.GetById(e.human_uid.ToString());
if (e.vid_screen == "1" && human.Gender== Gender.Female)
{
return new SqlFemaleScreening(e);
}
else if (e.vid_screen == "1" && human.Gender== Gender.Male)
{
return new SqlMaleScreening(e);
}
else
{
return new SqlChildScreening(e);
}
});
But I get the following error:
ERROR: Type arguments for method "System.Linq.Enumerable.SelectMany
<TSource,TResult> (System.Collections.Generic.IEnumerable <TSource>,
System.Func <TSource, int, System.Collections.Generic.IEnumerable
<TResult>>) "should be defined for use. Try to clearly define the
type arguments.
Thanks a lot in advance!
A:
The problem is that because you are returning multiple different types of objects the compilers isn't sure what objet type you are expecting in your returned enumerable. Usually when you use something like Select or SelectMany the compiler can work it out so you don't need to worry about it. In this case you need to worry about telling it what they should be.
Your code will be changed to look like:
return this.WrappedEntity.human_screen.SelectMany(e => e).Select<TSource, TResult>(e =>
{
//Same code as before in here
});
TSource should be the type of e in your select method. TResult should be the base type of SqlFemaleScreening, SqlMaleScreening, SqlChildScreening.
| {
"pile_set_name": "StackExchange"
} |
Q:
Probability density calculation question
Here is a part of probability density prove,
I can't understand why the second term of the last sequence was changed from psi* del^2 psi to psi del^2 psi*.
http://bado-shanai.net/Map%20of%20Physics/mopProbDensity.htm
A:
Let us go through this
\begin{align}
\frac{d}{dt}\left(\Psi^*\Psi\right) &= \left(\frac{-i\hbar}{2m}\nabla^2\Psi^* - \frac{U}{i\hbar}\Psi^*\right)\Psi + \Psi^*\left(\frac{i\hbar}{2m}\nabla^2\Psi + \frac{U}{i\hbar}\right).
\end{align}
The terms involving the potential energy cancel leaving:
\begin{align}
\frac{d}{dt}\left(\Psi^*\Psi\right) = \left(\frac{-i\hbar}{2m}\nabla^2\Psi^*\right)\Psi + \Psi^*\left(\frac{i\hbar}{2m}\nabla^2\Psi\right).
\end{align}
Each expression within paranthesis is not an operator: it is an operator acting on a state, producing a new state. The states are represented by functions, and multiplication of functions commute. Therefore we can write it as
\begin{align}
\frac{d}{dt}\left(\Psi^*\Psi\right) &= \Psi\left(\frac{-i\hbar}{2m}\nabla^2\Psi^*\right) + \Psi^*\left(\frac{i\hbar}{2m}\nabla^2\Psi\right) \\
&=\frac{i\hbar}{2m}\left(\Psi\nabla^2\Psi^* + \Psi^*\nabla^2\Psi\right) \\
&= \frac{i\hbar}{2m}\left(\Psi^*\nabla^2\Psi + \Psi\nabla^2\Psi^*\right).
\end{align}
| {
"pile_set_name": "StackExchange"
} |
Q:
Дублирование элементов массива
Создать функцию, которая принимает массив, а возвращает новый, с дублированными элементами, входного массива. У меня такой код, но в нём ошибка, как правильнее
function map(Array) {
let napp = [];
for (let i = 0; i<Array.length; i++){
}
return napp;
}
let doubleArray = Array.concat([1, 2, 3]);
console.log(doubleArray);
?
A:
function dblArr(a){
return a.concat(a);
}
var a = [1,2,3];
console.log( dblArr(a) );
| {
"pile_set_name": "StackExchange"
} |
Q:
var_dump returns null, can't figure out why
<?php
$json_string = file_get_contents('infile.json');
fwrite($fileout, $json_string);
var_dump(json_decode($json_string));
$get_json_values=json_decode($json_string,true);
if(is_array($get_json_values))
{
foreach ($get_json_values as $getlikes) { ?>
<li>
<a href="https://www.facebook.com/<?php echo $getlikes['id']; ?>" target="_top">
</li>
<?php
} }
?>
I am trying to get values from a json file and I just can't figure out why var_dump returns NULL. Also, if I remove the if, for obvious reasons, there is a
Warning: Invalid argument supplied for foreach()
Please help me with this, i've been working on this the whole day and it's just so frustrating that it doesn't work out in any way.
Note: The name of the file is correct, the file is in the same directory with the .php file, there is data in infile.json and it is printed when fwrite($fileout, $json_string); is done.
What would be the problem, and what should I do?
Edit: The json file has about 1000 entries containing facebook page data. They all have the following structure:
{"category":"Musician\/band","name":"Yann Tiersen (official)","id":"18359161762","created_time":"2013-03-09T23:00:54+0000"}
var_dump($json_string) prints the data from the file.
if this helps in any way, the json file can be downloaded here
I have made up my json like this:
function idx(array $array, $key, $default = null) {
return array_key_exists($key, $array) ? $array[$key] : $default;
}
$likes = idx($facebook->api('/me/likes'), 'data', array());
foreach ($likes as $like) {
fwrite($fileout,json_encode($like));
fwrite($fileout,PHP_EOL );
?>`
So, what should I change would be:
1) add fwrite($fileout, "["); before and fwrite($fileout,"]"); after foreach.
2) add fwrite($fileout,",") before fwrite($fileout,PHP_EOL );
Is this right?
A:
Your JSON file IS invalid.
Basically you have plenty of lines that are all valid JSON in itself, but they are not valid combined!
Invalid:
{"category":"Musician\/band","name":"Yann Tiersen (official)","id":"18359161762","created_time":"2013-03-09T23:00:54+0000"}
{"category":"Travel\/leisure","name":"Me hitchhiking around the world","id":"221159531328223","created_time":"2013-03-09T13:24:06+0000"}
Would be valid:
[
{"category":"Musician\/band","name":"Yann Tiersen (official)","id":"18359161762","created_time":"2013-03-09T23:00:54+0000"}
,
{"category":"Travel\/leisure","name":"Me hitchhiking around the world","id":"221159531328223","created_time":"2013-03-09T13:24:06+0000"}
]
You can either decode the JSON line by line, or convert it into a valid format.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can Turing Machines solve non-decision problems?
Since TMs are equivalent to algorithms, they must be able to perform algoriths like, say, mergesort. But the formal definition allows only for decision problems, i.e, acceptance of languages. So how can we cast the performance of mergesort as a decision problem?
A:
Usually, Turing machines are explained to calculate functions $f:A \rightarrow B$, of which decision problems are a special case where $B = \mathbb{B}$.
A:
You can define two kinds of Turing Machines, transducers and acceptors.
Acceptors have two final states (accept and reject) while transducers have only one final state and are used to calculate functions.
Let $\Sigma$ be the alphabet of the Turing Machine.
Transducers take an input $x \in \Sigma^*$ on an input tape and compute a function $f(x) \in \Sigma^*$ that is written on another tape (called output tape) when (and if) the machine halts.
The are various results that link together acceptors and transducers. For example:
Let $\Sigma=\{0, 1\}$. Given a language $L \subseteq \Sigma^*$ you can always define $f : L \to \{0,1\}$ to be the charateristic function of $L$ i.e.
$$
f(x) = \begin{cases}
1 & \mbox{if $x \in L$} \\
0 & \mbox{if $x \not\in L$}
\end{cases}
$$
In this case an acceptor machine for $L$ is essentially the same as a transducer machine for $f$ and vice versa.
For more details you can see Introduction to the Theory of Complexity by Crescenzi (download link at the bottom of the page). It is lincensed under Creative Commons.
A:
We focus on studying the decision problems in undergrad complexity theory courses because they are simpler and also questions about many other kinds of computations problems can be reduced to questions about decision problems.
However there is nothing in the definition of Turing machine by itself that restricts it to dealing with decision problems. Take for example the number function computation problems: we want to compute some function $f:\{0,1\}^*\to\{0,1\}^*$. We say that a Turing machine compute this function if on every input $x$, the machine halts and what is left over the tape is equal to $f(x)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Calendar week base php
I want to make a calendar based on weeks with php found this script. If i get week 18 the first day is in april. How can i make it wright &bnsp for the first day?
If you look at Juni there is 4 blank days in the begining of the week then i need php to print 4 &bsp (blank day) hope you can help.
$week_number = 18;
$year = 2018;
if($week_number < 10){
$week_number = "0".$week_number;
}
for($day=1; $day<=7; $day++)
{
echo date('d', strtotime($year."W".$week_number.$day))."\n";
}
A:
This will do what you want.
I save the days in an array instead and then find the key of the lowest number (that's the start of next month).
Then I loop the array and if the key is less than the start position I echo new line, else the value.
for($day=1; $day<=7; $day++){
$days[$day] = date('d', strtotime($year."W".$week_number.$day))."\n";
}
$start = array_keys($days, min($days))[0];
for($day=1; $day<=7; $day++){
If($day<$start){
Echo "\n";
}Else{
Echo $days[$day];
}
}
https://3v4l.org/dIhYZ
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there specific tropes/details/etc... that characterized Golden Age of Science Fiction?
Wiki article on the Golden Age of Science Fiction mentions a couple of major developments associated with it, but is pretty thin on comprehensive analysis:
Space opera came to prominence
Three Laws of Robotics
Celebration of scientific achievement and the sense of wonder (though, frankly, this seems to be dated back to Jules Verne? - DVK)
Libertarian ideology
Re-emergence of the religious or spiritual themes in opposition to Hugo Gernsback's "scientifiction".
Is there a good analysis or summary of all the major tropes, developments etc... which characterized Golden Age of Science Fiction?
I'd prefer a pointer to existing analysis (with a brief summary if it's extended) - could be published or online.
A:
I just leafed through a few books ("Cambridge Companion to Science Fiction", David Seeds likewise named "Companion to Science Fiction", Adam Roberts "Science Fiction" and even Suvins "Positions and Suppositions"). They all mention an "Golden Age" of Science Fiction, but do no use the term in any analytical fashion.
Suvin puts the "Golden Age" in the range from 1938-1958, so the inclusion of the fifties is not entirely new (referring to Wayfarers comment - the Suvin book is from the 70s). However Roberts says that "Fans talk unironically about "the "Golden Age" and [...] mean something quite specific: The late 1930s and early 1940s [...]".
I think that quote is also a clue to your question - professional literature critics prefer to categorize thematically or by the mode of publishing (e.g. "the magazine years") or, if they talk about time periods, they tie their categories to a relevant (to the genre) social movement (e.g. "postmodernism").
So my educated guess would be that there is no "professional" assement of Golden Age tropes (and you should look into fandom, which is not really my area of expertise).
| {
"pile_set_name": "StackExchange"
} |
Q:
Reverse Linked-List Recursive
I've traced through my code to reverse a linked-list using recursion, and I cannot find anything wrong with it, but I know it does not work. Can anyone please explain why?
Node reverseLL (Node head) {
if(curr.next == null) {
head = curr;
return head;
}
Node curr = head.next;
prev = head;
head.next = prev;
head = next;
reverseLL(head.next);
}
A:
Below is a working version of your code, added with some helping structures:
class LList {
Node head;
void reverse() {
head = rev(head, head.next);
}
private Node rev(Node node, Node next) {
if(next == null) return node; //return the node as head, if it hasn't got a next pointer.
if(node == this.head) node.next = null; //set the pointer of current head to null.
Node temp = next.next;
next.next = node; //reverse the pointer of node and next.
return rev(next, temp); //reverse pointer of next node and its next.
}
}
class Node {
int val;
Node next;
public Node(int val, Node next) {
this.val = val;
this.next = next;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
how to change soup file to 'dict' save?
I've two tables with same att:class, and there's no other att for tr or td.
<table class='content'>
<caption>
<em> table1 </em>
</caption>
<tbody>
<tr>
<th> A </th>
<th> B </th>
<th> C </th>
</tr>
<tr>
<td> a1 <td>
<td> b1 <td>
<td> c1 <td>
</tr>
<tr>
<td> a2 <td>
<td> b2 <td>
<td> c2 <td>
</tr>
</tbody>
</table>
<table class='content'>
<caption>
<em> table2 </em>
</caption>
<tbody>
<tr>
<th> A </th>
<th> B </th>
<th> C </th>
</tr>
<tr>
<td> a3 <td>
<td> b3 <td>
<td> c3 <td>
</tr>
<tr>
<td> a4 <td>
<td> b4 <td>
<td> c4 <td>
</tr>
</tbody>
</table>
Then I want a dict like
{table1:[ {A:[a1,a2]}, {B:[b1,b2]}, {C:[c1,c2]} ], table2:[ {A:[a3,a4]}, {B:[b3,b4]}, {C:[c3,c4]} ], }
Can anybody help me in getting this dict, or a similar one?
A:
Try this (also note that you have <td>...<td> instead of <td>...</td>):
import bs4
your_html = """..."""
soup = bs4.BeautifulSoup(your_html)
big_dict = {}
for table in soup.find_all("table"):
key = table.find("em").get_text().strip()
big_dict[key] = []
headers = []
for th in table.find_all("th"):
headers.append(th.get_text().strip())
big_dict[key].append({headers[-1]: []})
for row in table.find_all("tr"):
for i, cell in enumerate(row.find_all("td")):
big_dict[key][i][headers[i]].append(cell.get_text().strip())
print(big_dict)
Above yielded me:
{'table1': [{'A': ['a1', 'a2']}, {'B': ['b1', 'b2']}, {'C': ['c1', 'c2']}], 'table2': [{'A': ['a3', 'a4']}, {'B': ['b3', 'b4']}, {'C': ['c3', 'c4']}]}
| {
"pile_set_name": "StackExchange"
} |
Q:
Online requesting for response in Android
I am developing a kind of trading android app. In the application, a user can send a request to another user through online in real time and the other user can either accept or decline it. The concept is like calling someone that if you call a person, the application will prompt him if he wants to accept or decline it. How can I implement this kind of function in my application?
A:
a user can send a request to another user through online in real time
and the other user can either accept or decline it. ... How can I
implement this kind of function in my application?
With Google massaging system ( push notification) you can ask your server to ask google server to send a notification to the user. He will receive, when he has data connections and server and stars are aligned...
Then the other user can accept / reject, which will send a HTTP request to your server and that will notify you via presented messaging system.
The second version is to write an app, which send an SMS with an application code content, this doesn't need Internet connection, but may involve some additional costs for communication. Anyway this is the fastest safest method, in my opinion.
How to send SMS: https://www.tutorialspoint.com/android/android_sending_sms.htm
Android listen the incoming SMS:
http://androidexample.com/Incomming_SMS_Broadcast_Receiver_-_Android_Example/index.php?view=article_discription&aid=62
| {
"pile_set_name": "StackExchange"
} |
Q:
Apache error [notice] Parent: child process exited with status 3221225477 -- Restarting
I'm using PHP5, CodeIgniter and Apache. The localhost php pages were loading fine and then suddenly they started crashing Apache.
The web pages seem to get to different stages of loading when apache crashes.
The only interesting line in the Apache error log file says :
[notice] Parent: child process exited with status 3221225477 -- Restarting.
There is a lot of discussion of this issue on the web but it seems there is no one solution, different people have described different solutions that worked for their system.
Suggestions Appreciated.
A:
This problem often happens in Windows because of smaller Apache’s default stack size. And it usually happens when working with php code that allocates a lot of stacks.
To solve this issue, add the following at the end of apache config file, httpd.conf
<IfModule mpm_winnt_module>
ThreadStackSize 8888888
</IfModule>
AND restart apache.
i take this solution from this site.
A:
I found a solution that worked for me.
I copied the following two files from my PHP directory to the Win32 directory and the errors stopped : php5apache.dll, libmysql.dll.
So even though these files should have been found in the PHP directory under certain circumstances they needed to be in the system dir
A:
In my case it was the php extension APC (php_apc.dll, 3.1.10-5.4-vc9-x86, threadsafe), which caused the error.
I used XAMPP 1.8.2 with PHP 5.4.19 and Apache 2.4.4
Since it could be caused by another extension as well, it might be a good starting point to restore the original php.ini from the xampp distribution. If this one works well, try to change it line by line to your desired configuration (starting with the extension list).
| {
"pile_set_name": "StackExchange"
} |
Q:
Splitting fields over $\mathbb{Q}$
Find a splitting fields over $\mathbb{Q}$ for:
i)$x^4+4=(x^2-2x+2)(x^2+2x+2)$ (both factors are irreducible). The roots: $x_1=1+i,\ x_2=-(1+i)$. So the splitting field is $\mathbb{Q}(i)$, which has deg 2 over Q.
ii)$x^6-8=(x^2-2)(x^4+2x^2+2)$. The roots: $x_1=1, \ x_2=-1$. 4 left so it will be $e^{\frac{2 \pi i}{6}}$. So the splitting field is $\mathbb{Q}(e^{\frac{2\pi i}{6}})$ And deg is also 2?
iii)$x^4+5x^2+6=(x-i)(x+i)(x-i\sqrt5)(x+i\sqrt5)$. So the splitting field will be $\mathbb{Q}(\sqrt5,i)$ and deg 4?
Is that correct?
A:
For i) The roots are the powers of $\sqrt{2}e^{\frac{i \pi}{4}}$ and a splitting field is $\mathbb Q(\sqrt{2}e^{\frac{i \pi}{4}})$.
For ii) The roots are the powers of $\sqrt{2}e^{\frac{i \pi}{3}}$ and a splitting field is $\mathbb Q(\sqrt{2}e^{\frac{i \pi}{3}})$.
For iii)
$$x^4+5x^2+6=(x^2+2)(x^2+3)=(x-i\sqrt{2})(x+i\sqrt{2})(x-i\sqrt{3})(x+i\sqrt{3})$$ and a splitting field is $\mathbb Q(i\sqrt{2},i\sqrt{3})$
| {
"pile_set_name": "StackExchange"
} |
Q:
HashMap initialization
If I write
HashMap<String, String> map = new HashMap();
as opposed to
HashMap<String, String> map = new HashMap<>();
or as opposed to
HashMap<String, String> map = new HashMap<String, String>();
will the 1st one be unsafe in any way?
A:
The second is just an abbreviation of the third alternative.
The first way can cause problems if you use a different constructor, because it ignores generics.
For instance, the following compiles:
Map<Integer, Integer> intMap = ...;
Map<String, String> strMap = new HashMap(intMap);
It will even execute without errors because there are no generic checks at runtime. But if intMap contained data and you access it from strMap (eg., by iterating over keys), you will get a runtime exception.
Such a bug would be very hard to track because the exception might occur far away from the offending line.
So, in your particular case it wouldn't cause problems, but if you make this a habit you will run into problems eventually. Furthermore, you will get compiler warnings which you would have to suppress or ignore, both things that should be avoided.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dojo hide button label inside TableContainer
Have a dojox.layout.TableContainer containing some text fields and buttons. However the labels of the buttons are displayed before the button and on the button. Below is a subset of the code some slight changes:
var tableContainer = new dojox.layout.TableContainer(
{
cols: 1
});
var txtBox = new dijit.form.TextBox({
id: "txtBox1",
name: "txtBox1",
label: "First TextBox:"
},"ftxtb");
var addBtn = new dijit.form.Button({
label: "Add Button"
});
tableContainer.addChild(txtBox);
tableContainer.addChild(addBtn);
Now labels for TextBoxes are OK but I don't want the button label to be displayed except on the button. To clarify button will be shown as:
Add Button <Add Button>
How can I hide the label outside the button?
A:
If you wrap the button widget inside a ContentPane and then place the ContentPane inside TableContainer the problem goes away. I ran into exact same problem and I was also building everything programmatically inside a Dialog widget.
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditional CDF from joint CDF using partial derivatives
Is there a way of finding the conditional CDF $F(x\mid y)$ by using the partial derivative $\dfrac{dF(x,y)}{dy}$ ?
A:
$$F(x|y)=\int_{-\infty}^x \dfrac{f(z,y)}{f(y)}dz=\dfrac{\dfrac{dF(x,y)}{dy}}{f(y)}$$
Since $$ \dfrac{dF(x,y)}{dy}=\dfrac{d}{dy}\int_{-\infty}^y \int_{-\infty}^x f(z,w) dz dw=\int_{-\infty}^x f(z,y) dz$$
| {
"pile_set_name": "StackExchange"
} |
Q:
How can JavaScript arrays have non-numeric keys?
What I have learned is an array is a type of object. Objects are a collection of properties with key/value pairs. I always thought arrays are a collection of items that are numerically indexed starting at 0. Just recently, I was able to add a non-numeric key to an array.
let arr = ['cribriform plate','mastoid','hyoid'];
arr.eyes = 'brown';
arr.skin = 'white';
That resulted in
['cribriform plate','mastoid','hyoid',eyes : 'brown', skin : 'white'];
The for...in loop of arr yielded:
for(let i in arr){
console.log(i);
//0,1,2,3,eyes,skin
}
The for...of loop yielded:
for(let i of arr){
console.log(i);
//0,1,2,3
}
I was able to iterate over all the keys of an array using the for...in loop. However, when I used the for...of loop, I was only able to iterate over the numerically indexed keys. Why is that?
And, what is the most accurate definition of an array?
A:
With a for..of loop, the object's Symbol.iterator property is called. In the case of an array, this is equivalent to the array's .values() method, which contains the values for each index in the array. Non-numeric properties are not included - arrays generally don't have arbitrary non-numeric properties, and code that does assign arbitrary non-numeric properties to an array is likely in need of refactoring.
A for..in loop iterates over all enumerable properties on an object, including those inherited from the prototype. Thus, for..of on an array will exclude non-numeric properties on an array that a for..in loop will include.
Arrays, being objects, can have arbitrary properties assigned to them, for the most part, just like properties can be assigned to ordinary functions - it's just not a very good idea.
| {
"pile_set_name": "StackExchange"
} |
Q:
React Native - console.error: 'React Native version mismatch
I am using EXPO and React Native, the app work running completely fine until it suddenly stopped when I made a new file and even when I deleted it, the error stayed.
I have updated React Native to V0.56.0 but it is still showing the error:
console.error: 'React Native version mismatch.
Javascript version: 0.56.0
Native Version: 0.52.0
Before I updated it was:
Javascript version: 0.54.0
Native Version: 0.52.0
and still causing the same error?
Any ideas on how I fix this and which command I use to update the Native Version?
A:
Go to package.json file inside your project folder
Where you can find code like this
"dependencies": {
.....
"react-native": "^0.54.0",
......
},
change the react-native version to 0.54 and save file.
Then go to the terminal and redirect to your project folder and hit the command
npm install && expo start -c
A:
This Answer is Published in 2020,
Fix this Error in 3 steps:
First step: I changed the value of expo in package.json file to the latest supported version, according to expo documents(visit here).
Second step: I changed the value of sdkVersion in app.json file to the same value of expo in package.json.( equal number to last step).
Third step : I changed the value of react-native in package.json file to the same value of React Native Version , according to expo documents(visit here).
now your ready to go.
use npm install to install specified version of dependencies and then npm start to run the project
| {
"pile_set_name": "StackExchange"
} |
Q:
Determine if text returned in MYSQL query is the default text
Is there a way to easily determine if the text being returned by a query is the default text put in place when the database was created?
For example, the db I'm working with has several text fields that, when the db was set up, are pre-populated with greek ('lorem ipsum...'). But, each field is a little different in the amount of greek and what greek is used in the default. Without knowing the precise greek that is used in each field as the default, is there a way to have the query 'tell' me that it's the default text?
A:
You can use <cfdbinfo /> to get this information. You would use it as follows:
<cfdbinfo type="columns" name="qResult" table="tableName" datasource="dsnName" />
<cfdump var="#qResult#" />
In my tests, this returns a query with a "column_default_value" column that you can use to determine if the result is the default value or not.
You can find more info about cfdbinfo here
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I create custom exception in ColdFusion
Here is an example of my code:
<cftry>
<cfquery name="myquery" datasource="logindetails">
INSERT INTO userdetails
(FirstName,LastName,Email,Phonenumber,Country,Gender)
VALUES
('#Form.firstname#','#Form.lastname#','#Form.emailID#',
'#Form.PhoneNumber#','#Form.country#','#Form.gender#')
</cfquery>
<cfoutput>
<b>Your Form has been registered</b>
</cfoutput>
<cfcatch type="database">
<cfoutput>Email already exists. Try with a different email address</cfoutput>
</cfcatch>
<cfcatch type="any">
<cfoutput>Sorry! some error occured.</cfoutput>
</cfcatch>
</cftry>
I have two different database exceptions and I want to display different messages for these two exceptions form the database so I am asking how to create custom exceptions in ColdFusion?
A:
I think you are asking if it's possible to have custom messages for two different exceptions thrown by the cfquery (rather than custom exceptions which can be done with cfthrow)
if so any error coming from the cfquery will probably be of type database so you'll have to inspect the message in the cfcatch and alter the message depending on the content of the error message for example
<cftry>
<cfquery name="myquery" datasource="logindetails">
INSERT INTO userdetails
(FirstName,LastName,Email,Phonenumber,Country,Gender)
VALUES
('#Form.firstname#','#Form.lastname#','#Form.emailID#',
'#Form.PhoneNumber#','#Form.country#','#Form.gender#')
</cfquery>
<cfoutput>
<b>Your Form has been registered</b>
</cfoutput>
<cfcatch type="database">
<cfoutput>#findNoCase("error message 1", cfcatch.message) ? "Email already exists. Try with a different email address" : "Some other error message"#</cfoutput>
</cfcatch>
<cfcatch type="any">
<cfoutput>Sorry! some error occured.</cfoutput>
</cfcatch>
</cftry>
Possibly you will need to inspect multiple properties depending on the error returned from the db so here is a list of cfcatch properties
| {
"pile_set_name": "StackExchange"
} |
Q:
Paying to another user in Swift application
I have this problem. I'm making an iOS application in Swift that sells user images and videos. I've got my own server, so all media is saved there. But now I've come to a point where I need make possible that user can buy some content from another user using a credit card or PayPal account. Other users can be found on a map, they have added their payment information to their profile (it's not visible to others) so that transactions could be made.
I've done some research on this topic and I know that a powerful tool for payments in Swift is Stripe. However, as far as I read about it, users can only pay to one account that you register. Basically, they can make purchases as if buying from a store. But in my case, I need to provide the possibility to pay to another user.
Also, I need to integrate PayPal. For this I found API's like Auth0 and PayPal API, but can't seem to find any more information on inter-user transactions.
And there is In-App Purchases option, of course, but I'm not sure if I can use that in this case, because most of my purchases will be done from a Web App.
Can somebody please help me, by giving some tips on how to move forward from here and implement this payment system?
A:
There are several considerations to take into account, the three most important being price, ease of implementation and availability. I'll briefly discuss each point of the 3 options you mentioned:
Stripe:
Implementation: Stripe has a native SDK for iOS and has a functionality called Stripe Connect which enables payment between users directly, without having the money to go through your account, yet allows you to take a cut of the transaction if you'd like:
https://support.stripe.com/questions/can-i-enable-my-users-to-receive-payments-from-others
https://stripe.com/docs/connect
Price: Stripe has a starting fee of 0.3$ and takes 2.9 % of the full amount.
Availability: Currently Stripe is only available in 9 countries worldwide and available as a beta in another 15 countries:
https://stripe.com/global
PayPal:
Implementation: PayPal has a native SDK for iOS, but a very fractioned history of SDK libraries depending on how complex functionality you need (Which Pryo's answer underlined). Paypal has something called Adaptive Payments which allows for peer-to-peer payments:
https://developer.paypal.com/docs/classic/products/adaptive-payments/
Price: PayPal has a lot of mixed information about pricing (currency conversion, cross border transfer, etc.), but roughly it is a starting fee of 0.3$ and another 3.9 %.
Availability: PayPal is available in 203 countries/markets around the world:
https://www.paypal.com/webapps/mpp/country-worldwide
In-App Purchase:
Implementation: This money will always go directly to the developer, so this means you will need to implement some sort of service which takes money from your account to the final user. So the flow goes: buyer -> you -> receiver.
Price: Apple will take 30 % of the total amount.
Availability: In-App Purchase is available in every country where you would be able to distribute the iOS app.
Conclusion:
Don't use the In-App Purchase option for user-to-user sales, it's simply too complex and expensive out of the three options.
PayPal has a strong brand that people trust and is available in many countries, which makes it a stronger candidate than Stripe, but IMHO I would choose Stripe due to its simplicity and cheaper pricing.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multi-core CPU utilization by Java application
I have a program that sorts big files by splitting them into chunks, sort chunks and merge them into final sorted file. Application runs one thread for loading/saving data from/to file - only one thread does I/O operations. Also there are two more threads that receive chunk data, sort it and then send sorted data back to thread that does I/O.
So in general there are 4 threads running - main thread, thread that loads/saves data and two threads that sort data.
I thought during execution i will see 1 sleeping thread (main) that doesn't take any CPU time and 3 active threads that utilize 1 CPU core each.
When i run this program on dual 6 core processor machine with hyper threading (24 CPUs) i see that ALL 24 CPU's are loaded for 100%!
Initially i thought that sort algorithm is mutithreaded, but after looking into java sources i found that it's not.
I'm using simple Collections.sort(LinkedList) to sort the data...
here are some details:
# java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02, mixed mode)
# uname -a
Linux 2.6.32-28-server #55-Ubuntu SMP Mon Jan 10 23:57:16 UTC 2011 x86_64 GNU/Linux
I was using nmon to monitor processor loading.
I would appreciate any explanation of this case and any advise on how to control CPU loading as i this particular task doesn't leave CPU time for other applications
[UPDATE]
I used jvisualvm to count threads - it shows only threads i know about. Also i made a simple test program (see below) that runs only one main thread and got exactly the same results - all 24 processors are busy almost for 100% during code execution
public class Test {
public void run(){
Random r = new Random();
int len = r.nextInt(10) + 5000000;
LinkedList<String> list = new LinkedList<String>();
for (int i=0; i<len; i++){
list.add(new String("test" + r.nextInt(50000000)));
}
System.out.println("Inserted " + list.size() + " items");
list.clear();
}
public static void main(String[] argv){
Test t = new Test();
t.run();
System.out.println("Done");
}
}
[UPDATE]
Here is the screenshot i made while running the program above (used nmon):
http://imageshack.us/photo/my-images/716/cpuload.png/
A:
I would suggest, that this is rather a nmon than a java question and to solve it, I would take a peek at the top command which provides info about cpu-usage per process. I predict the following result: You will see one java thread using near 100% cpu-time (which is ok, as per-process percentage in top is relative to one (virtual) core), maybe a second and third java thread with much less cpu-usage (the I/O threads). Depending on the choice of the gc you might even spot one or more gc-Threads, however much less than 20.
HotSpot however will not (and even cannot to my knowledge) parallelize a sequential task on its own.
| {
"pile_set_name": "StackExchange"
} |
Q:
Uncaught ReferenceError: $ is not defined at http://localhost/project/public/user/1/edit:308:9 in Laravel
Jquery
<script src="http://localhost/project/public/plugins/jQuery/jquery-2.2.3.min.js"></script>
my code
<script type="text/javascript">
function readURL(input){
if(input.files && input.files[0]){
var reader = new FileReader();
reader.onload=function(e){
$('#showimages').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#inputimages").change(function(){
readURL(this);
});
</script>
<img src="" id="showimages">
<input type="file" name="images" id="inputimages">
and i got this error
Uncaught ReferenceError: $ is not defined
at http://localhost/project/public/user/1/edit:308:9
*line 308 -> $("#inputimages").change(function(){
Im new in js and jquery, Help me solve this error please...
I wrote the script out of the section. That was why the error occurred, see my answer.
A:
Thankyou for everyone!
This error is solved, in .blade.php laravel i have to write
@section('script')
<script type="text/javascript">
//my code here
</script>
@endsection
| {
"pile_set_name": "StackExchange"
} |
Q:
ESP8266 serial-wifi: antenna options
The cheap ESP8266 boards are offered on ebay with two built-in antenna options:
with a PCB trace antenna
with a ceramic(?) antenna
(PCB photographs see below.)
Has somebody bought both and compared their signal quality?
Or can somebody from looking a the desing hazard a guess how signal qualities will compare?
A:
I've been playing with ESP01 and ESP03 and the ceramic antenna beats the PCB antenna by far.
While doing throughput tests I could not get the ESP01 to reliably get more than 1mbps until I touched the antenna with my hand (getting 10mbps). With the same program on the ESP03 the rate was always 10mbps.
Also with ESP01 I get 20-90ms of RTT in my home WLAN and with ESP03 I get a steady 2-3ms.
| {
"pile_set_name": "StackExchange"
} |
Q:
Update app widget layout dynamically
I'm working on a voip/sip based application which is capable of making calls from a dialpad widget which has the four buttons at the bottom
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageButton
android:id="@+id/ibtn_handsfree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/selector_dialpad_action_button"
android:src="@drawable/selector_handsfree" />
<ImageButton
android:id="@+id/ibtn_headset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/selector_dialpad_action_button"
android:src="@drawable/selector_headset" />
<ImageButton
android:id="@+id/ibtn_copyToDir"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/selector_dialpad_action_button"
android:src="@drawable/selector_copytodir" />
<ImageButton
android:id="@+id/ibtn_keyboard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/selector_dialpad_action_button"
android:src="@drawable/selector_keyboard" />
<ImageButton
android:id="@+id/ibtn_sendkey_widget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/selector_dialpad_action_button"
android:src="@drawable/selector_send_key_dialer"
/>
</LinearLayout>
Is it discouraged that I toggle the visibility of any of my layout
elements dynamically ? For example if I wish to hide the fourth
button, depending on any active call present(which I believe would
require an individual and dedicated listener attached).
If the dynamic changes on the widget layout aren't discouraged, how
do I go about doing that ?
Appreciate your thoughts and help.
A:
I don't know the answer for the first question, but in order to toggle visibility of a button in a widget:
Add setOnClickPendingIntent for the button
Listen for that intent in your AppWidgetProvider's onReceive
Toggle visibility of the element and updateAppWidget
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there any tools for feature engineering?
Specifically what I am looking for are tools with some functionality, which is specific to feature engineering. I would like to be able to easily smooth, visualize, fill gaps, etc. Something similar to MS Excel, but that has R as the underlying language instead of VB.
A:
Very interesting question (+1). While I am not aware of any software tools that currently offer comprehensive functionality for feature engineering, there is definitely a wide range of options in that regard. Currently, as far as I know, feature engineering is still largely a laborious and manual process (i.e., see this blog post). Speaking about the feature engineering subject domain, this excellent article by Jason Brownlee provides a rather comprehensive overview of the topic.
Ben Lorica, Chief Data Scientist and Director of Content Strategy for Data at O'Reilly Media Inc., has written a very nice article, describing the state-of-art (as of June 2014) approaches, methods, tools and startups in the area of automating (or, as he put it, streamlining) feature engineering.
I took a brief look at some startups that Ben has referenced and a product by Skytree indeed looks quite impressive, especially in regard to the subject of this question. Having said that, some of their claims sound really suspicious to me (i.e., "Skytree speeds up machine learning methods by up to 150x compared to open source options"). Continuing talking about commercial data science and machine learning offerings, I have to mention solutions by Microsoft, in particular their Azure Machine Learning Studio. This Web-based product is quite powerful and elegant and offers some feature engineering functionality (FEF). For an example of some simple FEF, see this nice video.
Returning to the question, I think that the simplest approach one can apply for automating feature engineering is to use corresponding IDEs. Since you (me, too) are interested in R language as a data science backend, I would suggest to check, in addition to RStudio, another similar open source IDE, called RKWard. One of the advantages of RKWard vs RStudio is that it supports writing plugins for the IDE, thus, enabling data scientists to automate feature engineering and streamline their R-based data analysis.
Finally, on the other side of the spectrum of feature engineering solutions we can find some research projects. The two most notable seem to be Stanford University's Columbus project, described in detail in the corresponding research paper, and Brainwash, described in this paper.
A:
Featuretools is a recently released python library for automated feature engineering. It's based on an algorithm called Deep Feature Synthesis originally developed in 2015 MIT and tested on public data science competitions on Kaggle.
Here is how it fits into the common data science process.
The aim of the library is to not only help experts build better machine learning models faster, but to make the data science process less intimidating to people trying to learn. If you have event driven or relational data, I highly recommend you check it it out!
Disclaimer: I am one of the developers on the project.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I get the Bluetooth working on my Lenovo Yoga 3?
I have a Lenovo Yoga 3 that apparently has a new Broadcom Bluetooth device.
The bluetooth is detected at boot and when I try to pair a something in gnome, I can see a list of devices but none of them pair.
How can I get this device to work?
lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 004: ID 048d:8386 Integrated Technology Express, Inc.
Bus 001 Device 003: ID 5986:0535 Acer, Inc
Bus 001 Device 002: ID 0489:e07a Foxconn / Hon Hai
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
usb-devices
T: Bus=01 Lev=01 Prnt=01 Port=03 Cnt=02 Dev#= 2 Spd=12 MxCh= 0
D: Ver= 2.00 Cls=ff(vend.) Sub=01 Prot=01 MxPS=64 #Cfgs= 1
P: Vendor=0489 ProdID=e07a Rev=01.12
S: Manufacturer=Broadcom Corp
S: Product=BCM20702A0
S: SerialNumber=38B1DBE337E4
C: #Ifs= 4 Cfg#= 1 Atr=e0 MxPwr=0mA
I: If#= 0 Alt= 0 #EPs= 3 Cls=ff(vend.) Sub=01 Prot=01 Driver=btusb
I: If#= 1 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=01 Prot=01 Driver=btusb
I: If#= 2 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=ff Prot=ff Driver=(none)
I: If#= 3 Alt= 0 #EPs= 0 Cls=fe(app. ) Sub=01 Prot=01 Driver=(none)
A:
As of version 3.19, this device is supported in the Linux kernel, but you need to manually provide the device's firmware to the kernel.
Finding the Firmware:
You can find the firmware in the device's Windows driver, which you can download from Lenovo (or your computer manufacturer's website). Many drivers can just be unzipped, but for this particular computer, the driver is an .exe file and must be extracted with wine.
wine 4ab802rf.exe
Follow the "installation" instructions. The wizard will extract the .exe file and on the last step will ask to install it. Uncheck "Install Broadcom Bluetooth Driver now":
The driver file has been extracted to ~/.wine/driver_c/drivers/Broadcom Bluetooth Driver/
Identifying the right file
In my case, there are 20 - 30 firmware files in the extracted package. Which one corresponds to your device is revealed in one of the driver's inf files. Find your device ID from the output of lsusb or if that's unclear, usb-devices. In this case, it's e07a. Then grep the inf files to find out which one talks about that device:
grep -c E07A -r --include \*.inf
Win32/LD/bcbtumsLD-win7x86.inf:0
Win32/bcmhidnossr.inf:0
Win32/btwl2cap.inf:0
Win32/btwavdt.inf:0
Win32/btwrchid.inf:0
Win32/bcbtums-win8x86-brcm.inf:17
Win32/btwaudio.inf:0
Win64/LD/bcbtumsLD-win7x64.inf:0
Win64/bcmhidnossr.inf:0
Win64/btwl2cap.inf:0
Win64/btwavdt.inf:0
Win64/btwrchid.inf:0
Win64/bcbtums-win8x64-brcm.inf:17
Win64/btwaudio.inf:0
Autorun.inf:0
So in this driver, you can look in either Win32/bcbtums-win8x86-brcm.inf or Win64/bcbtums-win8x64-brcm.inf. Look through the file and find the hex file that is mentioned near E07A:
;;;;;;;;;;;;;RAMUSBE07A;;;;;;;;;;;;;;;;;
[RAMUSBE07A.CopyList]
bcbtums.sys
btwampfl.sys
BCM20702A1_001.002.014.1443.1496.hex
So the fimware is in the same directory and named BCM20702A1_001.002.014.1443.1496.hex.
Converting and Placing the Firmware
Download and compile the hex2hcd tool.
git clone https://github.com/jessesung/hex2hcd.git
cd hex2hcd
make
Convert the firmware to hcd:
hex2hcd BCM20702A1_001.002.014.1443.1496.hex firmware.hcd
Rename and move the firmware to the system's firmware subdirectory:
su -c 'mv firmware.hcd /lib/firmware/brcm/BCM20702A0-0489-e07a.hcd'
The name of this file is critical. The two sets of four characters, in this case 0489-e07a, should match your device's Vendor ID and Product ID.
Loading the Firmware
The easiest way to load the firmware is to power off your computer and turn it on again. Note that the computer should be turned off; a simple reboot may not be sufficient to reload this firmware.
A:
Following drs' using a shortcut, I managed to get the file and got possitive results. My bluetooth devices wasn't able to detect nearby visible devices, but now is.
The shortut I used was that since my computer has no optical drive and has Windows preinstalled, it came with a partition full of drivers. I found a directory with heaps of bluetooth drivers but looking into the INF file that drs suggested, I found that the E07A device was linked to driver file BCM20702A1_001.002.014.1483.1651.hex
After that I compiled de hex2hcd program and converted the file to HCD. I had to preserve BCM20702A1 name part as opposed to replacing it for BCM2070A0, as per the dmesg "patch not found" message.
I have not been able to pair my device, but being able to scan is definitely a step forward.
If you need the HCD file, please message me and hopefully I'll send it to you soon. I'll also send it to linux bluetooth mailing list.
EDIT. Apparently 1651 in the Windows HEX driver filename refers to the build number. Through dmesg I can see the kernel states that 1651 is the build number.
| {
"pile_set_name": "StackExchange"
} |
Q:
Scala: idiomatic way to merge list of maps with the greatest value of each key?
I have a List of Map[Int, Int], that all have the same keys (from 1 to 20) and I'd like to merge their contents into a single Map[Int, Int].
I've read another post on stack overflow about merging maps that uses |+| from the scalaz library.
I've come up with the following solution, but it seems clunky to me.
val defaultMap = (2 to ceiling).map((_,0)).toMap
val factors: Map[Int, Int] = (2 to ceiling). map(primeFactors(_)).
foldRight(defaultMap)(mergeMaps(_, _))
def mergeMaps(xm: Map[Int, Int], ym: Map[Int, Int]): Map[Int,Int] = {
def iter(acc: Map[Int,Int], other: Map[Int,Int], i: Int): Map[Int,Int] = {
if (other.isEmpty) acc
else iter(acc - i + (i -> math.max(acc(i), other(i))), other - i, i + 1)
}
iter(xm, ym, 2)
}
def primeFactors(number: Int): Map[Int, Int] = {
def iter(factors: Map[Int,Int], rem: Int, i: Int): Map[Int,Int] = {
if (i > number) factors
else if (rem % i == 0) iter(factors - i + (i -> (factors(i)+1)), rem / i, i)
else iter(factors, rem, i + 1)
}
iter((2 to ceiling).map((_,0)).toMap, number, 2)
}
Explanation: val factors creates a list of maps that each represent the prime factors for the numbers from 2-20; then these 18 maps are folded into a single map containing the greatest value for each key.
UPDATE
Using the suggestion of @folone, I end up with the following code (a definite improvement over my original version, and I don't have to change the Maps to HashMaps):
import scalaz._
import Scalaz._
import Tags._
/**
* Smallest Multiple
*
* 2520 is the smallest number that can be divided by each of the numbers
* from 1 to 10 without any remainder. What is the smallest positive number
* that is evenly divisible by all of the numbers from 1 to 20?
*
* User: Alexandros Bantis
* Date: 1/29/13
* Time: 8:07 PM
*/
object Problem005 {
def findSmallestMultiple(ceiling: Int): Int = {
val factors = (2 to ceiling).map(primeFactors(_).mapValues(MaxVal)).reduce(_ |+| _)
(1 /: factors.map(m => intPow(m._1, m._2)))(_ * _)
}
private def primeFactors(number: Int): Map[Int, Int] = {
def iter(factors: Map[Int,Int], rem: Int, i: Int): Map[Int,Int] = {
if (i > number) factors.filter(_._2 > 0).mapValues(MaxVal)
else if (rem % i == 0) iter(factors - i + (i -> (factors(i)+1)), rem / i, i)
else iter(factors, rem, i + 1)
}
iter((2 to number).map((_,0)).toMap, number, 2)
}
private def intPow(x: Int, y: Int): Int = {
def iter(acc: Int, rem: Int): Int = {
if (rem == 0) acc
else iter(acc * x, rem -1)
}
if (y == 0) 1 else iter(1, y)
}
}
A:
This solution does not work for general Maps, but if you are using immutable.HashMaps you may consider the merged method:
def merged[B1 >: B](that: HashMap[A, B1])(mergef: ((A, B1), (A, B1)) ⇒ (A, B1)): HashMap[A, B1]
Creates a new map which is the merge of this and the argument hash
map.
Uses the specified collision resolution function if two keys are the
same. The collision resolution function will always take the first
argument from this hash map and the second from that.
The merged method is on average more performant than doing a traversal
and reconstructing a new immutable hash map from scratch, or ++.
Use case:
val m1 = immutable.HashMap[Int, Int](1 -> 2, 2 -> 3)
val m2 = immutable.HashMap[Int, Int](1 -> 3, 4 -> 5)
m1.merged(m2) {
case ((k1, v1), (k2, v2)) => ((k1, math.max(v1, v2)))
}
A:
As your tags suggest, you might be interested in a scalaz solution. Here goes:
> console
[info] Starting scala interpreter...
[info]
Welcome to Scala version 2.10.0 (OpenJDK 64-Bit Server VM, Java 1.7.0_15).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import scalaz._, Scalaz._, Tags._
import scalaz._
import Scalaz._
import Tags._
There exists a Semigroup instance for Ints under a maximum operation:
scala> Semigroup[Int @@ MaxVal]
res0: scalaz.Semigroup[scalaz.@@[Int,scalaz.Tags.MaxVal]] = scalaz.Semigroup$$anon$9@15a9a9c6
Let's just use it:
scala> val m1 = Map(1 -> 2, 2 -> 3) mapValues MaxVal
m1: scala.collection.immutable.Map[Int,scalaz.@@[Int,scalaz.Tags.MaxVal]] = Map(1 -> 2, 2 -> 3)
scala> val m2 = Map(1 -> 3, 4 -> 5) mapValues MaxVal
m2: scala.collection.immutable.Map[Int,scalaz.@@[Int,scalaz.Tags.MaxVal]] = Map(1 -> 3, 4 -> 5)
scala> m1 |+| m2
res1: scala.collection.immutable.Map[Int,scalaz.@@[Int,scalaz.Tags.MaxVal]] = Map(1 -> 3, 4 -> 5, 2 -> 3)
If you're interested in how this "tagging" (the @@ thing) works, here's a good explanation: http://etorreborre.blogspot.de/2011/11/practical-uses-for-unboxed-tagged-types.html
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I adjust the date time format for an output parameter in Oracle?
I have an output parameter in oracle called outTime of type DATE. The format for this is set as yyyy-mm-dd and I need to be able to include the time from a table when I select into it.
I keep getting an error : date format picture ends before converting entire input string.
here is the insert into statement.
SELECT TO_CHAR(Table_Time, 'YYYY-MM-DD HH24:MI:SS') into outTime
FROM Table_One;
the out parameter is declared as
outTime OUT DATE;
within a stored procedure in a package of other procedures.
I keep finding ways to set the format globally but I only need to set the format for this instance.
Thanks for any insight.
A:
A DATE does not have a format. A string representation of a date has a format but a DATE does not.
If Table_Time is a VARCHAR2 (a string representation of a date) in the format yyyy-mm-dd hh24:mi:ss, then you would want to use TO_DATE to convert the string into a DATE (I assume that there is a single row in table_one in this example, otherwise the SELECT ... INTO will raise a no_data_found or a too_many_rows exception.
SELECT TO_DATE(Table_Time, 'YYYY-MM-DD HH24:MI:SS')
into outTime
FROM Table_One;
If Table_Time is a DATE, you would simply assign it to outTime
SELECT Table_Time
into outTime
FROM Table_One;
When you want to display outTime, you'll need to convert the DATE to a string representation of a date (a VARCHAR2). At that point, you can use the TO_CHAR function.
| {
"pile_set_name": "StackExchange"
} |
Q:
Extraer puntos dentro de un polígono, Python 2.7
Buen día a todos;
Estoy intentando extraer valores de (x,y) de puntos que se encuentran dentro de un polígono.
DF2 =
Coord_X Coord_Y
773686.694500 9963113.176875
773695.107375 9963167.598125
773707.252750 9963146.229750
773694.324000 9963092.721625
773686.197375 9963082.305875
773687.040875 9963167.699125
773727.531625 9963101.132000
773659.458625 9963152.513625
773696.472625 9963155.930750
773639.421625 9963091.894250
773639.421625 9963080.668875
773746.696125 9963121.726250
773667.951000 9963060.118625
773688.386375 9963140.699875
773694.572625 9963133.687500
773695.140250 9963177.481500
773694.225000 9963067.096375
773686.595000 9963102.952500
773639.401375 9963111.634000
773648.363250 9963113.248875
773640.049375 9963131.062375
773640.697750 9963141.208375
773649.267000 9963122.730250
773694.508250 9963103.219125
773662.812625 9963144.331125
773640.265375 9963123.938500
773653.061250 9963168.799625
773740.705500 9963102.361000
773639.853875 9963103.983125
773663.669000 9963141.736250
773656.719750 9963105.392750
773721.230250 9963148.101000
773705.000000 9963176.000000
773754.354000 9963120.056625
773699.880250 9963085.736625
773686.694500 9963113.176875
773695.107375 9963167.598125
773727.531625 9963101.132000
773696.472625 9963155.930750
773688.386375 9963140.699875
773694.572625 9963133.687500
773694.225000 9963067.096375
773639.401375 9963111.634000
773640.697750 9963141.208375
773640.265375 9963123.938500
773740.705500 9963102.361000
773705.000000 9963176.000000
773727.531625 9963101.132000
773688.386375 9963140.699875
773694.572625 9963133.687500
773694.225000 9963067.096375
773639.401375 9963111.634000
773640.697750 9963141.208375
773640.265375 9963123.938500
773727.531625 9963101.132000
El código es:
from shapely.geometry import Polygon
poly = Polygon([[773642.25342880527, 9963094.3392374925],
[773662.7163213623, 9963189.5526211839],
[773773.26644345513, 9963191.592321692],
[773771.91631169291, 9963098.0998664293],
[773667.59566028137, 9963054.4342967868]])
x,y = poly.exterior.xy
plt.scatter(DF2["Coord_X"], DF2["Coord_Y"], marker='+',linewidth=1,c="r", s=90)
plt.plot(x, y, color='y', alpha=2, linewidth=2, solid_capstyle='round', zorder=2)
plt.show()
Si dibujamos el polígono y los puntos, se muestran a continuación.
Como podría extraer solo puntos que se encuentran dentro del polígono, tal vez alguien tiene alguna idea, muchas gracias por su ayuda.
A:
Estás usando shapely y esa biblioteca ya te da las herramientas necesarias para verificar si un punto dado está o no dentro de un polígono dado:
polygon.contains(Point(x,y))
Sólo hay que juntar esto con pandas para filtrar todas aquellas filas en las que esa condición sea cierta. En tu caso, veo que tienes todos los datos en un dataframe llamado DF2, por lo que podrías hacer:
dentro = DF2[DF2.apply(lambda row: poly.contains(Point(row.Coord_X, row.Coord_Y)),
axis=1)]
Básicamente, DF2.apply(lambda, axis=1) aplica la función lambda en cuestión a cada fila del dataframe, y devuelve una Serie con el resultado de cada ejecución. Lo que hacemos es esa lambda llamar a poly.contains(), creando un Point con las coordenadas extraidas de esa fila. El resultado de cada llamada a la lambda será True o False, por lo que al final el DF2.apply() te retorna una serie (columna) de Trues y Falses. Aplicamos eso como índice de DF2[] para seleccionar sólo aquellas filas en que haya salido True.
El resultado son ya sólo las filas que corresponden a puntos dentro del polígono.
Para demostrarlo, voy a pintar con una X azul todos los puntos de DF2 y con un punto rojo todos los puntos del dataframe resultante dentro (además del polígono en amarillo):
ax = df.plot(x="Coord_X", y="Coord_Y", kind="scatter", marker="x", color="blue")
x,y = poly.exterior.xy
ax.plot(x, y, color='yellow', alpha=2, linewidth=2, solid_capstyle='round', zorder=2)
dentro.plot(x="Coord_X", y="Coord_Y", kind="scatter", color="red", marker=".", ax=ax)
y este es el resultado:
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is Householder computationally more stable than modified Gram-Schmidt?
I'm having trouble nailing down why using Householder transformations yields a more stable/accurate result than the modified Gram-Schmidt method when computing the QR decomposition of a matrix. Can anyone explain?
Thanks
A:
Both algorithms compute a QR factorisation of a matrix $A$, that is, $A=QR$. Due to rounding errors, we have $A=\tilde{Q}\tilde{R}+E$, where $\tilde{Q}$ is no longer orthogonal (but close to in some sense). The residual $E$ is not usually the problem, for both Householder and Gram-Schmidt (even the classic one), $\|E\|\leq c\epsilon\|A\|$, where $c$ depends only on the dimension of $A$, $\epsilon$ is the machine precision. Here, $\|\cdot\|$ is some "rounding errors friendly" norm, e.g., any $p$-norm (usually $1$, $2$, or $\infty$).
The main difference is in the accuracy of the orthogonal factor.
The Householder orthogonalisation gives $\tilde{Q}$ which is almost orthogonal in the sense that $\|I-\tilde{Q}^T\tilde{Q}\|\leq c\epsilon$. In the modified Gram-Schmidt, this "loss of orthogonality" is proportional to the condition number of $A$, that is, MGS yields $\|I-\tilde{Q}^T\tilde{Q}\|\leq c\epsilon\kappa_2(A)$ (note that the Q-factor from the classical Gram-Schmidt satisfies a similar bound with the condition number of $A$ squared).
The difference between Householder and MGS is, roughly speaking, due to the fact that Householder computes the Q-factor as a product of accurate Householder reflections while MGS directly orthogonalises the columns of $A$.
By the way, both Householder and MGS compute an accurate R-factor $\tilde{R}$ in the sense of backward error. For both, there is an (exact) orthogonal matrix $\hat{Q}$ and a residual matrix $\hat{E}$ (of course different for each) such that $\|\hat{E}\|\leq c\epsilon\|A\|$ and
$A=\hat{Q}\tilde{R}+\hat{E}$.
| {
"pile_set_name": "StackExchange"
} |
Q:
BUG in sprite GameMaker
In the game you have an object called obj_Corpo, and your image is a 3x3 square. I use it by stretching it horizontally or vertically for 10 or 20 times. Here's an example:
Acontece que no jogo ele não aparece da forma adequada.
It turns out that in the game it does not appear properly.
Note that it only gives horizontal error. This began to happen a few days ago, with no explanation. I've tried other colors and the same thing happens (darkened edges).
A:
After hours of stress I found the solution only by increasing the size of the texture pages from 4096 to 8192.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bottom aligning div without specifying parent container height
I have some html like this
<div class="gRow">
<div class="cell c9 right last">Text</div>
<div class="cell c8 right gCol8">Long text wrapped over multiple lines</div>
<div class="cell c7 right gCol7">Text</div>
</div>
See this fiddle: http://jsfiddle.net/LmZYE/
What I would like is to have the two "Text" div's align to the bottom of the gRow div.
I don't know the height of gRow at render time as the text changes with selected language. I have tried positioning gRow relative and my inner div's absolute, bottom:0 but in vain.
Can I do what I'm trying to do or do I need to know the height of the gRow div?
EDIT: Forgot one thing: I would like to have a right border going all the way from the top to the bottom of gRow.
Thanks in advance!
A:
If you need to do this using divs rather than a table you can use the css for display:table to make your divs respond like a table would:
html
<div class="table">
<div class="row">
<div class="cell c9 right last">Text</div>
<div class="cell c8 right gCol8">Long text wrapped over multiple lines</div>
<div class="cell c7 right gCol7">Text</div>
</div>
</div>
css
.table {display:table; border-right: 1px solid red;}
.row {display:table-row;}
.cell {border-left: 1px solid red; display:table-cell; width:33%;}
Then you can keep adding rows and cells as you please.
You are also able to take advantage of the vertical-align property for if you want to align text to the middle or bottom of the div
http://jsfiddle.net/LmZYE/6/
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.