date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/14
| 998 | 4,134 |
<issue_start>username_0: I am making an ajax PUT request and including all the required fields for the request. I am still getting 400 error.
This is my formdata
```
var formData = new FormData()
var politician_id = this.props.image_reducer.politicianList[this.props.image_reducer.selectedPoliticianRow].person.id
console.log("id is "+ politician_id)
var politician = {
"description": document.getElementById('description-input').value,
"political_party": document.getElementById('party-input').value,
"constituency": document.getElementById('constituency-input').value,
"positions": document.getElementById('positions-input').value,
}
formData.append("name", document.getElementById('name-input').value)
formData.append("dob", document.getElementById('birth-input').value)
formData.append("born_location",document.getElementById("birth-location-input").value)
formData.append("current_location",document.getElementById('current-location-input').value)
formData.append("description", document.getElementById('description-input').value)
formData.append("father_name", document.getElementById('father-input').value)
formData.append("mother_name", document.getElementById('mother-input').value)
formData.append("partner_name", document.getElementById('name-input').value)
formData.append("religion", document.getElementById('religion-input').value)
formData.append("caste", document.getElementById('caste-input').value)
formData.append("occupation", "politician")
formData.append("education", document.getElementById('occupation-input').value)
formData.append("politician", JSON.stringify(politician))
```
This is how I am making request
```
var settings = {
"async": true,
"crossDomain": true,
"url": url,
"type": "PUT",
processData: false,
contentType: false,
"credentials": 'include',
"headers": {
Authorization: "Token " + token
},
"data": data,
success:( response, textStatus, jQxhr )=> {
console.log("info updated")
}
}
$.ajax(settings).done((response) => {
console.log("info updated success")
});
```
This is the error I am getting
[](https://i.stack.imgur.com/RZLGj.png)
[](https://i.stack.imgur.com/vKcDU.png)
It is perfectly ok from my backend side if I leave "actor" field. Please don't consider that to be a possible answer. I tried including "actor" also but still got same error.
What am I doing wrong? Am I making formdata in wrong manner?
**Update**
The JSON I am sending is (This is from console where I printed formdata)
[](https://i.stack.imgur.com/yVg76.png)<issue_comment>username_1: Looks like the data is either not passed or not converted properly on the server side and hence the validation failure. In the request headers I can notice it is sending `multipart/form-data`.
Do update the `consumes` of your `RequestMapping` to allow `multipart/form-data` i.e. `consumes = { "multipart/form-data" }`
Upvotes: 1 <issue_comment>username_2: Try sending your data as JSON:
```
var settings = {
"async": true,
"crossDomain": true,
"url": url,
"type": "PUT",
processData: false,
"credentials": 'include',
"headers": {
Authorization: "Token " + token
},
"data": data,
"contentType":"application/json; charset=utf-8",
success:( response, textStatus, jQxhr )=> {
console.log("info updated")
}
}
$.ajax(settings).done((response) => {
console.log("info updated success")
});
```
Upvotes: 0
|
2018/03/14
| 1,567 | 5,121 |
<issue_start>username_0: I often rsync files to the same directory on the remote machine. Is it possible to give it an alias so that I don't have to type it in full every time?<issue_comment>username_1: You can add alias like that `alias myrsync='rsync -av -e "ssh" user@server:/path/to/sync /path/to/local/destination'` and You can add that to your .bashrc file.
After that you type "myrsync" and command "rsync -av -e "ssh" user@server:/path/to/sync /path/to/local/destination" will be execute.
Upvotes: -1 <issue_comment>username_2: Yes. Generally I will set up short scripts that define the `rsync` options and `src` and `dest` directories or perhaps arrays containing the directories of interest, for transferring files between hosts I admin. I usually simply pass the file to transfer src and dest files as arguments to an alias for that host (so I avoid having to type the hostname, etc..). Just make sure the script is executable, and define the alias in your .bashrc. It works fine. (I generally use rs\_host for sending to a remote host, and aliases of rsf\_host (the f indicating 'from').
For example, say I have a host `valkyrie.3111skyline.com` that is reachable only within my LAN. I so a lot of mirroring, and storage of software there for updating the kids computers as well as backups of my stuff. While I have backup scripts for bulk directories, sometimes I just was to shoot a file to the server or get a file from it. I don't like to type, so I make that process as short as possible. To do that I set of aliases (as described above) with `rsvl` to `rsync` to valkyrie and `rsfvl` to `rsync` from valkyrie. If I have updated my `.bashrc` and I want to send it to valkyrie, I only want to type:
```
rsvl ~/.bashrc
```
Similarly, if I want to get a file from valkyrie (say some C file in `~/dev/src-c/tmp/getline_ex.c` and transfer it to my current directory, I only want to type:
```
rsfvl ~/dev/src-c/tmp/getline_ex.c
```
I want the scripts to take it from there. Since I know there can be corner cases and I often want to confirm a transfer involving a large number of files, I have the scripts accept the `-n` (`--dry-run`) option so that the scripts will show what will be done before they actually do it. (handy when your not quite sure)
I keep my `rsync` scripts in `~/scr/net` (not too creative, I know...). In my `.bashrc`, the aliases are simply:
```
alias rsvl='/home/david/scr/net/rsyncvl.sh'
alias rsfvl='/home/david/scr/net/rsyncfvl.sh'
```
The scripts themselves are just quick and dirty helper scripts to get `rsync` to do as I want, e.g. the `rsyncvl.sh` scritpt (to valkyrie) is:
```
#!/bin/bash --norc
desthost=valkyrie.3111skyline.com
excl='--exclude=.~* --exclude=*.class'
usage() { ## simple usage function to display usage
cat >&2 << USG
usage: ${0##*/} [[-n|--dry-run|'options'] src [dest (~/Documents)]
for
rsync [-uai[n]]'options' \$src ${desthost}:\$dest [${desthost}:~/Documents]
USG
exit 0
}
## test for '-h' or '--help'
[ -z "$1" ] || [[ "${1:0:3}" =~ '-h' ]] && usage
## test for additional options passed to rsync
if test "${1:0:1}" == '-'; then
# options present so src is $2, dest is $3
src="$2"
destfn=${3:-~/Documents}
dest="${desthost}:${destfn}"
# preserve '-n' capability for '-uain' test
if test "$1" == '-n' || test "$1" == '--dry-run'; then
echo "[DRY RUN]"
opts='-uain'
else
# use options supplied for rsync
opts="$1"
fi
else
# default use
src="$1"
destfn=${2:-~/Documents}
dest="${desthost}:${destfn}"
opts='-uai'
fi
## output the text of the comman executed
echo "rsync $opts $excl ${src} ${dest}"
if [[ "$src" =~ '*' ]]; then
rsync $opts $excl ${src} "${dest}" # allow file globbing expansion
else
rsync $opts $excl "${src}" "${dest}"
fi
```
And the script to get files from valkyrie:
```
#!/bin/bash --norc
src="$1" ## source file on srchost
dest="${2:-.}" ## destination on local machine
srchost=valkyrie.3111skyline.com
usage() { ## simple usage function to display usage
cat >&2 << USG
Usage: ${0##*/} src dest ($HOSTNAME) --> rsync -uav [${srchost}:]\$src \$dest
USG
exit 0
}
[[ -z "$1" ]] && usage
## allow '.' shorthand to set pwd as source/dest dir
[[ $src == '.' ]] && src="$(pwd)" && {
dest="$(pwd)"
dest="${dest%/*}"
}
[[ $src == './' ]] && src="$(pwd)/"
[[ $src =~ '/' ]] || src="$(pwd)/$src"
srcstr="${srchost}:${src}" ## form source string
## echo command executed and execute
echo -e "\n rsync -uav ${srcstr} ${dest}\n"
rsync -uai "${srcstr}" "${dest}"
```
They can always be improved upon, and I wasn't all that particular when I wrote the first one a decade or so ago (which somehow has been duplicated for all the other hosts I have now...) So feel free to improve and tailor them to your needs. For basic use, all you need to do is change the hostname to the hostname of your remote machine and they will work fine. Both will display a short *Usage* if run without arguments and the to valkyrie script will respond to `-h` or `--help` as well. Good luck with your transfers.
Upvotes: 3 [selected_answer]
|
2018/03/14
| 1,699 | 5,611 |
<issue_start>username_0: I'm using MongoDB for an application. I have a Collection in my db named Role with the following fields: Id, Role and I cannot change these names.
In my VS code, I have a class named Role:
```
public class Role
{
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string ApplicationName { get; set; }
[BsonElement]
public string Name { get; set; }
}
```
I have an errOR that says the element Role doesn't match the fields from db.
I wonder if there exists an attribiute I can use to keep the "Name" property and not change it to "Role" because I cannot have a property named like my class.<issue_comment>username_1: You can add alias like that `alias myrsync='rsync -av -e "ssh" user@server:/path/to/sync /path/to/local/destination'` and You can add that to your .bashrc file.
After that you type "myrsync" and command "rsync -av -e "ssh" user@server:/path/to/sync /path/to/local/destination" will be execute.
Upvotes: -1 <issue_comment>username_2: Yes. Generally I will set up short scripts that define the `rsync` options and `src` and `dest` directories or perhaps arrays containing the directories of interest, for transferring files between hosts I admin. I usually simply pass the file to transfer src and dest files as arguments to an alias for that host (so I avoid having to type the hostname, etc..). Just make sure the script is executable, and define the alias in your .bashrc. It works fine. (I generally use rs\_host for sending to a remote host, and aliases of rsf\_host (the f indicating 'from').
For example, say I have a host `valkyrie.3111skyline.com` that is reachable only within my LAN. I so a lot of mirroring, and storage of software there for updating the kids computers as well as backups of my stuff. While I have backup scripts for bulk directories, sometimes I just was to shoot a file to the server or get a file from it. I don't like to type, so I make that process as short as possible. To do that I set of aliases (as described above) with `rsvl` to `rsync` to valkyrie and `rsfvl` to `rsync` from valkyrie. If I have updated my `.bashrc` and I want to send it to valkyrie, I only want to type:
```
rsvl ~/.bashrc
```
Similarly, if I want to get a file from valkyrie (say some C file in `~/dev/src-c/tmp/getline_ex.c` and transfer it to my current directory, I only want to type:
```
rsfvl ~/dev/src-c/tmp/getline_ex.c
```
I want the scripts to take it from there. Since I know there can be corner cases and I often want to confirm a transfer involving a large number of files, I have the scripts accept the `-n` (`--dry-run`) option so that the scripts will show what will be done before they actually do it. (handy when your not quite sure)
I keep my `rsync` scripts in `~/scr/net` (not too creative, I know...). In my `.bashrc`, the aliases are simply:
```
alias rsvl='/home/david/scr/net/rsyncvl.sh'
alias rsfvl='/home/david/scr/net/rsyncfvl.sh'
```
The scripts themselves are just quick and dirty helper scripts to get `rsync` to do as I want, e.g. the `rsyncvl.sh` scritpt (to valkyrie) is:
```
#!/bin/bash --norc
desthost=valkyrie.3111skyline.com
excl='--exclude=.~* --exclude=*.class'
usage() { ## simple usage function to display usage
cat >&2 << USG
usage: ${0##*/} [[-n|--dry-run|'options'] src [dest (~/Documents)]
for
rsync [-uai[n]]'options' \$src ${desthost}:\$dest [${desthost}:~/Documents]
USG
exit 0
}
## test for '-h' or '--help'
[ -z "$1" ] || [[ "${1:0:3}" =~ '-h' ]] && usage
## test for additional options passed to rsync
if test "${1:0:1}" == '-'; then
# options present so src is $2, dest is $3
src="$2"
destfn=${3:-~/Documents}
dest="${desthost}:${destfn}"
# preserve '-n' capability for '-uain' test
if test "$1" == '-n' || test "$1" == '--dry-run'; then
echo "[DRY RUN]"
opts='-uain'
else
# use options supplied for rsync
opts="$1"
fi
else
# default use
src="$1"
destfn=${2:-~/Documents}
dest="${desthost}:${destfn}"
opts='-uai'
fi
## output the text of the comman executed
echo "rsync $opts $excl ${src} ${dest}"
if [[ "$src" =~ '*' ]]; then
rsync $opts $excl ${src} "${dest}" # allow file globbing expansion
else
rsync $opts $excl "${src}" "${dest}"
fi
```
And the script to get files from valkyrie:
```
#!/bin/bash --norc
src="$1" ## source file on srchost
dest="${2:-.}" ## destination on local machine
srchost=valkyrie.3111skyline.com
usage() { ## simple usage function to display usage
cat >&2 << USG
Usage: ${0##*/} src dest ($HOSTNAME) --> rsync -uav [${srchost}:]\$src \$dest
USG
exit 0
}
[[ -z "$1" ]] && usage
## allow '.' shorthand to set pwd as source/dest dir
[[ $src == '.' ]] && src="$(pwd)" && {
dest="$(pwd)"
dest="${dest%/*}"
}
[[ $src == './' ]] && src="$(pwd)/"
[[ $src =~ '/' ]] || src="$(pwd)/$src"
srcstr="${srchost}:${src}" ## form source string
## echo command executed and execute
echo -e "\n rsync -uav ${srcstr} ${dest}\n"
rsync -uai "${srcstr}" "${dest}"
```
They can always be improved upon, and I wasn't all that particular when I wrote the first one a decade or so ago (which somehow has been duplicated for all the other hosts I have now...) So feel free to improve and tailor them to your needs. For basic use, all you need to do is change the hostname to the hostname of your remote machine and they will work fine. Both will display a short *Usage* if run without arguments and the to valkyrie script will respond to `-h` or `--help` as well. Good luck with your transfers.
Upvotes: 3 [selected_answer]
|
2018/03/14
| 4,297 | 13,354 |
<issue_start>username_0: Given a string and a list of substring that should be replaces as placeholders, e.g.
```
import re
from copy import copy
phrases = ["'s morgen", "'s-Hertogenbosch", "depository financial institution"]
original_text = "Something, 's morgen, ik 's-Hertogenbosch im das depository financial institution gehen"
```
The first goal is to first replace the substrings from `phrases` in the `original_text` with indexed placeholders, e.g.
```
text = copy(original_text)
backplacement = {}
for i, phrase in enumerate(phrases):
backplacement["MWEPHRASE{}".format(i)] = phrase.replace(' ', '_')
text = re.sub(r"{}".format(phrase), "MWEPHRASE{}".format(i), text)
print(text)
```
[out]:
```
Something, MWEPHRASE0, ik MWEPHRASE1 im das MWEPHRASE2 gehen
```
Then there'll be some functions to manipulate the `text` with the placeholders, e.g.
```
cleaned_text = func('Something, MWEPHRASE0, ik MWEPHRASE1 im das MWEPHRASE2 gehen')
print(cleaned_text)
```
that outputs:
```
MWEPHRASE0 ik MWEPHRASE1 MWEPHRASE2
```
the last step is to do the replacement we did in a backwards manner and put back the original phrases, i.e.
```
' '.join([backplacement[tok] if tok in backplacement else tok for tok in clean_text.split()])
```
[out]:
```
"'s_morgen ik 's-Hertogenbosch depository_financial_institution"
```
The questions are:
1. If the list of substrngs in `phrases` is huge, the time to do the 1st replacement and the last backplacement would take very long.
**Is there a way to do the replacement/backplacement with a regex?**
2. using the `re.sub(r"{}".format(phrase), "MWEPHRASE{}".format(i), text)` regex substitution isn't very helpful esp. if there are substrings in the phrases that matches not the full word,
E.g.
```
phrases = ["org", "'s-Hertogenbosch", "depository financial institution"]
original_text = "Something, 's morgen, ik 's-Hertogenbosch im das depository financial institution gehen"
backplacement = {}
text = copy(original_text)
for i, phrase in enumerate(phrases):
backplacement["MWEPHRASE{}".format(i)] = phrase.replace(' ', '_')
text = re.sub(r"{}".format(phrase), "MWEPHRASE{}".format(i), text)
print(text)
```
we get an awkward output:
```
Something, 's mMWEPHRASE0en, ik MWEPHRASE1 im das MWEPHRASE2 gehen
```
I've tried using `'\b{}\b'.format(phrase)` but that'll didn't work for the phrases with punctuations, i.e.
```
phrases = ["'s morgen", "'s-Hertogenbosch", "depository financial institution"]
original_text = "Something, 's morgen, ik 's-Hertogenbosch im das depository financial institution gehen"
backplacement = {}
text = copy(original_text)
for i, phrase in enumerate(phrases):
backplacement["MWEPHRASE{}".format(i)] = phrase.replace(' ', '_')
text = re.sub(r"\b{}\b".format(phrase), "MWEPHRASE{}".format(i), text)
print(text)
```
[out]:
```
Something, 's morgen, ik 's-Hertogenbosch im das MWEPHRASE2 gehen
```
**Is there some where to denote the word boundary for the phrases in the `re.sub` regex pattern?**<issue_comment>username_1: Instead of using re.sub you can split it!
```
def do_something_with_str(string):
# do something with string here.
# for example let's wrap the string with "@" symbol if it's not empty
return f"@{string}" if string else string
def get_replaced_list(string, words):
result = [(string, True), ]
# we take each word we want to replace
for w in words:
new_result = []
# Getting each word in old result
for r in result:
# Now we split every string in results using our word.
split_list = list((x, True) for x in r[0].split(w)) if r[1] else list([r, ])
# If we replace successfully - add all the strings
if len(split_list) > 1:
# This one would be for [text, replaced, text, replaced...]
sub_result = []
ws = [(w, False), ] * (len(split_list) - 1)
for x, replaced in zip(split_list, ws):
sub_result.append(x)
sub_result.append(replaced)
sub_result.append(split_list[-1])
# Add to new result
new_result.extend(sub_result)
# If not - just add it to results
else:
new_result.extend(split_list)
result = new_result
return result
if __name__ == '__main__':
initial_string = 'acbbcbbcacbbcbbcacbbcbbca'
words_to_replace = ('a', 'c')
replaced_list = get_replaced_list(initial_string, words_to_replace)
modified_list = [(do_something_with_str(x[0]), True) if x[1] else x for x in replaced_list]
final_string = ''.join([x[0] for x in modified_list])
```
Here's variables values of the example above:
```
initial_string = 'acbbcbbcacbbcbbcacbbcbbca'
words_to_replace = ('a', 'c')
replaced_list = [('', True), ('a', False), ('', True), ('c', False), ('bb', True), ('c', False), ('bb', True), ('c', False), ('', True), ('a', False), ('', True), ('c', False), ('bb', True), ('c', False), ('bb', True), ('c', False), ('', True), ('a', False), ('', True), ('c', False), ('bb', True), ('c', False), ('bb', True), ('c', False), ('', True), ('a', False), ('', True)]
modified_list = [('', True), ('a', False), ('', True), ('c', False), ('@bb', True), ('c', False), ('@bb', True), ('c', False), ('', True), ('a', False), ('', True), ('c', False), ('@bb', True), ('c', False), ('@bb', True), ('c', False), ('', True), ('a', False), ('', True), ('c', False), ('@bb', True), ('c', False), ('@bb', True), ('c', False), ('', True), ('a', False), ('', True)]
final_string = 'ac@bbc@bbcac@bbc@bbcac@bbc@bbca'
```
As you can see the lists contain tuples. They contain two values - `some string` and `boolean`, representing whether it's a text or replaced value (`True` when text).
After you get replaced list, you can modify it as in the example, checking if it's text value (`if x[1] == True`).
Hope that helps!
*P.S. String formatting like* `f"some string here {some_variable_here}"` *requires Python 3.6*
Upvotes: 2 <issue_comment>username_2: I think there are two keys to using regular expressions for this task:
1. Use custom boundaries, capture them, and substitute them back, along with the phrase.
2. Use a function to process the substitution matches, in both directions.
Below is an implementation that uses this approach. I tweaked your text slightly to repeat one of the phrases.
```
import re
from copy import copy
original_text = "Something, 's morgen, ik 's-Hertogenbosch im das depository financial institution gehen 's morgen"
text = copy(original_text)
#
# The phrases of interest
#
phrases = ["'s morgen", "'s-Hertogenbosch", "depository financial institution"]
#
# Create the mapping dictionaries
#
phrase_to_mwe = {}
mwe_to_phrase = {}
#
# Build the mappings
#
for i, phrase in enumerate(phrases):
mwephrase = "MWEPHRASE{}".format(i)
mwe_to_phrase[mwephrase] = phrase.replace(' ', '_')
phrase_to_mwe[phrase] = mwephrase
#
# Regex match handlers
#
def handle_forward(match):
b1 = match.group(1)
phrase = match.group(2)
b2 = match.group(3)
return b1 + phrase_to_mwe[phrase] + b2
def handle_backward(match):
return mwe_to_phrase[match.group(1)]
#
# The forward regex will look like:
#
# (^|[ ])('s morgen|'s-Hertogenbosch|depository financial institution)([, ]|$)
#
# which captures three components:
#
# (1) Front boundary
# (2) Phrase
# (3) Back boundary
#
# Anchors allow matching at the beginning and end of the text. Addtional boundary characters can be
# added as necessary, e.g. to allow semicolons after a phrase, we could update the back boundary to:
#
# ([,; ]|$)
#
regex_forward = re.compile(r'(^|[ ])(' + '|'.join(phrases) + r')([, ]|$)')
regex_backward = re.compile(r'(MWEPHRASE\d+)')
#
# Pretend we cleaned the text in the middle
#
cleaned = 'MWEPHRASE0 ik MWEPHRASE1 MWEPHRASE2 MWEPHRASE0'
#
# Do the translations
#
text1 = regex_forward .sub(handle_forward, text)
text2 = regex_backward.sub(handle_backward, cleaned)
print('original: {}'.format(original_text))
print('text1 : {}'.format(text1))
print('text2 : {}'.format(text2))
```
Running this generates:
```
original: Something, 's morgen, ik 's-Hertogenbosch im das depository financial institution gehen 's morgen
text1 : Something, MWEPHRASE0, ik MWEPHRASE1 im das MWEPHRASE2 gehen MWEPHRASE0
text2 : 's_morgen ik 's-Hertogenbosch depository_financial_institution 's_morgen
```
Upvotes: 2 <issue_comment>username_3: Here's a strategy you could use:
```
phrases = ["'s morgen", "'s-Hertogenbosch", "depository financial institution"]
original_text = "Something, 's morgen, ik 's-Hertogenbosch im das depository financial institution gehen"
# need this module for the reduce function
import functools as fn
#convert phrases into a dictionary of numbered placeholders (tokens)
tokens = { kw:"MWEPHRASE%s"%i for i,kw in enumerate(phrases) }
#replace embedded phrases with their respective token
tokenized = fn.reduce(lambda s,kw: tokens[kw].join(s.split(kw)), phrases, original_text)
#Apply text cleaning logic on the tokenized text
#This assumes the placeholders are left untouched,
#although it's ok to move them around)
cleaned_text = cleanUpfunction(tokenized)
#reverse the token dictionary (to map original phrases to numbered placeholders)
unTokens = {v:k for k,v in tokens.items() }
#rebuild phrases with original text associated to each token (placeholder)
final_text = fn.reduce(lambda s,kw: unTokens[kw].join(s.split(kw)), phrases, cleaned_text)
```
Upvotes: 1 <issue_comment>username_4: What you are looking for is called "multi-string search" or "multi-pattern search". The more common solutions are Aho-Corasick and Rabin-Karp algorithms. If you want to impement it yourself, go with Rabin-Karp, since its easier to grasp. Otherwise, you'll find some libraries. Here's a solution with the library <https://pypi.python.org/pypi/py_aho_corasick>.
Let
```
phrases = ["'s morgen", "'s-Hertogenbosch", "depository financial institution"]
original_text = "Something, 's morgen, ik 's-Hertogenbosch im das depository financial institution gehen"
```
And, for testing purposes:
```
def clean(text):
"""A simple stub"""
assert text == 'Something, MWEPHRASE0, ik MWEPHRASE1 im das MWEPHRASE2 gehen'
return "MWEPHRASE0 ik MWEPHRASE1 MWEPHRASE2"
```
Now, you have to define two automatons, one for the outward journey, and the other for the return. An automaton is defined by a list of (key,value):
```
fore_automaton = py_aho_corasick.Automaton([(phrase,"MWEPHRASE{}".format(i)) for i, phrase in enumerate(phrases)])
back_automaton = py_aho_corasick.Automaton([("MWEPHRASE{}".format(i), phrase.replace(' ','_')) for i, phrase in enumerate(phrases)])
```
The automaton will scan the text and return a list of matches. A match is a triplet (position, key, value). With a little work on matches, you'll be able to replace keys by values:
```
def process(automaton, text):
"""Returns a new text, with keys of the automaton replaced by values"""
matches = automaton.get_keywords_found(text.lower()) # text.lower() because auomaton of py_aho_corasick uses lowercase for keys
bk_value_eks = [(i,v,i+len(k)) for i,k,v in matches] # (begin of key, value, end of key)
chunks = [bk_value_ek1[1]+text[bk_value_ek1[2]:bk_value_ek2[0]] for bk_value_ek1,bk_value_ek2 in zip([(-1,"",0)]+bk_value_eks, bk_value_eks+[(len(text),"",-1)] if bk_value_ek1[2] <= bk_value_ek2[0]] # see below
return "".join(chunks)
```
A brief explanation on `chunks = [bk_value_ek1[1]+text[bk_value_ek1[2]:bk_value_ek2[0]] for bk_value_ek1,bk_value_ek2 in zip([(-1,"",0)]+bk_value_eks, bk_value_eks+[(len(text),"",-1)] if bk_value_ek1[2] <= bk_value_ek2[0]]`.
I zip matches with itself almost as usual : `zip(arr, arr[1:])` will output `(arr[0], arr[1)), (arr[1], arr[2]), ...` to consider every match with its sucessor. Here I placed two sentinels
to handle the begin and the end of matches.
* For the normal case, I just output the value (=`bk_value_ek1[1]`) and the text between the end of the key and the begin of the next key (`text[bk_value_ek1[2]:bk_value_ek2[0]`).
* The begin sentinel has an empty value, and its key ends at position 0, thus the first chunk will be "" + text[0:begin of key1], that is the text before the first key.
* Similarly, the end sentinel has also an empty value and its key begins at the end of the text, thus the last chunk will be : value of the last match + text[end of the last key:len(text)].
*What happens when keys overlap? Take an example: `text="abcdef"`, `phrases={"bcd":"1", "cde":"2"}`. You have two matches: `(1, "bcd", "1")` and `(2, "cde", "3")`.
Let's go: `bk_value_eks = [(1, "1", 4), (2, "2", 5)]`. Thus, without `if bk_value_ek1[2] <= bk_value_ek2[0]`, the text will be replaced by `text[:1]+"1"+text[4:2]+"2"+text[5:]`,
that is `"a"+"1"+""+"2"+"f"` = `"a12f"` instead of `"a1ef"` (ignore the second match)...*
Now, take a look a the result:
```
print(process(back_automaton, clean(process(fore_automaton, original_text))))
# "'s_morgen ik 's-Hertogenbosch depository_financial_institution"
```
You don't have to define a new `process` function for the return, just give it the `back_automaton` and it will do the job.
Upvotes: 1
|
2018/03/14
| 549 | 1,807 |
<issue_start>username_0: In postman,
I post the array like
[](https://i.stack.imgur.com/2g9wU.png)
```
key => Image[] / value => 1
key => Image[] / value => 2
key => Image[] / value => 3
```
I want when I put an array which user's card images, receive the card's Idx and Name.
So I make query like this,
```
$query = "SELECT DISTINCT
Idx AS Idx,
Name AS Name
FROM Card
WHERE Card.Image IN ('$_POST[Image]')";
```
But, It receive no data.
So I remove '' so
```
WHERE Card.Image IN ('$_POST[Image]')"
=> WHERE Card.Image IN ($_POST[Image])";
```
Then return Unknown column 'Array' in 'where clause'
I don't know what is problem of this.
when I post array like /key name[]/value 1
I know it can receive $\_POST[name].
How I can post array and receive of it.
Please help me.<issue_comment>username_1: ```
$string=$_POST[Image];
$array=array_map('intval', explode(',', $string));
$array = implode("','",$array);
$query = "SELECT DISTINCT Idx AS Idx, Name AS Name FROM Card WHERE
Card.Image IN ('".$array."')";
```
Upvotes: 0 <issue_comment>username_2: I hope `Image` column contains numbers.
Use `implode()` to correct your `IN` query
```
$string=$_POST['Image'];
$array= implode(',', $string);
$query = "SELECT DISTINCT Idx AS Idx, Name AS Name FROM Card WHERE Card.Image IN ($array)";
```
***Note:-***
1.Query will become:-`SELECT DISTINCT Idx AS Idx, Name AS Name FROM Card WHERE Card.Image IN (1,2,3)`. Now it will execute fine.
2.Try to use ***`prepared statements`*** of ***`mysqli_*`*** or ***`PDO`*** to prevent your code from ***`SQL-INJECTION`***. You current code is wide-open for it.
Upvotes: 2 [selected_answer]
|
2018/03/14
| 322 | 1,114 |
<issue_start>username_0: I have this batch file which runs the powershell script.
I want to run it the background but if I run with "windowstyle hidden" still visible.
powershell -ExecutionPolicy ByPass -windowstyle hidden -File "C:\script.ps1"<issue_comment>username_1: ```
$string=$_POST[Image];
$array=array_map('intval', explode(',', $string));
$array = implode("','",$array);
$query = "SELECT DISTINCT Idx AS Idx, Name AS Name FROM Card WHERE
Card.Image IN ('".$array."')";
```
Upvotes: 0 <issue_comment>username_2: I hope `Image` column contains numbers.
Use `implode()` to correct your `IN` query
```
$string=$_POST['Image'];
$array= implode(',', $string);
$query = "SELECT DISTINCT Idx AS Idx, Name AS Name FROM Card WHERE Card.Image IN ($array)";
```
***Note:-***
1.Query will become:-`SELECT DISTINCT Idx AS Idx, Name AS Name FROM Card WHERE Card.Image IN (1,2,3)`. Now it will execute fine.
2.Try to use ***`prepared statements`*** of ***`mysqli_*`*** or ***`PDO`*** to prevent your code from ***`SQL-INJECTION`***. You current code is wide-open for it.
Upvotes: 2 [selected_answer]
|
2018/03/14
| 637 | 2,164 |
<issue_start>username_0: I'm looking at the [webpush-java](https://github.com/web-push-libs/webpush-java) code. I run into a problem attempting to build the project using gradle. (I'm a gradle newbie).
>
> :signArchives FAILED
>
>
> FAILURE: Build failed with an exception.
>
>
> * What went wrong: Execution failed for task ':signArchives'.
>
> Cannot perform signing task ':signArchives' because it has no
> configured signatory
>
>
>
I guess that I need to configure a signatory. How do I do that?<issue_comment>username_1: Found solution here <https://github.com/jaegertracing/jaeger-client-java/issues/202>
Use the below command.
>
> ./gradlew assemble -x signArchives
>
>
>
Upvotes: -1 <issue_comment>username_2: Quoting the [Signing plugin documentation](https://docs.gradle.org/current/userguide/signing_plugin.html#sec:signatory_credentials) you should be able to resolve the error when you provide the expected GPG variables in the *gradle.properties* file in your *HOME* directory:
```groovy
# File location: ~/.gradle/gradle.properties - see https://docs.gradle.org/current/userguide/directory_layout.html
signing.keyId=24875D73
signing.password=<PASSWORD>
signing.secretKeyRingFile=/Users/me/.gnupg/secring.gpg
```
Gradle resp. the Signing plugin will automatically pick them up in the build process.
Upvotes: 4 <issue_comment>username_3: I got the same problem and it was because of several things:
**I didn't distribute the gpg key to any server;
I was using inMemory to sign and I shouldn't**
the link of the complete answer with build.gradle file and gradle.properties file: <https://stackoverflow.com/a/68505768/7937498>
Upvotes: 0 <issue_comment>username_4: Another option that does not require a special command-line option is to add the following in your build.gradle:
```
signing {
setRequired {
// signing is only required if the artifacts are to be published
gradle.taskGraph.allTasks.any { it.equals( PublishToMavenRepository) }
}
....
```
See e.g. <https://github.com/Vampire/command-framework/blob/master/buildSrc/src/main/kotlin/net/kautler/publishing.gradle.kts#L157>
Upvotes: 2
|
2018/03/14
| 619 | 2,217 |
<issue_start>username_0: I'm using Cordova to build Android/IOS app with Javascript
Versions:
```
cordova-android: 6.2.3
cordova-ios: 4.4.0
```
Before continue actions, user must be re-ask to confirm. A comfirmation popup will be displayed.
Problem is user can scroll background screen when popup shown in their own device. In development environment (browser), its working perfectly by setting popup wrapper full size of screen. I need disable scrolling in device for this case.
What are the best and simplest ways to fixed it?
Sorry for my bad English!<issue_comment>username_1: Found solution here <https://github.com/jaegertracing/jaeger-client-java/issues/202>
Use the below command.
>
> ./gradlew assemble -x signArchives
>
>
>
Upvotes: -1 <issue_comment>username_2: Quoting the [Signing plugin documentation](https://docs.gradle.org/current/userguide/signing_plugin.html#sec:signatory_credentials) you should be able to resolve the error when you provide the expected GPG variables in the *gradle.properties* file in your *HOME* directory:
```groovy
# File location: ~/.gradle/gradle.properties - see https://docs.gradle.org/current/userguide/directory_layout.html
signing.keyId=24875D73
signing.password=<PASSWORD>
signing.secretKeyRingFile=/Users/me/.gnupg/secring.gpg
```
Gradle resp. the Signing plugin will automatically pick them up in the build process.
Upvotes: 4 <issue_comment>username_3: I got the same problem and it was because of several things:
**I didn't distribute the gpg key to any server;
I was using inMemory to sign and I shouldn't**
the link of the complete answer with build.gradle file and gradle.properties file: <https://stackoverflow.com/a/68505768/7937498>
Upvotes: 0 <issue_comment>username_4: Another option that does not require a special command-line option is to add the following in your build.gradle:
```
signing {
setRequired {
// signing is only required if the artifacts are to be published
gradle.taskGraph.allTasks.any { it.equals( PublishToMavenRepository) }
}
....
```
See e.g. <https://github.com/Vampire/command-framework/blob/master/buildSrc/src/main/kotlin/net/kautler/publishing.gradle.kts#L157>
Upvotes: 2
|
2018/03/14
| 677 | 2,770 |
<issue_start>username_0: This is the part of my code that doesn't work. The `else` statement works fine but when the `password` is wrong the program just closes abruptly.
```
if logged_in == 'admin':
tries = -3
while tries < 0:
password = input("enter <PASSWORD> password. ")
if password != '<PASSWORD>':
print("incorrect password. Try again. " + tries + " tries left.")
tries = tries + i
else:
print("Hello admin, would you like to see a status report?")
input()
import sys
sys.exit(0)
```
This is the entire code:
```
users = ['anonymous', 'me', 'bill', '<PASSWORD>']
i = 1
while i == 1:
logged_in = input("Username:\n")
if logged_in == 'admin':
tries = -3
while tries < 0:
password = input("enter <PASSWORD>. ")
if password != '<PASSWORD>':
print("incorrect password. Try again. " + tries + " tries left.")
tries = tries + i
else:
print("Hello admin, would you like to see a status report?")
input()
import sys
sys.exit(0)
if logged_in in users:
print ("Hello " + logged_in + ", welcome back!")
break
else:
print ("invalid username. Do you wish to create an account? (Y/N)\n")
create_account = input()
if create_account == 'Y' or create_account == 'y':
new_username = input("Enter new username: ")
print("You have creted a new account. Welcome, " + new_username)
users.append(new_username)
else:
print ("Goodbye.")
break
input()
```<issue_comment>username_1: Your error is that on this line
```
print("incorrect password. Try again. " + tries + " tries left.")
```
`tries` is an int, whereas the other parts are strings. As you cannot add these two types, you get an error which is
```
TypeError: must be str, not int
```
To fix this just change the line to
```
print("incorrect password. Try again. " + str(tries) + " tries left.")
```
On an unrelated note, it is usually recommended that imports are at the top of your program.
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
print("incorrect password. Try again. " + tries + " tries left.")
```
This is incorrect as tries is an integer and therefore cannot be concatenated with the two other parts in the quotation marks as they are strings and needs to be converted into a string first to do so. eg.
```
print("incorrect password. Try again. " + str(tries) + " tries left.")
```
Upvotes: 1
|
2018/03/14
| 673 | 2,613 |
<issue_start>username_0: I got a bunch of logs, each one with the following format:
```
10-20-2016 13:57:28 [main] ERROR com.project.Main:11 - Error message here
```
The template of this log is:
```
: -
```
I want to parse that log and create a Java object with fields that match each token on that template.
I know that I can do this by hand, using a String Tokenizer, but I want to know first if there is some parsing library that already solves this problem (probably much better than I would do it).
I'm looking for something that supports that kind of templating: if I change the template, the parser should just extract those fields that match the template.<issue_comment>username_1: The short answer is no.
Not with all of the attributes you've described actually. Each logging framework ( log4j, logback, JUL are the big 3 ) have different configuration semantics so any solution would be specific to the backend in question.
Most of them have some sort of [LogEvent](http://logging.apache.org/log4j/2.x/log4j-core/apidocs/org/apache/logging/log4j/core/LogEvent.html) object or something that exists in the form you want as it get's passed through the pipeline before it ends in a file or whatever.
Figure out which logging back end you are using and just add an appender that serializes that thing to an [ObjectOputStream](https://docs.oracle.com/javase/9/docs/api/java/io/ObjectOutputStream.html) and read it later at your leisure.
Upvotes: 2 [selected_answer]<issue_comment>username_2: You're barking up the wrong tree here entirely. The idea is to install a handler that receives data according to the logging API you are using, and do with that data whatever you wish. Parsing logger output is doomed to failure sooner or later.
Upvotes: 1 <issue_comment>username_3: What works for a lot of cases is just making sure the logs are coming in a structured format.
If they come from outside you can pass them through [fluentd](https://www.fluentd.org/) and keep the most of the structure available. If you are using Logback or log4j there are libraries that can help with that such as [logback-more-appenders](https://github.com/sndyuk/logback-more-appenders)
This does not solve all cases though and sometimes even the structured logs still have the message that could use some parsing to extract values. In such case you need to write a custom parser... or use a dedicated solution that will do its best at figuring out what is the log pattern and extract parameters: <https://www.logsense.com/blog/integrating-java-logs-with-logsense> (disclaimer, I am working on it)
Upvotes: 0
|
2018/03/14
| 473 | 1,479 |
<issue_start>username_0: I'm trying to replace a word characters with other 'any' special characters, like in this example:
```
"if there is a definitive answer ? $120.223"
to
"** ***** ** * ********* ****** * ****.***"
```
or by maintain the first and the last character of each word, as:
```
"if there is a definitive answer ? $120.223"
to
"if t***e is a d*******e a****r ? $***.**3"
```
Could that be achieved using regex instead of build a pure-code (manually) function?
I think it could be achieve using sub function in re python library, but I don't have an idea to what use in the second parameter of the function (repl) !? if so, any proposed resource?<issue_comment>username_1: You can use a regex to select the middle of non-whitespace sequences
```
([^\s])([^\s]*)([^\s])
```
then replace the middle part (\2) with the proper number of \* characters. If you want to skip the . character you'll have to do that separately
Upvotes: 1 <issue_comment>username_2: ```
import re
s="if there is a definitive answer ? $120.223"
print(s)
print(re.sub("[a-z]|[A-Z]|[0-9]", '*', s))
```
output
```
if there is a definitive answer ? $120.223
** ***** ** * ********** ****** ? $***.***
```
Upvotes: 1 <issue_comment>username_3: I solved it, since there is no function to know the length of middle characters as @Lance\_Toth said in his comment, I worked on the "character level" in regex:
```
reg = r'((?
```
output:
```
T***e s**m to be an , f*f
```
Upvotes: 0
|
2018/03/14
| 649 | 2,087 |
<issue_start>username_0: I stumbled upon this problem while saving an int in a char array and converting it back. I used bit shifts and logic or, but my result ended up with all the bytes after the least significant as 0xFF.
My question is: considering this example
```
#include
int main() {
char c1 = 0x86;
unsigned char c2 = 0x86;
unsigned int i1 = 0, i2 = 0;
i1 = (unsigned int) c1;
i2 = (unsigned int) c2;
printf("%x-%x\n", i1, i2);
}
```
Why is the output `ffffff86-86`? Why does the char have all its upper bits set to 1?
I'm sure there is a very simple answer, but I couldn't come up with a specific enough query to find it on google.<issue_comment>username_1: It's implementation defined if a `char` is signed or unsigned.
If `char` is signed, then when being [promoted to an `int`](http://en.cppreference.com/w/c/language/conversion#Integer_promotions) it will be *sign extended*, so a negative value will keep its negative value after the promotion.
The leading `1` bits is how negative numbers are represented in [two's complement](https://en.wikipedia.org/wiki/Two's_complement) systems, which is the most common way to handle negative numbers.
---
If, with your compiler, `char` is signed (which it seems to be) then the initialization of `c1` should generate a warning. If it doesn't then you need to enable more warnings.
Upvotes: 3 [selected_answer]<issue_comment>username_2: `char c1 = 0x86;` here `c1` by default type is `signed`
```
c1 => 1000 0110
|
signed bit is set(1)
```
When statement
`i1 = (unsigned int) c1;` executes sign bit of `c1` gets copied into remaining bytes of `i1` as
```
i1 => 1000 0110
|
|<--this sign bit
1111 1111 1111 1111 1111 1111 1000 0110
f f f f f f 8 6
```
And `i2 = (unsigned int) c2;` here `i2` and `c2` both declared as `unsigned` type so in this case `sign bit` will not be copied into remaining bytes so it prints what's the data in `1st byte` which is `0x86`
Upvotes: 2
|
2018/03/14
| 706 | 2,229 |
<issue_start>username_0: I've a SQL which creates few metrics in below format and I want to transpose them into rows at every 'n'-th column for example, cut every 4 columns and convert into rows. Also there can be 'n' number of columns i.e 12, 20, 40, etc (multiples of 4 in my case).
I need to load these rows into a table.
Find below example,

Sample data.
```
SELECT 1 AS col1, 'Total number of Customer' AS col2, 100 AS col3, NULL AS col4,
1.1 AS col5, 'Total active customers' AS col6, 50 AS col7, NULL AS col8,
1.2 AS col9, 'Total inactive customers' AS col10, 50 AS col11,ABC AS col12
FROM DUAL;
```
---
**Note**: There could be `n` number of columns. It can be 12, 40 (multiples of 4 in my case).<issue_comment>username_1: It's implementation defined if a `char` is signed or unsigned.
If `char` is signed, then when being [promoted to an `int`](http://en.cppreference.com/w/c/language/conversion#Integer_promotions) it will be *sign extended*, so a negative value will keep its negative value after the promotion.
The leading `1` bits is how negative numbers are represented in [two's complement](https://en.wikipedia.org/wiki/Two's_complement) systems, which is the most common way to handle negative numbers.
---
If, with your compiler, `char` is signed (which it seems to be) then the initialization of `c1` should generate a warning. If it doesn't then you need to enable more warnings.
Upvotes: 3 [selected_answer]<issue_comment>username_2: `char c1 = 0x86;` here `c1` by default type is `signed`
```
c1 => 1000 0110
|
signed bit is set(1)
```
When statement
`i1 = (unsigned int) c1;` executes sign bit of `c1` gets copied into remaining bytes of `i1` as
```
i1 => 1000 0110
|
|<--this sign bit
1111 1111 1111 1111 1111 1111 1000 0110
f f f f f f 8 6
```
And `i2 = (unsigned int) c2;` here `i2` and `c2` both declared as `unsigned` type so in this case `sign bit` will not be copied into remaining bytes so it prints what's the data in `1st byte` which is `0x86`
Upvotes: 2
|
2018/03/14
| 1,866 | 6,553 |
<issue_start>username_0: This question is about different behaviour of `JEditorPane` in Java 8 and Java 9. I’d like to know if others have experienced the same, whether it could be a bug in Java 9, and if possible have your input to how to handle it in Java 9.
Context: In our (age-old) code base we are using a subclass of `JTable`, and for rendering multi-line HTML in one of the columns we are using a subclass of `JEditorPane`. We are using `JEditorPane.getPreferredSize()` for determining the height of the content and using it for setting the height of the table row. It’s been working well for many years. It doesn’t work in Java 9; the rows are displayed just 10 pixels high. Seen both on Windows and Mac.
I should like to show you two code examples. If the first and shorter one suffices for you, feel free to skip the second and longer one.
MCVE:
```
JEditorPane pane = new JEditorPane("text/html", "");
pane.setText("One line");
System.out.println(pane.getPreferredSize());
pane.setText("Line one
Line 2
Third line
Line four");
System.out.println(pane.getPreferredSize());
```
Output in Java 8 (1.8.0\_131):
```
java.awt.Dimension[width=48,height=15]
java.awt.Dimension[width=57,height=60]
```
And on Java 9 (jdk-9.0.4):
```
java.awt.Dimension[width=49,height=15]
java.awt.Dimension[width=58,height=0]
```
In Java 9 the first time I set the text, the preferred height reflects it. Every subsequent time it doesn’t.
I have searched to see if I could find any information on a bug that might account for this, did not find anything relevant.
**Question: Is this intended (change of) behaviour? Is it a bug??**
Longer example
--------------
```
public class TestJEditorPaneAsRenderer extends JFrame {
public TestJEditorPaneAsRenderer() {
super("Test JEditorPane");
MyRenderer renderer = new MyRenderer();
String html2 = "one/2
two/2";
String html4 = "one of four
two of four
"
+ "three of four
four of four";
JTable table = new JTable(new String[][] { { html2 }, { html4 } },
new String[] { "Dummy col title" }) {
@Override
public TableCellRenderer getDefaultRenderer(Class colType) {
return renderer;
}
};
add(table);
setSize(100, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
System.out.println(System.getProperty("java.version"));
new TestJEditorPaneAsRenderer().setVisible(true);
}
}
class MyRenderer extends JEditorPane implements TableCellRenderer {
public MyRenderer() {
super("text/html", "");
}
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean selected, boolean hasFocus, int row, int col) {
setText(value.toString());
Dimension preferredSize = getPreferredSize();
System.out.format("Row %d preferred size %s%n",row, preferredSize);
if (preferredSize.height > 0 && table.getRowHeight(row) != preferredSize.height) {
table.setRowHeight(row, preferredSize.height);
}
return this;
}
}
```
Result on Java 8 is as expected:
[](https://i.stack.imgur.com/MhPRc.png)
Output from Java 8:
```
1.8.0_131
Row 0 preferred size java.awt.Dimension[width=32,height=30]
Row 1 preferred size java.awt.Dimension[width=72,height=60]
Row 0 preferred size java.awt.Dimension[width=32,height=30]
Row 1 preferred size java.awt.Dimension[width=72,height=60]
```
On Java 9 the second row is not shown high enough so most of the lines are hidden:
[](https://i.stack.imgur.com/vIduJ.png)
Output from Java 9:
```
9.0.4
Row 0 preferred size java.awt.Dimension[width=33,height=30]
Row 1 preferred size java.awt.Dimension[width=73,height=0]
Row 0 preferred size java.awt.Dimension[width=33,height=0]
Row 1 preferred size java.awt.Dimension[width=73,height=0]
```
A possible fix is if I create a new renderer component each time by changing the body of `getDefaultRenderer()` to:
```
return new MyRenderer();
```
Now the table looks good as on Java 8. If necessary I suppose we could live with a similar fix in our production code, but it seems quite a waste. Especially if it’s only necessary until the behaviour change is reverted in a coming Java version. **I’d be grateful for your suggestions here.**<issue_comment>username_1: I have faced similar problem, but with JLabel. My solution was to set the size of the JLabel which seems to force the component to recalculate its preferred size.
Try this:
```
JEditorPane pane = new JEditorPane("text/html", "");
pane.setText("One line");
System.out.println(pane.getPreferredSize());
pane.setText("Line one
Line 2
Third line
Line four");
// get width from initial preferred size, height should be much larger than necessary
pane.setSize(61, 1000);
System.out.println(pane.getPreferredSize());
```
In this casse the output is
```
java.awt.Dimension[width=53,height=25]
java.awt.Dimension[width=61,height=82]
```
Note: my fonts are different, that is why I get different dimensions.
Edit: I changed your getTableCellRendererComponent in the longer example like this and it is working for me. I am using jdk9.0.4, 64 bit.
```
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean hasFocus, int row, int col) {
setText(value.toString());
Dimension preferredSize = getPreferredSize();
setSize(new Dimension(preferredSize.width, 1000));
preferredSize = getPreferredSize();
System.out.format("Row %d preferred size %s%n", row, preferredSize);
if (preferredSize.height > 0 && table.getRowHeight(row) != preferredSize.height) {
table.setRowHeight(row, preferredSize.height);
}
return this;
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Based on previous suggestion and digging in JDK sources I'm suggesting a little bit simpler solution:
```
setSize(new Dimention(0, 0))
```
Based on BasicTextUI.getPreferredSize implementation it forces to recalculate root view size
```
} else if (d.width == 0 && d.height == 0) {
// Probably haven't been layed out yet, force some sort of
// initial sizing.
rootView.setSize(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
```
Upvotes: 0
|
2018/03/14
| 819 | 3,426 |
<issue_start>username_0: I am creating an CRUD Application in Asp.Net Core
After Add Operation I am redirecting to same view with setting model value as null to get another entry
Below is my code
```
public IActionResult Add(OptionMasterVM model)
{
try
{
model.QuestionList = context.QuestionMaster.Select(x => new SelectListItem { Text = x.QuestionName, Value = x.QuestionId.ToString() }).ToList();
if (HttpContext.Request.Method == "POST")
{
OptionMaster _optionmaster = new OptionMaster();
_optionmaster = model.OptionMaster;
using (var ctx = new QuestionnaireEntities(_configuration))
{
ctx.OptionMaster.Add(_optionmaster);
ctx.SaveChanges();
}
TempData["Msg"] = "Option Added Successfully , Add Another Option";
model.OptionMaster.OptionValue = string.Empty;
model.OptionMaster.OptionRating = 0;
return View(model);
}
}
catch (Exception ex)
{
logger.LogError(ex);
}
finally
{
}
return View(model);
}
```
Here I am setting Option Value to empty and rating to Zero to take next entry , but on view it does not show empty and zero , on view it show previously filled value.
[](https://i.stack.imgur.com/OP3zX.png)
After Setting below code these two fields should be reset but they don't
```
model.OptionMaster.OptionValue = string.Empty;
model.OptionMaster.OptionRating = 0;
```
Is there any other way to set model object as null in Asp.net Core ?<issue_comment>username_1: This can happen because Razor helpers use values from ModelState, rather than the model itself. Your OptionValue is probably displayed using a helper, for example:
```
@Html.TextBoxFor(m => m.OptionMaster.OptionValue)
```
When you change model values within an action, you need remove the old values from ModelState before rendering the View.
The easiest way of doing this is to call [ModelState.Clear()](https://msdn.microsoft.com/en-us/library/system.web.mvc.modelstatedictionary.clear(v=vs.118).aspx)
```
model.OptionMaster.OptionValue = string.Empty;
model.OptionMaster.OptionRating = 0;
ModelState.Clear(); // ensure these changes are rendered in the View
return View(model);
```
Upvotes: 2 <issue_comment>username_2: The values displayed for bound form fields come from `ModelState`, which is composed based on values from `Request`, `ViewData`/`ViewBag`, and finally `Model`. After posting, obviously, you'll have values set in `Request`, which will therefore be the values in `ModelState`. It works this way, so that when there's a validation error and the user is returned to the form to correct their mistakes, the values they posted will be there for them to edit.
Long and short, you need to follow the PRG (Post-Redirect-Get) pattern. Essentially, after posting, you only return the view on error. If the post is successful, you *redirect*. This not only clears `ModelState`, but also prevents accidental re-posts if the user attempts to refresh the page.
If you want to take the user back to the same view, simply redirect to the same action, but you need to do a redirect, not return the view.
Upvotes: 1
|
2018/03/14
| 420 | 1,605 |
<issue_start>username_0: I've just started to use GCP and I have some doubts regarding the right use of some of its tools. Particularly, I'm trying to ingest data from Google Analytics into BigQuery. Would it be possible to use Dataprep on data stored in BigQuery? Almost every example I've seen uses Dataprep to visualize data stored in Google Storage, but nothing refers to BigQuery.
Any help would be really appreciated.<issue_comment>username_1: You can totally use Dataprep to process data stored in BigQuery. It gives you a great way to visualize how your dataset looks, and interactively define transformations.
Now, do you really want to use Dataprep for this? The transformations will be more expensive and slow, as they will run on Dataflow - which is usually more expensive and slow than doing everything within BigQuery (as the question refers to data that's already in BigQuery).
On the other hand, the interactive environment can help you quickly define what you want and run the created recipe periodically.
See more about this on Lak's "How to schedule a BigQuery ETL job with Dataprep".
* <https://medium.com/google-cloud/how-to-schedule-a-bigquery-etl-job-with-dataprep-b1c314883ab9>.
Upvotes: 2 <issue_comment>username_2: According to the [documentation on Dataprep](https://cloud.google.com/dataprep/docs/html/BigQuery-Browser_59736137), you can import BigQuery datasets.
But it might be easier to just to open Dataprep and check the importing options there:
[](https://i.stack.imgur.com/PFXI1.png)
Upvotes: 0
|
2018/03/14
| 406 | 1,476 |
<issue_start>username_0: To upload a file I use
`Storage::disk('spaces')->putFile('uploads', $request->file, 'public');`
The file is saved successfully on digital ocean spaces. But I want to rename it to something like this `user_1_some_random_string.jpg`. And then save it.
How can I do it?<issue_comment>username_1: You can totally use Dataprep to process data stored in BigQuery. It gives you a great way to visualize how your dataset looks, and interactively define transformations.
Now, do you really want to use Dataprep for this? The transformations will be more expensive and slow, as they will run on Dataflow - which is usually more expensive and slow than doing everything within BigQuery (as the question refers to data that's already in BigQuery).
On the other hand, the interactive environment can help you quickly define what you want and run the created recipe periodically.
See more about this on Lak's "How to schedule a BigQuery ETL job with Dataprep".
* <https://medium.com/google-cloud/how-to-schedule-a-bigquery-etl-job-with-dataprep-b1c314883ab9>.
Upvotes: 2 <issue_comment>username_2: According to the [documentation on Dataprep](https://cloud.google.com/dataprep/docs/html/BigQuery-Browser_59736137), you can import BigQuery datasets.
But it might be easier to just to open Dataprep and check the importing options there:
[](https://i.stack.imgur.com/PFXI1.png)
Upvotes: 0
|
2018/03/14
| 578 | 2,022 |
<issue_start>username_0: I'm using Great Schools Api :
```
fetch("https://api.greatschools.org/search/schools?key=***********&state=CA&q=cupertino&levelCode=elementary-schools&limit=1",{
method: 'GET',
Accept:'application/xml',
headers : new Headers ({
'content-type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT',
'Access-Control-Allow-Headers': 'Content-Type',
}),
mode:'no-cors'
})
.then(response => {
console.log(response, 'data')
})
```
console for response is :
```
Response
bodyUsed: false
headers: Headers { }
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
```
But in Browser Network console I'm geting correct XMl response.
How to get correct response.<issue_comment>username_1: You can totally use Dataprep to process data stored in BigQuery. It gives you a great way to visualize how your dataset looks, and interactively define transformations.
Now, do you really want to use Dataprep for this? The transformations will be more expensive and slow, as they will run on Dataflow - which is usually more expensive and slow than doing everything within BigQuery (as the question refers to data that's already in BigQuery).
On the other hand, the interactive environment can help you quickly define what you want and run the created recipe periodically.
See more about this on Lak's "How to schedule a BigQuery ETL job with Dataprep".
* <https://medium.com/google-cloud/how-to-schedule-a-bigquery-etl-job-with-dataprep-b1c314883ab9>.
Upvotes: 2 <issue_comment>username_2: According to the [documentation on Dataprep](https://cloud.google.com/dataprep/docs/html/BigQuery-Browser_59736137), you can import BigQuery datasets.
But it might be easier to just to open Dataprep and check the importing options there:
[](https://i.stack.imgur.com/PFXI1.png)
Upvotes: 0
|
2018/03/14
| 644 | 2,476 |
<issue_start>username_0: I have a Jenkinsfile instance using ansible-playbook to deploy webmachine.
I need to specified ansible-playbook parameters more than one at once.
I got
>
> WorkflowScript: 25: Multiple occurrences of the parameters section
>
>
>
my jenkinsfile like this,
```
pipeline {
agent none
stages {
stage('docker-compose up') {
input {
message "Should we continue?"
ok "Yes, do it!"
parameters {
string(name: 'KIBANA_TAG', defaultValue: '', description: 'input tag for ansible command.')
}
parameters {
string(name: 'FLUENT_TAG', defaultValue: '', description: 'input tag for ansible command.')
}
parameters {
string(name: 'ES_TAG', defaultValue: '', description: 'input tag for ansible command.')
}
parameters {
string(name: 'HOST', defaultValue: '', description: 'input tag for ansible command.')
}
}
steps {
sh "rd6-admin@qa ansible-playbook /tmp/qa/docker-compose-up.yml -e fluent_tag=${params.FLUENT_TAG} -e kibana_tag=${params.KIBANA_TAG} -e es_tag=${params.ES_TAG} -e host=${params.HOST}"
}
}
}
}
```
what part should i fix?<issue_comment>username_1: You can totally use Dataprep to process data stored in BigQuery. It gives you a great way to visualize how your dataset looks, and interactively define transformations.
Now, do you really want to use Dataprep for this? The transformations will be more expensive and slow, as they will run on Dataflow - which is usually more expensive and slow than doing everything within BigQuery (as the question refers to data that's already in BigQuery).
On the other hand, the interactive environment can help you quickly define what you want and run the created recipe periodically.
See more about this on Lak's "How to schedule a BigQuery ETL job with Dataprep".
* <https://medium.com/google-cloud/how-to-schedule-a-bigquery-etl-job-with-dataprep-b1c314883ab9>.
Upvotes: 2 <issue_comment>username_2: According to the [documentation on Dataprep](https://cloud.google.com/dataprep/docs/html/BigQuery-Browser_59736137), you can import BigQuery datasets.
But it might be easier to just to open Dataprep and check the importing options there:
[](https://i.stack.imgur.com/PFXI1.png)
Upvotes: 0
|
2018/03/14
| 729 | 2,555 |
<issue_start>username_0: I would like to use local variables in lambda functions but I get error:
Please see the 1. and 2. points in the code.
```
class Foo {
int d = 0; // 1. It compiles, but ugly, 2. doesnt compile
public void findMax(List> routeLists) {
int d = 0; // 2.Error : Local variable dd defined in an enclosing scope must be final or effectively final
routeLists.forEach(e-> {
e.forEach(ee -> {
d+=ee.getDistance();
});
});
... doing some other operation with d
}
}
```
How can I use them whitout setting them as global variables ?<issue_comment>username_1: You can't use an int as variable because **it must be final** to be used in a stream.
But You can create a class wrapping the int.
Then declare the variable holding this class as final.
Changing the content of the inner int variable.
```
public void findMax(List> routeLists) {
final IntWrapper dWrapper = new IntWrapper();
routeLists.forEach(e-> {
e.forEach(ee -> {
dWrapper.value += ee.getDistance();
});
});
int d = dWrapper.value;
... doing some other operation with d
}
public class IntWrapper {
public int value;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: `forEach` is the wrong tool for the job.
```
int d =
routeLists.stream() // Makes a Stream>
.flatMap(Collection::stream) // Makes a Stream
.mapToInt(Route::getDistance) // Makes an IntStream of distances
.sum();
```
Or just use nested for loops:
```
int d = 0;
for (List rs : routeLists) {
for (Route r : rs) {
d += r.getDistance();
}
}
```
Upvotes: 3 <issue_comment>username_3: Having side effects is discouraged (or even forbidden?) in the functions used in a stream.
A better way would be one of
```
routeLists.stream()
.flatMapToInt(innerList -> innerList.stream()
.mapToInt(Route::getDistance))
.sum()
```
or
```
routeLists.stream()
.mapToInt(innerList -> innerList.stream()
.mapToInt(Route::getDistance).sum())
.sum()
```
The first will, for each sublist, create a stream of distances. All these streams will become flattened and summed at once.
The second will create the sum of each sublist and then add all those sums together again.
They should be equivalent, but I am not sure if the one or other is better in terms of performance (i. e., if flattening the streams is more expensive than summing).
A third alternative of flattening the lists and then getting and summing the distances is covered by [username_2's answer](https://stackoverflow.com/a/49273486/296974).
Upvotes: 1
|
2018/03/14
| 8,964 | 30,877 |
<issue_start>username_0: I have a list of locations that i want to implement as a dropdown list in Flutter. Im pretty new to the language. Here's what i have done.
```
new DropdownButton(
value: _selectedLocation,
onChanged: (String newValue) {
setState(() {
_selectedLocation = newValue;
});
},
items: _locations.map((String location) {
return new DropdownMenuItem(
child: new Text(location),
);
}).toList(),
```
This is my list of items:
```
List \_locations = ['A', 'B', 'C', 'D'];
```
And I am getting the following error.
```
Another exception was thrown: 'package:flutter/src/material/dropdown.dart': Failed assertion: line 468 pos 15: 'value == null || items.where((DropdownMenuItem item) => item.value == value).length == 1': is not true.
```
I assume the value of `_selectedLocation` is getting null. But i am initialising it like so.
`String _selectedLocation = 'Please choose a location';`<issue_comment>username_1: Try this
```
DropdownButton(
items: ['A', 'B', 'C', 'D'].map((String value) {
return DropdownMenuItem(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (\_) {},
)
```
Upvotes: 9 [selected_answer]<issue_comment>username_2: You need to add `value: location` in your code to work it. Check [this](https://docs.flutter.io/flutter/material/DropdownMenuItem-class.html) out.
```
items: _locations.map((String location) {
return new DropdownMenuItem(
child: new Text(location),
value: location,
);
}).toList(),
```
Upvotes: 3 <issue_comment>username_3: you have to take this into account (from DropdownButton docs):
>
> "The items must have distinct values and if value isn't null it must
> be among them."
>
>
>
So basically you have this list of strings
```
List \_locations = ['A', 'B', 'C', 'D'];
```
And your value in Dropdown value property is initialised like this:
```
String _selectedLocation = 'Please choose a location';
```
Just try with this list:
```
List \_locations = ['Please choose a location', 'A', 'B', 'C', 'D'];
```
That should work :)
Also check out the "hint" property if you don't want to add a String like that (out of the list context), you could go with something like this:
```
DropdownButton(
items: locations.map((String val) {
return new DropdownMenuItem(
value: val,
child: new Text(val),
);
}).toList(),
hint: Text("Please choose a location"),
onChanged: (newVal) {
\_selectedLocation = newVal;
this.setState(() {});
});
```
Upvotes: 4 <issue_comment>username_4: place the value inside the items.then it will work,
```
new DropdownButton(
items:\_dropitems.map((String val){
return DropdownMenuItem(
value: val,
child: new Text(val),
);
}).toList(),
hint:Text(\_SelectdType),
onChanged:(String val){
\_SelectdType= val;
setState(() {});
})
```
Upvotes: 3 <issue_comment>username_5: I was facing a similar issue with the DropDownButton when i was trying to display a dynamic list of strings in the dropdown. I ended up creating a plugin : [flutter\_search\_panel](https://pub.dartlang.org/packages/flutter_search_panel). Not a dropdown plugin, but you can display the items with the search functionality.
Use the following code for using the widget :
```
FlutterSearchPanel(
padding: EdgeInsets.all(10.0),
selected: 'a',
title: 'Demo Search Page',
data: ['This', 'is', 'a', 'test', 'array'],
icon: new Icon(Icons.label, color: Colors.black),
color: Colors.white,
textStyle: new TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0, decorationStyle: TextDecorationStyle.dotted),
onChanged: (value) {
print(value);
},
),
```
Upvotes: 1 <issue_comment>username_6: **Let say we are creating a drop down list of currency:**
```
List _currency = ["INR", "USD", "SGD", "EUR", "PND"];
List> \_dropDownMenuCurrencyItems;
String \_currentCurrency;
List> getDropDownMenuCurrencyItems() {
List> items = new List();
for (String currency in \_currency) {
items.add(
new DropdownMenuItem(value: currency, child: new Text(currency)));
}
return items;
}
void changedDropDownItem(String selectedCurrency) {
setState(() {
\_currentCurrency = selectedCurrency;
});
}
```
**Add below code in body part:**
```
new Row(children: [
new Text("Currency: "),
new Container(
padding: new EdgeInsets.all(16.0),
),
new DropdownButton(
value: \_currentCurrency,
items: \_dropDownMenuCurrencyItems,
onChanged: changedDropDownItem,
)
])
```
Upvotes: 2 <issue_comment>username_7: The error you are getting is due to ask for a property of a null object. Your item must be null so when asking for its value to be compared you are getting that error. Check that you are getting data or your list is a list of objects and not simple strings.
Upvotes: 0 <issue_comment>username_8: When I ran into this issue of wanting a less generic DropdownStringButton, I just created it:
**dropdown\_string\_button.dart**
```
import 'package:flutter/material.dart';
// Subclass of DropdownButton based on String only values.
// Yes, I know Flutter discourages subclassing, but this seems to be
// a reasonable exception where a commonly used specialization can be
// made more easily usable.
//
// Usage:
// DropdownStringButton(items: ['A', 'B', 'C'], value: 'A', onChanged: (string) {})
//
class DropdownStringButton extends DropdownButton {
DropdownStringButton({
Key key, @required List items, value, hint, disabledHint,
@required onChanged, elevation = 8, style, iconSize = 24.0, isDense = false,
isExpanded = false, }) :
assert(items == null || value == null || items.where((String item) => item == value).length == 1),
super(
key: key,
items: items.map((String item) {
return DropdownMenuItem(child: Text(item), value: item);
}).toList(),
value: value, hint: hint, disabledHint: disabledHint, onChanged: onChanged,
elevation: elevation, style: style, iconSize: iconSize, isDense: isDense,
isExpanded: isExpanded,
);
}
```
Upvotes: 0 <issue_comment>username_9: For the solution, scroll to the end of the answer.
First of all, let's investigate what the error says (I have cited the error that's thrown with Flutter 1.2, but the idea is the same):
>
> Failed assertion: line 560 pos 15: 'items == null || items.isEmpty || value == null || items.where((DropdownMenuItem item) => item.value == value).length == 1': is not true.
>
>
>
There are four `or` conditions. At least one of them must be fulfilled:
* Items (a list of `DropdownMenuItem` widgets) were provided. This eliminates `items == null`.
* Non-empty list was provided. This eliminates `items.isEmpty`.
* A value (`_selectedLocation`) was also given. This eliminates `value == null`. Note that this is `DropdownButton`'s value, not `DropdownMenuItem`'s value.
Hence only the last check is left. It boils down to something like:
>
> Iterate through `DropdownMenuItem`'s. Find all that have a `value` that's equal to `_selectedLocation`. Then, check how many items matching it were found. There must be exactly one widget that has this value. Otherwise, throw an error.
>
>
>
The way code is presented, there is not a `DropdownMenuItem` widget that has a value of `_selectedLocation`. Instead, all the widgets have their value set to `null`. Since `null != _selectedLocation`, last condition fails. Verify this by setting `_selectedLocation` to `null` - the app should run.
To fix the issue, we first need to set a value on each `DropdownMenuItem` (so that something could be passed to `onChanged` callback):
```
return DropdownMenuItem(
child: new Text(location),
value: location,
);
```
The app will still fail. This is because your list still does not contain `_selectedLocation`'s value. You can make the app work in two ways:
* ***Option 1***. Add another widget that has the value (to satisfy `items.where((DropdownMenuItem item) => item.value == value).length == 1`). Might be useful if you want to let the user re-select `Please choose a location` option.
* ***Option 2***. Pass something to `hint:` paremter and set `selectedLocation` to `null` (to satisfy `value == null` condition). Useful if you don't want `Please choose a location` to remain an option.
See the code below that shows how to do it:
```
import 'package:flutter/material.dart';
void main() {
runApp(Example());
}
class Example extends StatefulWidget {
@override
State createState() => \_ExampleState();
}
class \_ExampleState extends State {
// List \_locations = ['Please choose a location', 'A', 'B', 'C', 'D']; // Option 1
// String \_selectedLocation = 'Please choose a location'; // Option 1
List \_locations = ['A', 'B', 'C', 'D']; // Option 2
String \_selectedLocation; // Option 2
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: DropdownButton(
hint: Text('Please choose a location'), // Not necessary for Option 1
value: \_selectedLocation,
onChanged: (newValue) {
setState(() {
\_selectedLocation = newValue;
});
},
items: \_locations.map((location) {
return DropdownMenuItem(
child: new Text(location),
value: location,
);
}).toList(),
),
),
),
);
}
}
```
Upvotes: 7 <issue_comment>username_10: You can use `DropDownButton` class in order to create drop down list :
```
...
...
String dropdownValue = 'One';
...
...
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: DropdownButton(
value: dropdownValue,
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: ['One', 'Two', 'Free', 'Four']
.map>((String value) {
return DropdownMenuItem(
value: value,
child: Text(value),
);
}).toList(),
),
),
);
...
...
```
please refer to this [flutter documentation](https://api.flutter.dev/flutter/material/DropdownButton-class.html)
Upvotes: 3 <issue_comment>username_11: It had happened to me when I replace the default value with a new dynamic value. But, somehow your code may be dependent on that default value. So try keeping a constant with default value stored somewhere to fallback.
```
const defVal = 'abcd';
String dynVal = defVal;
// dropdown list whose value is dynVal that keeps changing with onchanged
// when rebuilding or setState((){})
dynVal = defVal;
// rebuilding here...
```
Upvotes: 1 <issue_comment>username_12: Change
```
List \_locations = ['A', 'B', 'C', 'D'];
```
To
```
List \_locations = [\_selectedLocation, 'A', 'B', 'C', 'D'];
```
\_selectedLocation needs to be part of your item List;
Upvotes: 2 <issue_comment>username_13: For anyone interested to implement a `DropDown` of custom `class` you can follow the bellow steps.
1. Suppose you have a class called `Language` with the following code and a `static` method which returns a `List`
```
class Language {
final int id;
final String name;
final String languageCode;
const Language(this.id, this.name, this.languageCode);
}
const List getLanguages = [
Language(1, 'English', 'en'),
Language(2, 'فارسی', 'fa'),
Language(3, 'پشتو', 'ps'),
];
```
2. Anywhere you want to implement a `DropDown` you can `import` the `Language` class first use it as follow
```
DropdownButton(
underline: SizedBox(),
icon: Icon(
Icons.language,
color: Colors.white,
),
items: getLanguages.map((Language lang) {
return new DropdownMenuItem(
value: lang.languageCode,
child: new Text(lang.name),
);
}).toList(),
onChanged: (val) {
print(val);
},
)
```
Upvotes: 4 <issue_comment>username_14: Use `StatefulWidget` and `setState` to update dropdown.
```
String _dropDownValue;
@override
Widget build(BuildContext context) {
return DropdownButton(
hint: _dropDownValue == null
? Text('Dropdown')
: Text(
_dropDownValue,
style: TextStyle(color: Colors.blue),
),
isExpanded: true,
iconSize: 30.0,
style: TextStyle(color: Colors.blue),
items: ['One', 'Two', 'Three'].map(
(val) {
return DropdownMenuItem(
value: val,
child: Text(val),
);
},
).toList(),
onChanged: (val) {
setState(
() {
\_dropDownValue = val;
},
);
},
);
}
```
initial state of dropdown:
[](https://i.stack.imgur.com/jLTNGm.png)
Open dropdown and select value:
[](https://i.stack.imgur.com/OT9aZm.png)
Reflect selected value to dropdown:
[](https://i.stack.imgur.com/Oahvem.png)
Upvotes: 5 <issue_comment>username_15: Use this code.
```
class PlayerPreferences extends StatefulWidget {
final int numPlayers;
PlayerPreferences({this.numPlayers});
@override
_PlayerPreferencesState createState() => _PlayerPreferencesState();
}
class _PlayerPreferencesState extends State {
int dropDownValue = 0;
@override
Widget build(BuildContext context) {
return Container(
child: DropdownButton(
value: dropDownValue,
onChanged: (int newVal){
setState(() {
dropDownValue = newVal;
});
},
items: [
DropdownMenuItem(
value: 0,
child: Text('Yellow'),
),
DropdownMenuItem(
value: 1,
child: Text('Red'),
),
DropdownMenuItem(
value: 2,
child: Text('Blue'),
),
DropdownMenuItem(
value: 3,
child: Text('Green'),
),
],
),
);
}
}
```
and in the main body we call as
```
class ModeSelection extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
child: PlayerPreferences(),
) ,
),
);
}
}
```
Upvotes: 0 <issue_comment>username_16: If you don't want the `Drop list` to show up like a popup. You can customize it this way just like me (it will show up as if on the same flat, see image below):
[](https://i.stack.imgur.com/I5Mps.png)
After expand:
[](https://i.stack.imgur.com/U1BuD.png)
Please follow the steps below:
First, create a dart file named `drop_list_model.dart`:
```
import 'package:flutter/material.dart';
class DropListModel {
DropListModel(this.listOptionItems);
final List listOptionItems;
}
class OptionItem {
final String id;
final String title;
OptionItem({@required this.id, @required this.title});
}
```
Next, create file `file select_drop_list.dart`:
```
import 'package:flutter/material.dart';
import 'package:time_keeping/model/drop_list_model.dart';
import 'package:time_keeping/widgets/src/core_internal.dart';
class SelectDropList extends StatefulWidget {
final OptionItem itemSelected;
final DropListModel dropListModel;
final Function(OptionItem optionItem) onOptionSelected;
SelectDropList(this.itemSelected, this.dropListModel, this.onOptionSelected);
@override
_SelectDropListState createState() => _SelectDropListState(itemSelected, dropListModel);
}
class _SelectDropListState extends State with SingleTickerProviderStateMixin {
OptionItem optionItemSelected;
final DropListModel dropListModel;
AnimationController expandController;
Animation animation;
bool isShow = false;
\_SelectDropListState(this.optionItemSelected, this.dropListModel);
@override
void initState() {
super.initState();
expandController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 350)
);
animation = CurvedAnimation(
parent: expandController,
curve: Curves.fastOutSlowIn,
);
\_runExpandCheck();
}
void \_runExpandCheck() {
if(isShow) {
expandController.forward();
} else {
expandController.reverse();
}
}
@override
void dispose() {
expandController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Container(
padding: const EdgeInsets.symmetric(
horizontal: 15, vertical: 17),
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white,
boxShadow: [
BoxShadow(
blurRadius: 10,
color: Colors.black26,
offset: Offset(0, 2))
],
),
child: new Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(Icons.card\_travel, color: Color(0xFF307DF1),),
SizedBox(width: 10,),
Expanded(
child: GestureDetector(
onTap: () {
this.isShow = !this.isShow;
\_runExpandCheck();
setState(() {
});
},
child: Text(optionItemSelected.title, style: TextStyle(
color: Color(0xFF307DF1),
fontSize: 16),),
)
),
Align(
alignment: Alignment(1, 0),
child: Icon(
isShow ? Icons.arrow\_drop\_down : Icons.arrow\_right,
color: Color(0xFF307DF1),
size: 15,
),
),
],
),
),
SizeTransition(
axisAlignment: 1.0,
sizeFactor: animation,
child: Container(
margin: const EdgeInsets.only(bottom: 10),
padding: const EdgeInsets.only(bottom: 10),
decoration: new BoxDecoration(
borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)),
color: Colors.white,
boxShadow: [
BoxShadow(
blurRadius: 4,
color: Colors.black26,
offset: Offset(0, 4))
],
),
child: \_buildDropListOptions(dropListModel.listOptionItems, context)
)
),
// Divider(color: Colors.grey.shade300, height: 1,)
],
),
);
}
Column \_buildDropListOptions(List items, BuildContext context) {
return Column(
children: items.map((item) => \_buildSubMenu(item, context)).toList(),
);
}
Widget \_buildSubMenu(OptionItem item, BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 26.0, top: 5, bottom: 5),
child: GestureDetector(
child: Row(
children: [
Expanded(
flex: 1,
child: Container(
padding: const EdgeInsets.only(top: 20),
decoration: BoxDecoration(
border: Border(top: BorderSide(color: Colors.grey[200], width: 1)),
),
child: Text(item.title,
style: TextStyle(
color: Color(0xFF307DF1),
fontWeight: FontWeight.w400,
fontSize: 14),
maxLines: 3,
textAlign: TextAlign.start,
overflow: TextOverflow.ellipsis),
),
),
],
),
onTap: () {
this.optionItemSelected = item;
isShow = false;
expandController.reverse();
widget.onOptionSelected(item);
},
),
);
}
}
```
Initialize value:
```
DropListModel dropListModel = DropListModel([OptionItem(id: "1", title: "Option 1"), OptionItem(id: "2", title: "Option 2")]);
OptionItem optionItemSelected = OptionItem(id: null, title: "Chọn quyền truy cập");
```
Finally use it:
```
SelectDropList(
this.optionItemSelected,
this.dropListModel,
(optionItem){
optionItemSelected = optionItem;
setState(() {
});
},
)
```
Upvotes: 5 <issue_comment>username_17: Make your custom Widget:
```
import 'package:flutter/material.dart';
/// Usage:
/// CustomDropdown(
// items: ['A', 'B', 'C'],
// onChanged: (val) => \_selectedValue = val,
// center: true,
// ),
/// --> Remember: f.toString() at line 105 is @override String toString() in your class
// @override
// String toString() {
// return name;
// }
class CustomDropdown extends StatefulWidget {
CustomDropdown({
Key key,
@required this.items,
@required this.onChanged,
this.onInit,
this.padding = const EdgeInsets.only(top: 10.0),
this.height = 40,
this.center = false,
this.itemText,
}) : super(key: key);
/// list item
List items;
/// onChanged
void Function(T value) onChanged;
/// onInit
void Function(T value) onInit;
///padding
EdgeInsetsGeometry padding;
/// container height
double height;
/// center
bool center;
String Function(String text) itemText;
@override
\_CustomDropdownState createState() => \_CustomDropdownState();
}
class \_CustomDropdownState extends State> {
/// current selected value
T \_selectedValue;
@override
void initState() {
super.initState();
\_initValue();
}
@override
Widget build(BuildContext context) {
return \_buildBody();
}
/// set default selected value when init
\_initValue() {
\_selectedValue = widget.items[0];
if (widget.onInit != null) widget.onInit(\_selectedValue);
}
\_buildBody() {
Color borderLine = Color(0xffc0c0c0);
return Padding(
padding: widget.padding,
child: Row(
mainAxisAlignment: (widget.center)
? MainAxisAlignment.center
: MainAxisAlignment.start,
children: [
new Container(
height: widget.height,
padding: EdgeInsets.only(left: 10.0),
decoration: ShapeDecoration(
color: Colors.white,
shape: RoundedRectangleBorder(
side: BorderSide(
width: 0.8, style: BorderStyle.solid, color: borderLine),
borderRadius: BorderRadius.all(Radius.circular(5.0)),
),
),
child: new DropdownButtonHideUnderline(
child: new DropdownButton(
value: \_selectedValue,
onChanged: (T newValue) {
setState(() {
\_selectedValue = newValue;
widget.onChanged(newValue);
});
},
items: widget.items.map((T f) {
return new DropdownMenuItem(
value: f,
child: new Text(
(widget.itemText != null)
? widget.itemText(f.toString())
: f.toString(),
style: new TextStyle(color: Colors.black),
),
);
}).toList(),
),
),
),
],
),
);
}
}
```
* After that, simple call:
```
CustomDropdown(
items: ['A', 'B', 'C'],
onChanged: (val) => \_selectedValue = val,
center: true,
)
```
* Or with your class:
class Student {
int id;
String name;
A(this.id,this.name);
//remember override
@override
String toString() {
return name;
}
}
And call:
```
CustomDropdown(
items: studentList,
onChanged: (val) => \_selectedValue = val,
center: true,
),
```
Upvotes: 2 <issue_comment>username_18: This is the code which I found most useful.
It gives you everything you need. (ctrl+c , ctrl+v will work)
```
List location = ['One', 'Two', 'Three', 'Four'];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Fuel Entry')),
body: Padding(
padding: const EdgeInsets.all(15.0),
child: Center(
child: Column(
children: [
DropdownButton(
hint: Text('Select a vehicle '),
value: dropdownValue,
icon: const Icon(Icons.arrow\_downward),
iconSize: 24,
elevation: 16,
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue!;
});
},
items: location.map>((String value) {
return DropdownMenuItem(
value: value,
child: Text(value),
);
}).toList(),
)
],
),
),
),
);
```
Upvotes: 2 <issue_comment>username_19: it is very simple
```
DropdownButton(
isExpanded: true,
value: selectedLocation,
icon: const Icon(Icons.arrow\_circle\_down),
iconSize: 20,
elevation: 16,
underline: Container(),
onChanged: (String newValue) {
setState(() {
selectedLocation = newValue;
});
},
items: List.generate(
\_locations.length,
(index) => DropdownMenuItem(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
\_locations[index]
),
),
value: \_locations[index],
),
),
),
),
```
**Complete Code Example Given Below[](https://i.stack.imgur.com/2u3j0.png)**
```html
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
var \_locations = ['A', 'B', 'C', 'D'];
String selectedLocation = 'A';
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: DropdownButton(
isExpanded: true,
value: selectedLocation,
icon: const Icon(Icons.arrow\_circle\_down),
iconSize: 20,
elevation: 16,
underline: Container(),
onChanged: (String newValue) {
setState(() {
selectedLocation = newValue;
});
},
items: List.generate(
\_locations.length,
(index) => DropdownMenuItem(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
\_locations[index]
),
),
value: \_locations[index],
),
),
),
),
);
}
}
```
Upvotes: 0 <issue_comment>username_20: This one has the hint text that shows up before selection
```
DropdownButton(
focusColor: Colors.white,
value: \_chosenValue,
//elevation: 5,
style: TextStyle(color: Colors.white),
iconEnabledColor: Colors.black,
items:classes.map>((String value) {
return DropdownMenuItem(
value: value,
child: Text(
value,
style: TextStyle(color: Colors.black),
),
);
}).toList(),
hint: Text(
"All Classes",
style: TextStyle(
color: Colors.black, fontSize: 14, fontWeight: FontWeight.w500),
),
onChanged: (String value) {
setState(() {
\_chosenValue = value;
});
},
);
```
Upvotes: 2 <issue_comment>username_21: ```
DropdownButton(
value: 6, //selected
icon: Icon(Icons.arrow\_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Theme.of(context).accentColor),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (int? newValue) {},
items: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.map>((int value) {
return DropdownMenuItem(
value: value,
child: Text(value.toString()),
);
}).toList(),
)
```
Upvotes: 2 <issue_comment>username_22: You can use like this
```
class DropDownMenu extends StatefulWidget {
const DropDownMenu({Key? key}) : super(key: key);
@override
State createState() => \_DropDownMenuState();
}
class \_DropDownMenuState extends State {
String? dropDownIndex;
var dropDownList = ["Delete","Change","Remove","Save"];
@override
Widget build(BuildContext context) {
return DropdownButton(
icon: const Icon(Icons.expand\_circle\_down),
dropdownColor: Colors.yellow,
hint: const Text("select"),
enableFeedback: true,
iconSize: 16,
borderRadius: BorderRadius.circular(16),
style: const TextStyle(
color: Colors.green,
decoration: TextDecoration.underline,
decorationColor: Colors.yellow,
),
items: dropDownList.map((value) => DropdownMenuItem(value: value,child:
Text(value),)).toList(),
onChanged: (String? index) {
setState(() {
dropDownIndex = index;
});
},
value: dropDownIndex,
);
}
}
```
Upvotes: 0 <issue_comment>username_23: ```
import 'package:flutter/material.dart';
import 'package:pax_pos/resource/values/app_colors.dart';
import 'package:pax_pos/utils/widget_helper.dart';
class DropdownWidget extends StatefulWidget {
const DropdownWidget(
{Key? key, required this.onTapItem, required this.itemList})
: super(key: key);
final Function onTapItem;
final List itemList;
@override
State createState() => \_DropdownWidgetState();
}
class \_DropdownWidgetState extends State
with TickerProviderStateMixin {
String header = "Day";
final LayerLink \_layerLink = LayerLink();
late OverlayEntry \_overlayEntry;
bool \_isOpen = false;
GlobalKey keyDropdown = GlobalKey();
//Controller Animation
late AnimationController \_animationController;
late Animation \_expandAnimation;
//late AnimationController \_controller;
late Animation \_iconTurns;
static final Animatable \_iconTurnTween =
Tween(begin: 0.0, end: 0.5)
.chain(CurveTween(curve: Curves.fastOutSlowIn));
@override
void dispose() {
super.dispose();
\_animationController.dispose();
}
@override
void initState() {
super.initState();
\_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 200),
);
\_expandAnimation = CurvedAnimation(
parent: \_animationController,
curve: Curves.easeInOut,
);
\_iconTurns = \_animationController.drive(\_iconTurnTween);
}
@override
Widget build(BuildContext context) {
return CompositedTransformTarget(
link: \_layerLink,
child: InkWell(
onTap: \_toggleDropdown,
child: Container(
key: keyDropdown,
height: 50,
padding: const EdgeInsets.symmetric(horizontal: 15),
decoration: BoxDecoration(
border: Border.all(width: 1.5, color: AppColors.PRIMARY\_COLOR),
borderRadius: BorderRadius.circular(10)),
child: Row(
children: [
Center(
child: Text(
header,
style: const TextStyle(
//fontWeight: FontWeight.w600,
fontSize: 16,
color: AppColors.PRIMARY\_COLOR),
)),
const SizedBox(
width: 15,
),
RotationTransition(
turns: \_iconTurns,
child: const SizedBox(
width: 20,
height: 20,
child: Icon(
Icons.expand\_more,
color: AppColors.PRIMARY\_COLOR,
)),
),
],
)), //Define your child here
),
);
}
OverlayEntry \_createOverlayEntry(Size size) {
return OverlayEntry(
builder: (context) => GestureDetector(
onTap: () => \_toggleDropdown(close: true),
behavior: HitTestBehavior.translucent,
// full screen container to register taps anywhere and close drop down
child: SizedBox(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: [
Positioned(
left: 100,
top: 100.0,
width: size.width,
child: CompositedTransformFollower(
//use offset to control where your dropdown appears
offset: Offset(0, size.height + 8),
link: \_layerLink,
showWhenUnlinked: false,
child: Material(
elevation: 2,
borderRadius: BorderRadius.circular(6),
borderOnForeground: true,
color: Colors.white,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(6),
boxShadow: [
BoxShadow(
color: AppColors.BACKGROUND\_COLOR\_FILTER\_STATUS
.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 1,
offset: const Offset(
0, 1) // changes position of shadow
),
],
),
child: SizeTransition(
axisAlignment: 1,
sizeFactor: \_expandAnimation,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
...WidgetHelper.map(widget.itemList,
(int index, value) {
String title = value;
return Material(
color: Colors.transparent,
borderRadius: BorderRadius.circular(5),
child: InkWell(
onTap: () {
widget.onTapItem(title);
\_toggleDropdown(close: true);
},
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 15, vertical: 10),
child: Text(title)),
),
);
}),
//These are the options that appear in the dropdown
],
),
),
),
),
),
),
],
),
),
),
);
}
void \_toggleDropdown({
bool close = false,
}) async {
if (\_isOpen || close) {
\_animationController.reverse().then((value) {`enter code here`
\_overlayEntry.remove();
if (mounted) {
setState(() {
\_isOpen = false;
});
}
});
} else {
final overlayName = Overlay.of(keyDropdown.currentContext!)!;
final renderBox =
keyDropdown.currentContext!.findRenderObject() as RenderBox;
final size = renderBox.size;
\_overlayEntry = \_createOverlayEntry(size);
//Overlay.of(context)!.insert(\_overlayEntry);
overlayName.insert(\_overlayEntry);
setState(() => \_isOpen = true);
\_animationController.forward();
}
}
}
```
Upvotes: 0
|
2018/03/14
| 238 | 932 |
<issue_start>username_0: I have some external website which i am loading using iFrame. And i am trying to implement fake click inside the iframe.
Here is my code
```
window.load(function(){
$('#book-iframe').contents().find('.Home').trigger("click");
});
```
also if try `$('#book-iframe').contents().find('.Home').trigger("click");` code on browser console it works very well.
Any suggestions<issue_comment>username_1: An iframe is independent of the frame that is displaying it.
To apply changes (styles / content / etc.) to the iFrame page you need to edit that page.
Upvotes: 0 <issue_comment>username_2: You can modify iframes only if they are from the **same parent domain.**
With external website you could do that only if:
1) You have **direct access** to the source code
2) You have found security vulnerability an [XSS (Cross Site Scripting)](https://en.wikipedia.org/wiki/Cross-site_scripting)
Upvotes: 1
|
2018/03/14
| 190 | 763 |
<issue_start>username_0: I have used CSV file in Jmeter script. But Jmeter is Not reading data from CSV File. Now I want if data is Not read from CSV file then it will pick Default Value. How to do this ? Any Function for doing this ?<issue_comment>username_1: An iframe is independent of the frame that is displaying it.
To apply changes (styles / content / etc.) to the iFrame page you need to edit that page.
Upvotes: 0 <issue_comment>username_2: You can modify iframes only if they are from the **same parent domain.**
With external website you could do that only if:
1) You have **direct access** to the source code
2) You have found security vulnerability an [XSS (Cross Site Scripting)](https://en.wikipedia.org/wiki/Cross-site_scripting)
Upvotes: 1
|
2018/03/14
| 685 | 2,414 |
<issue_start>username_0: I call http post method from angular4 component to web api. When I print those values return from web api on console it prints empty values. I checked the request using postman also. It also didn't work.
Http post call from component file.
```
EditValue(event, name, id) {
const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
const options = new RequestOptions({ headers: headers });
let body = { "name" : name, "id": id }
this.http_.post('http://localhost:12412/api/employee?', body, options)
.subscribe((data) => {console.log(data)});
}
```
Http post method in web api.
```
[HttpPost]
public string postemp(Model model)
{
return "name:" +model.name + " , " + "id: " + model.id;
}
public class Model
{
public int id { get; set; }
public string name { get; set; }
}
```
When I check the name and id from Editvalue function those values are passing. I tried solutions given by [Angular4 http post method does not pass data to web api](https://stackoverflow.com/questions/49144824/angular4-http-post-method-does-not-pass-data-to-web-api) also. But issue didn't fix.How to check those posted data is passing to web api post method?
I attached the response result I got below.
[](https://i.stack.imgur.com/htPLz.png)<issue_comment>username_1: try `JSON.stringify(body)` before you send to the webapi once
Upvotes: 0 <issue_comment>username_2: You are sending the info in the body in JSON format. But in your header you set `application/x-www-form-urlencoded` in which the values are encoded in key-value tuples separated by '&', with a '=' between the key and the value. So, to be able to send the data in the JSON format you need to change the `Content-Type` in your header to `application/json`.
Upvotes: 1 <issue_comment>username_3: Just use the `[FromBody]` attribute to your API method parameter like below.
```
[HttpPost]
public string postemp([FromBody]Model model)
{
return "name:" +model.name + " , " + "id: " + model.id;
}
```
Upvotes: 1 <issue_comment>username_4: Since the content type I used here is 'application/x-www-form-urlencoded', body should not be passed using JSON object. Body I passed here should be in query string like below.
```html
let body="id="+id+"&name="+name;
```
It worked for me.
Upvotes: 0
|
2018/03/14
| 429 | 1,904 |
<issue_start>username_0: I am facing a problem with a specific translation issue on iOS.
The app I am currently working on gets all the texts it displays from a web service. I have been able to implement this everywhere with one single exception:
I have not yet found a way to programmatically alter texts from info.plist which get used from the system in code I cannot control. The one I need to deal with is "Privacy - Camera Usage Description". So far any documentation I have found tells me to add localized text versions for info.plist - but in this particular case this won't help me, because different customers may specify different texts for the same language, and I sometimes do not even know what language the texts are in, so I cannot solely rely on static data in the app to select the proper text version.
Is there any way to set such a text programmatically, or if that isn't possible to catch the alert displaying it and replace it with one of my own?<issue_comment>username_1: No, It's not possible, we can not change Info.plist runtime. But if I was there in place of you I will do one thing as a solution. **Display** a custom alertview with your specified text from the api. Which will ask that "We will use your camera". If user says "Ok" than display the system's alertview for the permission with static localized string. It needs 2 time interaction but it can guide user thoroughly.
Upvotes: 2 [selected_answer]<issue_comment>username_2: You can localize `info.plist` file itself.
from project, go to your `info.plist` file and open Utilities tab and hit on Localization.
For different Localizations, use different Strings on specified keys.
### Note
I Haven't tried it myself, just checked to see if it can be localized. and one more thing, using this way, Application will use Device's Localization (You can't use libraries to swizzle String table your app uses)
Upvotes: 0
|
2018/03/14
| 725 | 2,997 |
<issue_start>username_0: I am new to the React Native integration in Android. I am creating a chat application and for that need to pass the UserId and another User information in my React Native component. How can I pass that from Android Native? I searched but I haven't found any successful lead. I tried doing it with SharedPreference, But didn't have any idea how to extract the sharedpreference holder in the React native. Are there any other way that I can extract this information?
I have created ReactRootView in the ReactActivity and integrated ReactInstanceManager in it.
As per Geng's and Cool7's answer, I have implemented my Android Kotlin code as given below:
```
val map = Arguments.createMap()
map.putString("user_id", "Value1")
try {
mReactInstanceManager?.currentReactContext
?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
?.emit("userEventMap", map)
} catch (e: Exception) {
Log.d("ChatActivity", "DeviceEventEmitter Caught Exception: " + e.printStackTrace())
}
```
And my React native code to extract it is as below:
```
componentWillMount() {
console.log("UserId Emission");
DeviceEventEmitter.addListener("userEventMap", function() {
console.log("UserId Emission inside");
console.log("UserId :: ", e.user_id);
});
```
}
I have tried Cool7's ditto code also and like above also. But UserId Emission is getting printed but the inside logs are not. The Map is not getting listened in this emitter.
Thanks in advance.<issue_comment>username_1: To send data from android to react native :
From android side emit your event(Notification or Broadcast) in following way:
```
public class MainActivity extends ReactActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WritableMap map = Arguments.createMap();
map.putString("key1", "Value1");
map.putString("key1", "Value1");
try {
getReactInstanceManager().getCurrentReactContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("customEventName", map);
} catch (Exception e){
Log.e("ReactNative", "Caught Exception: " + e.getMessage());
}
}
```
And in react component addEventListner(subscribe) to that event like as:
```
import { DeviceEventEmitter } from 'react-native';
componentWillMount: function() {
DeviceEventEmitter.addListener('customEventName', function(e: Event) {
// handle event.
});
```
}
Also refer
[To send data from android native to react native](https://facebook.github.io/react-native/docs/native-modules-android.html#sending-events-to-javascript)
Upvotes: 3 <issue_comment>username_2: Please refer to <https://facebook.github.io/react-native/docs/native-modules-android.html>. Basically you need to create and register a module in native code, and call it from react native.
Upvotes: -1
|
2018/03/14
| 349 | 1,164 |
<issue_start>username_0: I want to replace if string is started with `/` until next unique character ... I tried like below , but it replace all occurrences into one only ! I want to replace all occurrence characters ...
```js
var textTitle = "///test///";
var result = textTitle.replace(/^\/{1,}/g, '../');
console.log(result); // wanted => ../../../test///
textTitle = "//test/";
result = textTitle.replace(/^\/{1,}/g, '../');
console.log(result); // wanted => ../../test/
```<issue_comment>username_1: You could try:
```
var textTitle = "///test///";
var result = textTitle.replace(/^\/{1,}/g, (match, key) => {
return match.split('').reduce((res, next) => res += '..' + next, '');
});
console.log(result);
```
```js
var textTitle = "///test///";
var result = textTitle.replace(/^\/{1,}/g, (match, key) => {
return match.split('').reduce((res, next) => res += '..' + next, '');
});
console.log(result);
```
Upvotes: 0 <issue_comment>username_2: Use `y` flag which takes one step on each successful approach on `lastIndex` property:
```js
console.log("///test///".replace(/\//gy, "../"));
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 413 | 1,647 |
<issue_start>username_0: I want to render Local json file by listing it in cards, Im using FlatList View but couldn't get it rendered.
Here is my code Snippet :
```
import React, { Component, View, FlatList } from 'react';
import { Image } from 'react-native';
import {
Container,
Header,
Title,
Content,
Button,
Icon,
Card,
CardItem,
Text,
Thumbnail,
Left,
Body,
Right
} from 'native-base';
import styles from './styles';
const json = require('./fixtures.json');
const logo = require('../../../assets/logo.png');
const cardImage = require('../../../assets/cskvsdd.jpg');
class Fixtures extends Component {
render() {
return (
{
this.props.navigation.goBack()}>
Fixtures
json data
json data
josn data
json data
json data
}
/>
);
}
}
export default Fixtures;
```
I Have overcome many tutorials before asking here. But couldn't figure it out. Apologies if this is too novice.
Kindly help me render json data to cards by refactoring my code.
Thank in advance<issue_comment>username_1: By looking at your code snippet I realized that you are not setting the data anywhere in the code. please pass the array of data into Flatlist.
```
{item.key}}
keyExtractor={(item, index)=> index}
/>
```
`keyExtractor` should be unique .
Upvotes: 2 <issue_comment>username_2: Please check flatlist documentation:
<https://facebook.github.io/react-native/docs/flatlist.html>
Make sure your JSON data is correctly formated and accessed.
Upvotes: 0
|
2018/03/14
| 948 | 3,361 |
<issue_start>username_0: Let's imagine I have this model and I would like to sort them by logical operation `n1 != n2`:
```
class Thing(Model):
n1 = IntegerField()
n2 = IntegerField()
...
def is_different(self):
return self.n1 != self.n2
```
If I sort them by `sorted` built-in function, I found that it does not return a Queryset, but a list:
```
things = Thing.objects.all()
sorted_things = sorted(things, key=lambda x: x.is_different())
```
Now, if I use `annotate`
```
sorted_things = things.annotate(diff=(F('n1') != F('n2'))).order_by('diff')
```
it raises the following error: `AttributeError: 'bool' object has no attribute 'resolve_expression'`.
I found a solution using `extra` queryset:
```
sorted_things = things.extra(select={'diff': 'n1!=n2'}).order_by('diff')
```
but following Django docs (<https://docs.djangoproject.com/en/2.0/ref/models/querysets/#extra>):
>
> Use this method as a last resort
>
>
> This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods. If you do need to use it, please file a ticket using the QuerySet.extra keyword with your use case (please check the list of existing tickets first) so that we can enhance the QuerySet API to allow removing extra(). We are no longer improving or fixing bugs for this method.
>
>
>
Then, what is the optimal way to do it?
Thanks!<issue_comment>username_1: You can work around it using [Func() expressions](https://docs.djangoproject.com/en/dev/ref/models/expressions/#func-expressions).
```
from django.db.models import Func, F
class NotEqual(Func):
arg_joiner = '<>'
arity = 2
function = ''
things = Thing.objects.annotate(diff=NotEqual(F('n1'), F('n2'))).order_by('diff')
```
Upvotes: 2 <issue_comment>username_2: Conditional expressions
=======================
One option for it is to use [conditional expressions](https://docs.djangoproject.com/en/1.8/ref/models/conditional-expressions/). They provide simple way of checking conditions and providing one of values depending on them. In your case it will look like:
```
sorted_things = things.annotate(diff=Case(When(n1=F('n2'), then=True), default=False, output_field=BooleanField())).order_by('diff')
```
Q and ExpressionWrapper
=======================
There is another, a bit hacky way, to achieve that by combining usage of `Q` and `ExpressionWrapper`.
In django, `Q` is intended to be used inside `filter()`, `exclude()`, `Case` etc. but it simply creates condition that apparently can be used anywhere. It has only one drawback: it doesn't define what type is outputting (it's always boolean and django can assume that in every case when `Q` is intended to be used.
But there comes `ExpressionWrapper` that allows you to wrap any expression and define it's final output type. That way we can simply wrap `Q` expression (or more than one `Q` expresisons glued together using `&`, `|` and brackets) and define by hand what type it outputs.
**Be aware that this is undocumented, so this behavior may change in future, but I've checked it using django versions 1.8, 1.11 and 2.0 and it works fine**
Example:
```
sorted_things = things.annotate(diff=ExpressionWrapper(Q(n1=F('n2')), output_field=BooleanField())).order_by('diff')
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 692 | 2,502 |
<issue_start>username_0: i trying to learn php but found an issue.. im using mamp on a windows PC. and when im trying to connect my php with mysql a get this error:SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES).....
in mysql i got the info username and password are 'root', host:localhost port:8889
and this is my code..
```
function connectToDb()
{
try{
return new PDO('mysql:host=localhost; dbname=tutorials','root','root');
}
catch (PDOException $e){
die ($e->getMessage());
}
}
```
any help will be appreciate.... thanks...<issue_comment>username_1: You can work around it using [Func() expressions](https://docs.djangoproject.com/en/dev/ref/models/expressions/#func-expressions).
```
from django.db.models import Func, F
class NotEqual(Func):
arg_joiner = '<>'
arity = 2
function = ''
things = Thing.objects.annotate(diff=NotEqual(F('n1'), F('n2'))).order_by('diff')
```
Upvotes: 2 <issue_comment>username_2: Conditional expressions
=======================
One option for it is to use [conditional expressions](https://docs.djangoproject.com/en/1.8/ref/models/conditional-expressions/). They provide simple way of checking conditions and providing one of values depending on them. In your case it will look like:
```
sorted_things = things.annotate(diff=Case(When(n1=F('n2'), then=True), default=False, output_field=BooleanField())).order_by('diff')
```
Q and ExpressionWrapper
=======================
There is another, a bit hacky way, to achieve that by combining usage of `Q` and `ExpressionWrapper`.
In django, `Q` is intended to be used inside `filter()`, `exclude()`, `Case` etc. but it simply creates condition that apparently can be used anywhere. It has only one drawback: it doesn't define what type is outputting (it's always boolean and django can assume that in every case when `Q` is intended to be used.
But there comes `ExpressionWrapper` that allows you to wrap any expression and define it's final output type. That way we can simply wrap `Q` expression (or more than one `Q` expresisons glued together using `&`, `|` and brackets) and define by hand what type it outputs.
**Be aware that this is undocumented, so this behavior may change in future, but I've checked it using django versions 1.8, 1.11 and 2.0 and it works fine**
Example:
```
sorted_things = things.annotate(diff=ExpressionWrapper(Q(n1=F('n2')), output_field=BooleanField())).order_by('diff')
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 686 | 2,549 |
<issue_start>username_0: We are not using multi-tenancy. When it is disabled most of the tenant related UI gets hidden but in the LinkedAccount page, the user can view the tenancy name(which is Default). We wanted to hide it in the UI. Tried to find a property like `IsMultiTenancyEnabled` but couldn't find(Actually it is in the `IMultiTenancyConfig` but not available to razor page). So, how can hide UI elements if Multitenancy is not enabled?
```
//This is the code we want to hide.
@L("TenancyName")
```
And there is one thing more: What happens if we hide this code anyway? Should we change the model or app service (Yes)?<issue_comment>username_1: You can work around it using [Func() expressions](https://docs.djangoproject.com/en/dev/ref/models/expressions/#func-expressions).
```
from django.db.models import Func, F
class NotEqual(Func):
arg_joiner = '<>'
arity = 2
function = ''
things = Thing.objects.annotate(diff=NotEqual(F('n1'), F('n2'))).order_by('diff')
```
Upvotes: 2 <issue_comment>username_2: Conditional expressions
=======================
One option for it is to use [conditional expressions](https://docs.djangoproject.com/en/1.8/ref/models/conditional-expressions/). They provide simple way of checking conditions and providing one of values depending on them. In your case it will look like:
```
sorted_things = things.annotate(diff=Case(When(n1=F('n2'), then=True), default=False, output_field=BooleanField())).order_by('diff')
```
Q and ExpressionWrapper
=======================
There is another, a bit hacky way, to achieve that by combining usage of `Q` and `ExpressionWrapper`.
In django, `Q` is intended to be used inside `filter()`, `exclude()`, `Case` etc. but it simply creates condition that apparently can be used anywhere. It has only one drawback: it doesn't define what type is outputting (it's always boolean and django can assume that in every case when `Q` is intended to be used.
But there comes `ExpressionWrapper` that allows you to wrap any expression and define it's final output type. That way we can simply wrap `Q` expression (or more than one `Q` expresisons glued together using `&`, `|` and brackets) and define by hand what type it outputs.
**Be aware that this is undocumented, so this behavior may change in future, but I've checked it using django versions 1.8, 1.11 and 2.0 and it works fine**
Example:
```
sorted_things = things.annotate(diff=ExpressionWrapper(Q(n1=F('n2')), output_field=BooleanField())).order_by('diff')
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 922 | 2,924 |
<issue_start>username_0: Php:
```
$json_string = "{
"26":{"blabla":123,"group_id":1,"from":"27.08.2018","to":"02.09.2018"},
"25":{"blabla":124,"group_id":1,"from":"20.08.2018","to":"26.08.2018"},
"24":{"blabla":125,"group_id":1,"from":"20.08.2018","to":"26.08.2018"}
}"
```
my.blade.php template:
```
```
MyComponent.vue:
```
export default {
props: ['records'],
...
mounted: function () {
console.log(this.records);
}
```
Output is:
```
{__ob__: Observer}
24:(...)
25:(...)
26:(...)
```
And when I use v-for, records in my table in wrong order (like in console.log output).
What I am doing wrong?
**EDIT:**
I figured out 1 thing:
When I do json\_encode on collection where indexes are from 0 till x, than json string is: `[{some data}, {some data}]`
But if I do `->get()->keyBy('id')` (laravel) and than json\_encode, json string is:
```
{ "26":{some data}, "25":{some data}, "24":{some data} }
```
Then how I understood, issue is in different outer brackets.<issue_comment>username_1: You can work around it using [Func() expressions](https://docs.djangoproject.com/en/dev/ref/models/expressions/#func-expressions).
```
from django.db.models import Func, F
class NotEqual(Func):
arg_joiner = '<>'
arity = 2
function = ''
things = Thing.objects.annotate(diff=NotEqual(F('n1'), F('n2'))).order_by('diff')
```
Upvotes: 2 <issue_comment>username_2: Conditional expressions
=======================
One option for it is to use [conditional expressions](https://docs.djangoproject.com/en/1.8/ref/models/conditional-expressions/). They provide simple way of checking conditions and providing one of values depending on them. In your case it will look like:
```
sorted_things = things.annotate(diff=Case(When(n1=F('n2'), then=True), default=False, output_field=BooleanField())).order_by('diff')
```
Q and ExpressionWrapper
=======================
There is another, a bit hacky way, to achieve that by combining usage of `Q` and `ExpressionWrapper`.
In django, `Q` is intended to be used inside `filter()`, `exclude()`, `Case` etc. but it simply creates condition that apparently can be used anywhere. It has only one drawback: it doesn't define what type is outputting (it's always boolean and django can assume that in every case when `Q` is intended to be used.
But there comes `ExpressionWrapper` that allows you to wrap any expression and define it's final output type. That way we can simply wrap `Q` expression (or more than one `Q` expresisons glued together using `&`, `|` and brackets) and define by hand what type it outputs.
**Be aware that this is undocumented, so this behavior may change in future, but I've checked it using django versions 1.8, 1.11 and 2.0 and it works fine**
Example:
```
sorted_things = things.annotate(diff=ExpressionWrapper(Q(n1=F('n2')), output_field=BooleanField())).order_by('diff')
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 464 | 1,785 |
<issue_start>username_0: `static_cast()` is the 'C++ way' of writing `void` conversion
In the en.cppreference.com website mentioned as discards the value of the expression. In below link four points on **Explanation** section
<http://en.cppreference.com/w/cpp/language/static_cast>
Where and Why should we use `static_cast()`? give a example..<issue_comment>username_1: This is a way to tell that it is ok for a variable to be unused suppressing corresponding compiler warning. This approach has been deprecated with introduction of `[[maybe_unused]]` attribute in C++17.
Upvotes: 5 [selected_answer]<issue_comment>username_2: The usual purpose of casting to `void` is to “use” the result of a computation. In relatively strict build environments it is common to output warnings, or even errors, when a variable is declared, maybe even written to, but the result is never used. If, in your code, you know you do not need a result somewhere, you can use the `static_cast` method to mark the result as discarded – but the compiler will consider the variable used then and no longer create a warning or error.
An example:
```
#include
int myFunction() \_\_attribute\_\_ ((warn\_unused\_result));
int myFunction()
{
return 42;
}
int main()
{
// warning: ignoring return value of 'int myFunction()',
// declared with attribute warn\_unused\_result [-Wunused-result]
myFunction();
// warning: unused variable 'result' [-Wunused-variable]
auto result = myFunction();
// no warning
auto result2 = myFunction();
static\_cast(result2);
}
```
When compiled with `g++ -std=c++14 -Wall example.cpp`, the first two function calls will create warnings.
As VTT pointed out in his post, from C++17 you have the option of using the `[[maybe_unused]]` attribute instead.
Upvotes: 2
|
2018/03/14
| 299 | 757 |
<issue_start>username_0: I want to count the records that start with 123, i need to count several times with different values, Starting with 123, 789, 567, ... I have those values in the column2
```
- column1 | column2
- 1234567 | 123
- 5489186 | 135
- 1238756 | 548
SELECT column1, LEFT(column1,3) AS prefijo, column2 COUNT(LEFT(column1 = 123))
FROM DDBB.table
```
SOLUTION
```
SELECT LEFT(llamante,3) prefix, COUNT(*) quantity
FROM CDRcolas.`270`
GROUP BY LEFT(llamante,3)
```<issue_comment>username_1: Use `count()` function
```
select count(*) counts
from table
where column1 LIKE '123%'
```
Upvotes: 2 <issue_comment>username_2: Try this:
```
SELECT COUNT(*) `Count`
FROM DDBB.`table`
WHERE SUBSTR(column1,1,3)='123';
```
Upvotes: 0
|
2018/03/14
| 1,121 | 4,133 |
<issue_start>username_0: I am trying to query a cassandra table for every single kafka message.
Below is the code that I have been working on:
```
def main(args: Array[String]) {
val spark = SparkSession
.builder()
.master("local[*]")
.appName("Spark SQL basic example")
.config("spark.cassandra.connection.host", "localhost")
.config("spark.cassandra.connection.port", "9042")
.getOrCreate()
val topicsSet = List("Test").toSet
val kafkaParams = Map[String, Object](
"bootstrap.servers" -> "localhost:9092",
"key.deserializer" -> classOf[StringDeserializer],
"value.deserializer" -> classOf[StringDeserializer],
"group.id" -> "12345",
"auto.offset.reset" -> "latest",
"enable.auto.commit" -> (false: java.lang.Boolean)
)
val messages = KafkaUtils.createDirectStream[String, String](
ssc,
LocationStrategies.PreferConsistent,
ConsumerStrategies.Subscribe[String, String](topicsSet, kafkaParams))
val lines = messages.map(_.value)
val lines_myobjects = lines.map(line =>
new Gson().fromJson(line, classOf[myClass]) // The myClass is a simple case class which extends serializable
//This changes every single message into an object
)
```
Now things get complicated, I cannot get around the point where I can query the cassandra table with relevant to the message from the kafka message. Every single kafka message object has a return method.
I have tried multiple ways to get around this. For instance:
```
val transformed_data = lines_myobjects.map(myobject => {
val forest = spark.read
.format("org.apache.spark.sql.cassandra")
.options(Map( "table" -> "mytable", "keyspace" -> "mydb"))
.load()
.filter("userid='" + myobject.getuserId + "'")
)}
```
I have also tried `ssc.cassandraTable` which gave me no luck.
The main goal is to get all the rows from the database where the userid matches with the userid that comes from the kafka message.
One thing I would like to mention is that even though loading or querying the cassandra database every time is not efficient, the cassandra database changes everytime.<issue_comment>username_1: I would approach this a different way.
The data that is flowing into Cassandra, route it through Kafka (and from Kafka send to the Cassandra with the [Kafka Connect sink](https://github.com/jcustenborder/kafka-connect-cassandra)).
With your data in Kafka, you can then join between your streams of data, whether in Spark, or with Kafka's Streams API, or KSQL.
Both Kafka Streams and KSQL support stream-table joins that you're doing here. You can see it in action with KSQL [here](http://videos.confluent.io/watch/m1LpiDwQo4Vvd4YHWKcszs) and [here](https://www.confluent.io/blog/ksql-in-action-real-time-streaming-etl-from-oracle-transactional-data).
Upvotes: 1 <issue_comment>username_2: You can't do `spark.read` or `ssc.cassandraTable` inside `.map(`. Because it means you would try to create new RDD per each message. It shouldn't work like that.
Please, sider the following options:
1 - If you could ask required data by one/two CQL queries, try to use [CassandraConnector](https://github.com/datastax/spark-cassandra-connector/blob/master/doc/1_connecting.md#connecting-manually-to-cassandra) inside the `.mapPartitions(`. Something like this:
```
import com.datastax.spark.connector._
import com.datastax.spark.connector.cql._
val connector = ...instantiate CassandraConnector onece here
val transformed_data = lines_myobjects.mapPartitions(it => {
connector.withSessionDo { session =>
it.map(myobject => session.execute("CQL QUERY TO GET YOUR DATA HERE", myobject.getuserId)
})
```
2 - Otherwise (if you select by primary/partition key) consider `.joinWithCassandraTable`. Something like this:
```
import com.datastax.spark.connector._
val mytableRDD = sc.cassandraTable("mydb", "mytable")
val transformed_data = lines_myobjects
.map(myobject => {
Tuple1(myobject.getuserId) // you need to wrap ids to a tuple to do join with Cassandra
})
.joinWithCassandraTable("mydb", "mytable")
// process results here
```
Upvotes: 2
|
2018/03/14
| 979 | 3,249 |
<issue_start>username_0: I've found hints at there being command completion available for bash[1] for the Azure CLI (`az` command), but I have not found any indication on how to install/enable that for zsh. Anyone know how to do that, if it is possible? I use oh-my-zsh, if that is relevant.
[1] <https://learn.microsoft.com/en-us/cli/azure/get-started-with-azure-cli?view=azure-cli-latest#finding-commands><issue_comment>username_1: It is possible to have completions for `az` in zsh.
1. Get the completions for bash from the Azure CLI git repo and store this file somewhere your zsh startup script can find it: <https://raw.githubusercontent.com/Azure/azure-cli/dev/az.completion>
2. Enable bash autocompletions in zsh [if it's not enabled already](https://stackoverflow.com/questions/3249432/can-a-bash-tab-completion-script-be-used-in-zsh):
```sh
autoload -U +X bashcompinit && bashcompinit
```
3. Enable the command completions for az:
```sh
source /path/to/az.completion
```
The code snippets from step 2 and 3 can be added to a shell startup file (`.zshrc` or similar) to make the changes permanent.
Upvotes: 6 [selected_answer]<issue_comment>username_2: Also, the bash completion file should already be installed on your system.
Look for `/etc/bash_completion.d/azure-cli`
If the file is there, you can skip step 1 in accepted answer and source that file directly.
Upvotes: 3 <issue_comment>username_3: In MacBook
1. Download the Bash\_completion script
2. place the az bash completion script in /usr/local/etc/bash\_completion.d
3. Make sure az script with executable permissions .
4. Update your .zshrc file as below
autoload bashcompinit && bashcompinit
source /usr/local/etc/bash\_completion.d/az
5. Restart your terminal.
Upvotes: 2 <issue_comment>username_4: For bash here are the steps:
1: AzureJumpBox $ cd /etc/bash\_completion.d/
AzureJumpBox $ ls
apport\_completion azure-cli git-prompt grub
2: AzureJumpBox $ source /etc/bash\_completion.d/azure-cli
3: AzureJumpBox $ az aks
You will see all the options
Upvotes: 0 <issue_comment>username_5: If your OS has `/etc/bash_completion.d/azure-cli`, then with [oh-my-zsh](https://github.com/ohmyzsh/ohmyzsh) it is as simple as:
```
$ ln -s /etc/bash_completion.d/azure-cli ~/.oh-my-zsh/custom/az.zsh
$ source ~/.zshrc
```
Alternatively you have to download it:
```
$ wget https://raw.githubusercontent.com/Azure/azure-cli/dev/az.completion \
-O ~/.oh-my-zsh/custom/az.zsh
```
Upvotes: 2 <issue_comment>username_6: Installed Az CLI on macOS Monterey with Homebrew I've used this commands in my `~/.zshrc` file:
```
autoload -U +X bashcompinit && bashcompinit
source /opt/homebrew/etc/bash_completion.d/az
```
Autocompletion was deployed to another location.
Upvotes: 3 <issue_comment>username_7: I landed on this page searching for Zsh `az` completion tips. Based on the earlier posts, the following adds completion using [Antidote](https://getantidote.github.io/) for plugin management:
Add
```
Azure/azure-cli kind:clone path:az.completion
```
to your `.zsh_plugins.txt` file
In your `.zshrc`, before [`antidote load`](https://getantidote.github.io/install), add
```
autoload -Uz compinit
compinit
autoload -U +X bashcompinit
bashcompinit
```
Upvotes: 0
|
2018/03/14
| 668 | 2,420 |
<issue_start>username_0: Recently I was working with lists in kotlin and had the following snippet:
```
a = listOf(1, 2, 3, 4)
println(a[-2])
```
Of course this causes an `IndexOutOfBoundsException` so I thought it would be nice to extend this functionality. So I thought one could override the `get` operator in the `List` class:
```
operator fun List.get(index: Int): T =
// Here this should call the non-overridden version of
// get.
get(index % size)
```
I understand that extensions are just static methods and therefore cannot be overridden, but is there a way one can achieve something like this?
Of course you could just create another function
```
fun List.safeGet(index: Int): T = get(index % size)
```
but I'd like to know if there are other ways.
*(I understand that `index % size` is a very naive way of doing what I want, but it's not the focus of my question and makes the code smaller.)*
**EDIT**
When I wrote this question I thought the `%` operator would return always positive numbers when the right hand side is positive - like in python. I'm keeping the original question here just for consistency.<issue_comment>username_1: You're trying something impossible, because extensions are always shadowed by members, even `@JvmName` cannot save you.
Workaround: use your second solution, or add a `Unit` parameter which is ugly (looks like `a[x, Unit]`) but can exist with its own `get` method together.
Another solution: create your own `List` implementation (recommended).
Upvotes: 3 [selected_answer]<issue_comment>username_2: Since `get` operator is already defined in `List`, you cannot redefine `get` (with one `Int` parameter).
However, you can override `invoke` operator, which is not defined in `List`.
```
fun main(args: Array) {
val a = listOf(1, 2, 3, 4)
println(a(-2))
}
// If `index` is negative, `index % size` will be non-positive by the definition of `rem` operator.
operator fun List.invoke(index: Int): T = if (index >= 0) get(index % size) else get((-index) % (-size))
```
although I think that creating a new extension method to `List` with an appropriate name will be more preferable option.
As a sidenote, `(positive value) % (negative value)` is non-negative, and `(negative value) % (positive value)` is non-positive.
`%` in Kotlin corresponds to `rem` in Haskell in the following example: <https://stackoverflow.com/a/28027235/869330>
Upvotes: 2
|
2018/03/14
| 1,822 | 4,850 |
<issue_start>username_0: I have a list containing a set of the history of a file. I need to separate each element in the list into several columns and save it to `CSV` file.
The columns I need are `commit_id, filename, committer, date, time, line_number, code`.
Suppose, this is my list:
```
my_list = [
'f5213095324 master/ActiveMasterManager.java (Michael Stack 2010-08-31 23:51:44 +0000 1) /**',
'f5213095324 master/ActiveMasterManager.java (Michael Stack 2010-08-31 23:51:44 +0000 2) *',
'f5213095324 master/ActiveMasterManager.java (Michael Stack 2010-08-31 23:51:44 +0000 3) * Licensed to the Apache Software Foundation (ASF) under one',
'f5213095324 master/ActiveMasterManager.java (Michael Stack 2010-08-31 23:51:44 +0000 4) * or more contributor license agreements.',
...
'b5cf8748198 master/ActiveMasterManager.java (Michael Stack 2012-09-27 05:40:09 +0000 160) if (ZKUtil.checkExists(this.watcher, backupZNode) != -1) {'
]
```
The desired `csv` output:
```
commit_id | filename | committer | date | time | line_number | code
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
f5213095324 | master/ActiveMasterManager.java | Michael Stack | 2010-08-31 | 23:51:44 | 1 | /**
f5213095324 | master/ActiveMasterManager.java | <NAME> | 2010-08-31 | 23:51:44 | 2 | *
f5213095324 | master/ActiveMasterManager.java | Michael Stack | 2010-08-31 | 23:51:44 | 3 | * Licensed to the Apache Software Foundation (ASF) under one
f5213095324 | master/ActiveMasterManager.java | Michael Stack | 2010-08-31 | 23:51:44 | 4 | * or more contributor license agreements.
........
b5cf8748198 | master/ActiveMasterManager.java | <NAME> | 2012-09-27 | 05:40:09 | 160 | if (ZKUtil.checkExists(this.watcher, backupZNode) != -1) {
```
I tried using this code:
```
pattern = re.compile(r'(?P\w+)\s+(?P[^\s]+)\s+\((?P.+)\s+(?P\d{4}-\d\d-\d\d)\s+(?P\d\d:\d\d:\d\d).+(?P\b\d+\b)\)\s+(?P`[^"]*)')
with open('somefile.csv', 'w+', newline='') as f:
writer = csv.writer(f)
writer.writerow(['commit_id', 'filename', 'committer', 'date', 'time', 'line_number', 'code'])
for line in my_list:
writer.writerow([field.strip() for field in pattern.match(line).groups()])`
```
In general, the code works.
But for `line number = 160`, it's written `-1` in column `line_number` and is written only `{` in column `code`.
Is there something missing in the regex?<issue_comment>username_1: I fixed regex.
This should work:
```
pattern = re.compile(r'(?P\w+)\s+(?P[^\s]+)\s+\((?P.+)\s+(?P\d{4}-\d\d-\d\d)\s+(?P\d\d:\d\d:\d\d).+?(?P\b\d+\b)\)\s+(?P`[^"]*)')`
```
I added a question mark to use Lazy matching
".+" => ".+?"
<https://regex101.com/r/GQGLvy/1>
Upvotes: 1 <issue_comment>username_2: Not exactly you are looking for but this can be useful.
```
import re
for row in my_list:
print([x.strip() for x in re.split(r"(?![)])\s+(?![(])", row)])
out:
['f5213095324', 'master/ActiveMasterManager.java', '(Michael', 'Stack', '2010-08-31', '23:51:44', '+0000', '1)', '/**']
['f5213095324', 'master/ActiveMasterManager.java', '(Michael', 'Stack', '2010-08-31', '23:51:44', '+0000', '2)', '*']
...
```
Upvotes: 0 <issue_comment>username_3: The main problem with your pattern is usage of `.+`. If you replace it with `.*?` you will not only solve the issue with line number but also with catching whitespaces after committer name:
```
pattern = re.compile(r'(?P\w+)\s+(?P[^\s]+)\s+\((?P.\*?)\s+(?P\d{4}-\d\d-\d\d)\s+(?P\d\d:\d\d:\d\d).\*?(?P\b\d+\b)\)\s+(?P`[^"]*)')`
```
<https://regex101.com/r/f7zjpA/2>
**EDIT:**
You didn't mention that you want to keep indentations and your code didn't look like you actually want it. Whitespaces/indentations before the code are removed not only because of the regex pattern. There are two things:
* in regex pattern you used `\s+` before `code` group, which excludes all the whitespaces/indentations. If you want to keep them, replace `\s+` with `\s` which will catch only first one instead all of them:
```
pattern = re.compile(r'(?P\w+)\s+(?P[^\s]+)\s+\((?P.\*?)\s+(?P\d{4}-\d\d-\d\d)\s+(?P\d\d:\d\d:\d\d).\*?(?P\b\d+\b)\)\s(?P`[^"]*)')`
```
* in the for loop you use `field.strip()` which removes all whitespaces which are present at the beginning and the end of the string. Modifying the pattern and exchanging:
```
writer.writerow([field.strip() for field in pattern.match(line).groups()])
```
with:
```
writer.writerow(pattern.match(line).groups())
```
will result in keeping indentations where they belong.
Upvotes: 2 [selected_answer]
|
2018/03/14
| 1,088 | 3,055 |
<issue_start>username_0: This is the Code
**Person.java**
```
@Entity
class Person {
@Id private Long Id;
@NotNull private String name;
//getter setters
}
```
**PersonRepository.java**
```
@RepositoryRestResource(collectionResourceRel = "person", path="person" )
interface PersonRepository extends CrudRepository{
}
```
Now, when I send null against name attribute , the validator validates it correctly, but the actual exception that is getting thrown is TransactionRollbackExecption.
Like this
```
{
"timestamp": "2018-03-14T09:01:08.533+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction",
"path": "/peron"
}
```
How do I get the actual ConstraintViolation exception. I do see the exception in logs. But its not getting thrown.<issue_comment>username_1: I fixed regex.
This should work:
```
pattern = re.compile(r'(?P\w+)\s+(?P[^\s]+)\s+\((?P.+)\s+(?P\d{4}-\d\d-\d\d)\s+(?P\d\d:\d\d:\d\d).+?(?P\b\d+\b)\)\s+(?P`[^"]*)')`
```
I added a question mark to use Lazy matching
".+" => ".+?"
<https://regex101.com/r/GQGLvy/1>
Upvotes: 1 <issue_comment>username_2: Not exactly you are looking for but this can be useful.
```
import re
for row in my_list:
print([x.strip() for x in re.split(r"(?![)])\s+(?![(])", row)])
out:
['f5213095324', 'master/ActiveMasterManager.java', '(Michael', 'Stack', '2010-08-31', '23:51:44', '+0000', '1)', '/**']
['f5213095324', 'master/ActiveMasterManager.java', '(Michael', 'Stack', '2010-08-31', '23:51:44', '+0000', '2)', '*']
...
```
Upvotes: 0 <issue_comment>username_3: The main problem with your pattern is usage of `.+`. If you replace it with `.*?` you will not only solve the issue with line number but also with catching whitespaces after committer name:
```
pattern = re.compile(r'(?P\w+)\s+(?P[^\s]+)\s+\((?P.\*?)\s+(?P\d{4}-\d\d-\d\d)\s+(?P\d\d:\d\d:\d\d).\*?(?P\b\d+\b)\)\s+(?P`[^"]*)')`
```
<https://regex101.com/r/f7zjpA/2>
**EDIT:**
You didn't mention that you want to keep indentations and your code didn't look like you actually want it. Whitespaces/indentations before the code are removed not only because of the regex pattern. There are two things:
* in regex pattern you used `\s+` before `code` group, which excludes all the whitespaces/indentations. If you want to keep them, replace `\s+` with `\s` which will catch only first one instead all of them:
```
pattern = re.compile(r'(?P\w+)\s+(?P[^\s]+)\s+\((?P.\*?)\s+(?P\d{4}-\d\d-\d\d)\s+(?P\d\d:\d\d:\d\d).\*?(?P\b\d+\b)\)\s(?P`[^"]*)')`
```
* in the for loop you use `field.strip()` which removes all whitespaces which are present at the beginning and the end of the string. Modifying the pattern and exchanging:
```
writer.writerow([field.strip() for field in pattern.match(line).groups()])
```
with:
```
writer.writerow(pattern.match(line).groups())
```
will result in keeping indentations where they belong.
Upvotes: 2 [selected_answer]
|
2018/03/14
| 253 | 771 |
<issue_start>username_0: I would like to check if
`$price_a = 30;`
is greater than all the values in
```
$all_prices = [
1 => 12,
2 => 24,
3 => 32,
4 => 44
];
```
I guess I'd have to loop through the array and do the check for each iteration but I'm not sure how that loop should look like. Or is there a simpler solution?<issue_comment>username_1: You can use the max function in array
<http://php.net/manual/en/function.max.php>
`echo max(2, 3, 1, 6, 7); // 7`
Upvotes: 1 <issue_comment>username_2: You can check it by using max function of php :
```
php
if($price_a max($all_prices)){
echo "Greater than all the values";
}
else{
echo "Smaller than ".max($all_prices);
}
?>
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 749 | 2,911 |
<issue_start>username_0: A standard pattern using DynamoDB is to separate data used by each environment by prefixing the table names with any environment-specific string.
I assumed that this would be easy to do using ElasticBeanstalk and the CloudFormation configurations in `.ebextensions`. However - for my platform (Java 8 running on 64bit Amazon Linux) at least - this seems not to be the case.
My naive implementation was to add an environment property (`DB_PREFIX`) for each environment and then adapt my table creation config in `.ebextensions` as follows:
```
Resources:
UserTable:
Type: AWS::DynamoDB::Table
Properties:
TableName:
Fn::Join:
- '_'
- - ${env:DB_PREFIX}
- 'User'
KeySchema:
HashKeyElement: {AttributeName: id, AttributeType: S}
ProvisionedThroughput: {ReadCapacityUnits: 1, WriteCapacityUnits: 1}
```
This doesn't work, possibly because, for my platform at least, environment properties are not made available as OS environment variables (see <https://stackoverflow.com/a/36567121/96553> ).
I have also thought about conditionally setting an AWS environment property based on the environment name (not a great solution as it doesn't scale well) it might be acceptable.
Does anyone have a pattern that they're already using for this kind of problem?<issue_comment>username_1: Might not be what you're looking for, but instead of relying on cloudformation to handle environment differences, I do so with a very simple build system. Say you have two envrionments, one `dev` and one `prod`. My build system will output two entirely different dists:
```
/dev
.ebextensions
/prod
.ebextensions
```
In the /dev .ebextensions file of course everything is prefixed with `dev-`. In /prod .ebextensions, everything is prefixed with `prod-`. I use gulp and nunjucks to do this, but there are a lot of options out there. So I don't have to worry about how cloudformation handles things, I know that my output is exactly what I want. I can even validate the contents of /dev and /prod with some simple tests.
In your case, you'd get this in the /dev output folder:
```
Fn::Join:
- '_'
- - dev
- 'User'
```
and this in /prod:
```
Fn::Join:
- '_'
- - prod
- 'User'
```
More details on how I do that: <https://stackoverflow.com/a/49011398/3650835>
Upvotes: 1 <issue_comment>username_2: Simply don't set a name. CloudFormation will select a unique name for you that contains the stack name. Another option is using `${AWS::StackName}` yourself.
```
Resources:
UserTable:
Type: AWS::DynamoDB::Table
Properties:
TableName:
Fn::Sub: ${AWS::StackName}_User
KeySchema:
HashKeyElement: {AttributeName: id, AttributeType: S}
ProvisionedThroughput: {ReadCapacityUnits: 1, WriteCapacityUnits: 1}
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 224 | 782 |
<issue_start>username_0: I have a constructor that looks like
```
constructor(values: Object = {}) {
//Constructor initialization
Object.assign(this, values);
}
```
but it requires named initialization :
```
new Inventory({ Name: "Test", Quantity: 1, Price: 100 })
```
can it be done directly from array like this:
```
new Inventory(["Test",1,100])
```<issue_comment>username_1: Try this
```
var [Name, Quantity, Price] = ["Test", 1, 100];
new Inventory({Name, Quantity, Price});
```
Upvotes: 1 <issue_comment>username_2: You could change constructor to:
```
constructor(name: string, quantity: number, price: number) {
//Constructor initialization
Object.assign(this, { Name: name, Quantity: quantity, Price: price });
}
```
Upvotes: 0
|
2018/03/14
| 1,449 | 4,681 |
<issue_start>username_0: Hya,
I have the below setup:
**App.Component.Ts contents**
```
carForm: FormGroup;
constructor(
private fb: FormBuilder
) {
this.carForm= this.fb.group({
name: '',
type: '',
extras: this.fb.array([])
});
}
get carExtras(): FormArray {
return this.carForm.get('extras') as FormArray;
}
addNewExtra() {
this.carExtras.push(this.fb.group(new Extra());
}
```
**Extra Model**
```
export class Extra {
name: string = '';
description: string = '';
}
```
Now lets say i add 4 new Extras, the array would look as follows:
```
1. name = "Phantom Wheels", description = "Big dark wheels coz driver is overcompensating"
2. name = "Clearshield", description = "Simple tint that we overcharge customers"
3. name = "Rainbow Paint Job", description = "Leftover random paints mixed and thrown onto car"
4. name = "Slick Rims", description = "Major overcompensation"
```
I want to be able to programmatically change the order of the 4 items listed.
Say i click up button next to "Slick Rims", it will swap positions with "Rainbow Paint Job" item. If i press it again it will swap positions with "Clearshield" with result as follows.
```
1. name = "Phantom Wheels", description = "Big dark wheels coz driver is overcompensating"
2. name = "Slick Rims", description = "Major overcompensation"
3. name = "Clearshield", description = "Simple tint that we overcharge customers"
4. name = "Rainbow Paint Job", description = "Leftover random paints mixed and thrown onto car"
```
Same principle if i press the down button for the entry.
Any ideas how to achieve this, its doing my head in on how to achieve this with a FormArray.<issue_comment>username_1: Assuming your form array looks like this in HTML:
```
extras:
UP
DOWN
```
you can create `moveUp` and `moveDown` functions to swap values at indexes (i-1, i) or (i, i+1) if it is possible
```
moveUp(index: number) {
if (index > 0) {
const extrasFormArray = this.carForm.get('extras') as FormArray;
const extras = extrasFormArray.value;
const newExtras = this.swap(extras, index - 1, index);
extrasFormArray.setValue(newExtras);
}
}
moveDown(index: number) {
const extrasFormArray = this.carForm.get('extras') as FormArray;
const extras = extrasFormArray.value;
if (index < extras.length - 1) {
const newExtras = this.swap(extras, index, index + 1);
extrasFormArray.setValue(newExtras);
}
}
```
swap function:
```
swap(arr: any[], index1: number, index2: number): any[] {
arr = [...arr];
const temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
return arr;
}
```
demo: <https://stackblitz.com/edit/angular-bhcdcf>
EDIT: Actually we can simplify that to single function
```
swap(index1: number, index2: number) {
const extrasFormArray = this.carForm.get('extras') as FormArray;
const extras = [...extrasFormArray.value];
if (index2 > 0 && index1 < extras.length - 1) {
[extras[index1], extras[index2]] = [extras[index2], extras[index1]];
extrasFormArray.setValue(extras);
}
}
```
which would be called with appropriate indexes
```
UP
DOWN
```
demo: <https://stackblitz.com/edit/angular-9gifvd>
EDIT 2 by Aeseir:
Further simplification and following DRY principle (at least attempting to):
```
get extras(): FormArray {
return this.carForm.get('extras') as FormArray;
}
moveUp(index: number) {
var extraTmp = this.extras.at(index);
this.removeExtra(index);
this.extras.insert(index-1, extraTmp);
}
moveDown(index: number) {
var extraTmp = this.extras.at(index-1);
this.removeExtra(index-1);
this.extras.insert(index, extraTmp);
}
removeExtra(index: number) {
this.extras.removeAt(index);
}
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: If you have FormGroup in FormArray and FormGroup also has FormArray, you'll want to just swap them around.
The next example works for me:
```
import { FormArray } from '@angular/forms';
const swap = (items: T[], a: number, b: number): T[] => {
switch (true) {
case a < 0:
case b < 0:
case a > items.length - 1:
case b > items.length - 1:
throw new Error('Undefined swap index');
}
return items.map((\_, i) => {
switch (i) {
case a:
return items[b];
case b:
return items[a];
default:
return items[i];
}
});
};
export const swapFormArray = (formArray: T, a: number, b: number): void => {
formArray.controls = swap(formArray.controls, a, b);
formArray.updateValueAndValidity();
};
```
usage:
```
swapFormArray(formArr, i, i - 1);
swapFormArray(formArr, i, i + 1);
```
Upvotes: 0
|
2018/03/14
| 1,489 | 5,128 |
<issue_start>username_0: This is my json object:
```
{
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
}
```
I want my output like this:
```
{
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"cats": [1,2] // this 1 and 2 is coming from categoriesservices array inside the category object i have id
}
```
How to do this using map function? I am new to javascript, which is good approach map or forloop?<issue_comment>username_1: See [`destructuring assignment`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), [`Array.prototype.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), and [`JSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) for more info.
```js
// Input.
const input = {
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
}
// Categories => Objects to Cats => Ids.
const output = (input) => JSON.parse(JSON.stringify({
...input,
cats: input.categoryservices.map(({category: {id}}) => id),
categoryservices: undefined
}))
// Log.
console.log(output(input))
```
Upvotes: 1 <issue_comment>username_2: You can try using jquery each:
```
var conversation = {
'John': {
1: 'Test message 1',
2: 'Test message 2',
'Reply': {
3: 'Test message 3',
4: 'Test message 4'
}
},
'Jack': {
5: 'Test message 5',
6: 'Test message 6'
}
};
function iterate(obj) {
if (typeof obj === 'string') {
$('#log').append((obj + '
'));
}
if (typeof obj === 'object') {
$.each(obj, function(key, value) {
iterate(value);
});
}
}
iterate(conversation);
```
Upvotes: -1 <issue_comment>username_3: If you are not worried about original object immutability, then try this
```
obj['cats'] = obj['categoryservices'].map(cat => cat.category.id);
delete obj['categoryservices'];
console.log(obj);
```
Upvotes: 0 <issue_comment>username_4: I just use .map() on categoryservices array:
```
var output = {
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
};
output.cats = output.categoryservices.map((element) =>
element.category.id);
delete output.categoryservices;
console.log(JSON.stringify(output));
```
Upvotes: 0 <issue_comment>username_5: use `.map()` , it return value as array ! You want to change is `categoryservices` key only ! So *delete* that after you get wanted value ..
```js
var output = {
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
};
output.cats = output.categoryservices.map(i => i.category.id );
delete output.categoryservices;
console.log(output);
```
Upvotes: 0 <issue_comment>username_6: **Try this working demo :**
```js
var jsonObj = {
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
};
var arr = jsonObj.categoryservices.map(item => item.category.id)
jsonObj.cats = arr;
delete jsonObj.categoryservices;
console.log(jsonObj);
```
Upvotes: 0 <issue_comment>username_7: Try this
```
var testData={
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
}
testData.cats=[];
testData.categoryservices.forEach(function (item) {
testData.cats.push(item.category.id);
});
delete testData.categoryservices;
console.log(testData);
```
Upvotes: 0
|
2018/03/14
| 897 | 3,013 |
<issue_start>username_0: I am getting some syntax error in my PHP code, which I am unable to solve.
Please have a look at this and help me to solve this. [Here Is The Screenshot](https://i.stack.imgur.com/lmx6H.png).
I have attached the screenshot of the error which I am getting on line 14.
```
php
$link = mysqli_connect('localhost','root','','satyam');
if(isset($_POST['name']))
{
$name = $_POST['name'];
$sql = "SELECT * FROM students WHERE name='".$name."'";
$sql_run = mysqli_query($link,$sql);
if($row=mysqli_fetch_array($sql_run))
{
$name = $row["name"];
$roll = $row["roll"];
$branch = $row["branch"];
$address = $row["address"];
echo 'Name: '.$name.' Roll: '.$roll.' Branch: '.$branch.' Address: '.$address';
} else {
echo "No Record Found";
}
}
?
```<issue_comment>username_1: You have an extra `'` at the end of :
```
echo 'Name: '.$name.' Roll: '.$roll.' Branch: '.$branch.' Address: '.$address';
```
after `$address`
Upvotes: 0 <issue_comment>username_2: You added an extra unnecessary single quote (`'`) end of the following line
```
echo 'Name: ' . $name . ' Roll: ' . $roll . ' Branch: ' . $branch . ' Address: ' . $address;
```
This code works fine.
```
$link = mysqli_connect('localhost','root','','satyam');
if(isset($_POST['name'])) {
$name = $_POST['name'];
$sql = "SELECT * FROM students WHERE name='" . $name."'";
$sql_run = mysqli_query($link,$sql);
if($row = mysqli_fetch_array($sql_run)) {
$name = $row["name"];
$roll = $row["roll"];
$branch = $row["branch"];
$address = $row["address"];
echo 'Name: ' . $name . ' Roll: ' . $roll . ' Branch: ' . $branch . ' Address: ' . $address;
} else {
echo "No Record Found";
}
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: Please check this :
```
php
$link = mysqli_connect('localhost','root','','satyam');
if(isset($_POST['name']))
{
$name = $_POST['name'];
$sql = "SELECT * FROM students WHERE name='".$name."'";
$sql_run = mysqli_query($link,$sql);
if($row=mysqli_fetch_array($sql_run))
{
$name = $row["name"];
$roll = $row["roll"];
$branch = $row["branch"];
$address = $row["address"];
echo 'Name: '.$name.' Roll: '.$roll.' Branch: '.$branch.' Address: '.$address;
} else {
echo "No Record Found";
}
}
?
```
You added a extra ' on this line :
```
echo 'Name: '.$name.' Roll: '.$roll.' Branch: '.$branch.' Address: '.$address;
```
Upvotes: 0 <issue_comment>username_4: This line:
```
echo 'Name: '.$name.' Roll: '.$roll.' Branch: '.$branch.' Address: '.$address';
```
Should be:
```
echo 'Name: '.$name.' Roll: '.$roll.' Branch: '.$branch.' Address: '.$address;
```
Upvotes: 0 <issue_comment>username_5: remove the quotation mark (') at the end of line 14 (the one next to the semicolon).
Upvotes: 0
|
2018/03/14
| 1,398 | 5,053 |
<issue_start>username_0: I am trying to authenticate users through ldap (window active directory) with Symfony 3.4 and i use this [documentation](https://symfony.com/doc/3.4/security/ldap.html)
Please, Help Me!!!!
But I'm getting error:
>
> php.DEBUG: Warning: ldap\_bind(): Unable to bind to server: Invalid credentials {"exception":"[object] (Symfony\Component\Debug\Exception\SilencedErrorContext: {\"severity\":2,\"file\":\"C:\\OSPanel\\domains\\warcsymfony\\vendor\\symfony\\symfony\\src\\Symfony\\Component\\Ldap\\Adapter\\ExtLdap\\Connection.php\",\"line\":53,\"trace\":[{\"file\":\"C:\\OSPanel\\domains\\warcsymfony\\vendor\\symfony\\symfony\\src\\Symfony\\Component\\Ldap\\Ldap.php\",\"line\":38,\"function\":\"bind\",\"class\":\"Symfony\\Component\\Ldap\\Adapter\\ExtLdap\\Connection\",\"type\":\"->\"}],\"count\":1})"} []
> [2018-03-14 10:27:03] security.INFO: Authentication request failed. {"exception":"[object] (Symfony\Component\Security\Core\Exception\BadCredentialsException(code: 0): Bad credentials. at C:\OSPanel\domains\warcsymfony\vendor\symfony\symfony\src\Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider.php:71, Symfony\Component\Security\Core\Exception\UsernameNotFoundException(code: 0): User \"testusername\" not found. at C:\OSPanel\domains\warcsymfony\vendor\symfony\symfony\src\Symfony\Component\Security\Core\User\LdapUserProvider.php:75, Symfony\Component\Ldap\Exception\ConnectionException(code: 0): Invalid credentials at C:\OSPanel\domains\warcsymfony\vendor\symfony\symfony\src\Symfony\Component\Ldap\Adapter\ExtLdap\Connection.php:54)"} []
> [2018-03-14 10:27:03] security.DEBUG: Authentication failure, redirect triggered. {"failure\_path":"login"} []
>
>
>
I tried change in parameters, but it did not work
```
security.yml
security:
providers:
my_ldap:
ldap:
service: Symfony\Component\Ldap\Ldap
base_dn: DC=example,DC=com
search_dn: 'OU=all-users-accounts,DC=example,DC=com'
search_password: <PASSWORD>
default_roles: ROLE_USER
uid_key: sAMAccountName
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
pattern: ^/
anonymous: ~
form_login_ldap:
login_path: login
check_path: login
service: Symfony\Component\Ldap\Ldap
dn_string: 'sAMAccountName={username},DC=example,DC=com'
service.yml
services:
Symfony\Component\Ldap\Ldap:
arguments: ['@Symfony\Component\Ldap\Adapter\ExtLdap\Adapter']
Symfony\Component\Ldap\Adapter\ExtLdap\Adapter:
arguments:
- host: **.**.**.**
port: 389
encryption: 'none'
options:
protocol_version: 3
referrals: false
```
SecurityController
```
/**
* @Route("/login", name="login")
*/
public function loginAction(Request $request, AuthenticationUtils $authenticationUtils){
$error = $authenticationUtils->getLastAuthenticationError();
$username = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', array(
'last_username' => $username,
'error' => $error
));
}
```<issue_comment>username_1: So tested and work. i think what your mistake was search\_dn,search\_password and query\_string.
```
my_ldap:
ldap:
service: Symfony\Component\Ldap\Ldap
base_dn: "DC=example,DC=lv"
#remmber this is ldap user with read only permisions
#could be also just username search_dn:"bind"
search_dn: "CN=bind bind,CN=Users,DC=example,DC=lv"
search_password: "<PASSWORD> user password"
uid_key: sAMAccountName
```
in form example i used query string- it check if sAMAccoutName and if member of SystemGroup.
```
form_login_ldap:
provider: my_ldap
login_path: login_route
check_path: login_check_form
service: Symfony\Component\Ldap\Ldap
dn_string: 'DC=example,DC=lv'
query_string: '(&(sAMAccountName={username})(memberof=CN=SystemGroup,OU=Groups,OU=xxx_users,DC=example,DC=lv))'
```
Just test your query\_string with ldap\_search
<http://php.net/manual/en/function.ldap-search.php#112191>
Upvotes: 1 <issue_comment>username_2: I believe it is your search\_dn which is incorrect, this line:
```
search_dn: 'OU=all-users-accounts,DC=example,DC=com'
```
It needs to be the dn of the administrator that has access to browse Active Directory. You can use [Softerra's free LDAP Browser](http://www.ldapadministrator.com/download.htm) to browse active directory and figure that out.
This is all outlined in my [Symfony LDAP Component AD Authentication](https://alvinbunk.wordpress.com/2017/09/07/symfony-ldap-component-ad-authentication/) article. Be advised, you need to do a lot of debugging to get this working, but once you get it working it's easy.
Upvotes: 0
|
2018/03/14
| 275 | 851 |
<issue_start>username_0: I need to create a new model, after setting the virtual host I couldn't acces the url for gii generator.
My Virtual Host :
```
DocumentRoot "C:/xampp/htdocs/admin/backend/web"
ServerName admin.product
```
How can I access the gii generator now?
>
> The gii url looks like
> <http://hostname/index.php?r=gii>
>
>
> reference: <http://www.yiiframework.com/doc-2.0/guide-start-gii.html>
>
>
><issue_comment>username_1: Found the solution.
I could access gii via url
>
> admin.product/gii
>
>
>
Note : I use pretty url.
Upvotes: 1 [selected_answer]<issue_comment>username_2: 1. If you are on Windows, assure you set up your hosts file right.
2. Assure that you can access the main page of your backend application.
3. Then assure that you have your Gii module included into backend app's config.
Upvotes: 2
|
2018/03/14
| 162 | 565 |
<issue_start>username_0: Is there feature in WSO2 APIM 2.1 or higher version which could do first flattening of wsdl file and then create APIs ?<issue_comment>username_1: Found the solution.
I could access gii via url
>
> admin.product/gii
>
>
>
Note : I use pretty url.
Upvotes: 1 [selected_answer]<issue_comment>username_2: 1. If you are on Windows, assure you set up your hosts file right.
2. Assure that you can access the main page of your backend application.
3. Then assure that you have your Gii module included into backend app's config.
Upvotes: 2
|
2018/03/14
| 303 | 1,032 |
<issue_start>username_0: I have an `Error` table which stores the names of the **table** in which the error occurred.
Now I want to query the table using the table name selected from the "Error" table.
I tried to store the table name in a variable and use this variable in the FROM clause in my query. But this doesn't work:
```
DECLARE @tableName VARCHAR(15)
select @tableName = TableName from SyncErrorRecords where Status = 'Unsynced'
select * from @tableName
```
Can anyone help me out on this.
Thanks in advance.<issue_comment>username_1: you need to use `Dynamic SQL`
either
```
declare @sql nvarchar(max)
select @sql = 'select * from ' + quotename(@tableName)
exec (@sql)
```
or
```
exec sp_executesql @sql
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: The Query as follows.
```
DECLARE @tableName VARCHAR(15),
@Qry VARCHAR(4000)
SELECT @tableName = TableName FROM SyncErrorRecords WHERE Status = 'Unsynced'
SET @Qry = 'SELECT * FROM ' + @tableName
EXEC SP_EXECUTESQL @Qry
```
Upvotes: 0
|
2018/03/14
| 658 | 2,491 |
<issue_start>username_0: I want the **random string result(output)** to display inside the **text box** so I can saved the value into my database.
```js
(function() {
function IDGenerator() {
this.length = 4;
this.timestamp = +new Date;
var _getRandomInt = function( min, max ) {
return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
}
this.generate = function() {
var ts = this.timestamp.toString();
var parts = ts.split( "" ).reverse();
var id = "TEST";
for( var i = 0; i < this.length; ++i ) {
var index = _getRandomInt( 0, parts.length - 1 );
id += parts[index];
}
return id;
}
}
document.addEventListener( "DOMContentLoaded", function() {
var btn = document.querySelector( "#generate" ),
output = document.querySelector( "#output" );
btn.addEventListener( "click", function() {
var generator = new IDGenerator();
output.innerHTML = generator.generate();
}, false);
});
})();
```
```html
Generate
```
**NOTE**
Any idea on how to fix this? So when every time I click **generate button** the result will come out in a **text box** then save the value to my database.<issue_comment>username_1: Simply you can replace code tag by input tag
```
```
and replace output.innerHTML to be
```
output.value= generator.generate();
```
Hope that's help
Upvotes: 0 <issue_comment>username_2: ```js
(function() {
function IDGenerator() {
this.length = 4;
this.timestamp = +new Date;
var _getRandomInt = function( min, max ) {
return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
}
this.generate = function() {
var ts = this.timestamp.toString();
var parts = ts.split( "" ).reverse();
var id = "TEST";
for( var i = 0; i < this.length; ++i ) {
var index = _getRandomInt( 0, parts.length - 1 );
id += parts[index];
}
return id;
}
}
document.addEventListener( "DOMContentLoaded", function() {
var btn = document.querySelector( "#generate" ),
output = document.querySelector( "#output" );
btn.addEventListener( "click", function() {
var generator = new IDGenerator();
$("#output").val(generator.generate());
}, false);
});
})();
```
```html
Generate
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 459 | 1,520 |
<issue_start>username_0: I have `NSDictionary` with floating values, I am trying to get values like this
```
[[NSDictionary valueForKey:@"some_value"] floatValue];
```
but looks like value not rounded correctly.
For example:
I have value in dictionary: `@"0.35"` but after above conversion returns `0.34999999403953552 float value`, `@"0.15"` converts into `0.15000000596046448` etc.<issue_comment>username_1: Simply you can replace code tag by input tag
```
```
and replace output.innerHTML to be
```
output.value= generator.generate();
```
Hope that's help
Upvotes: 0 <issue_comment>username_2: ```js
(function() {
function IDGenerator() {
this.length = 4;
this.timestamp = +new Date;
var _getRandomInt = function( min, max ) {
return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
}
this.generate = function() {
var ts = this.timestamp.toString();
var parts = ts.split( "" ).reverse();
var id = "TEST";
for( var i = 0; i < this.length; ++i ) {
var index = _getRandomInt( 0, parts.length - 1 );
id += parts[index];
}
return id;
}
}
document.addEventListener( "DOMContentLoaded", function() {
var btn = document.querySelector( "#generate" ),
output = document.querySelector( "#output" );
btn.addEventListener( "click", function() {
var generator = new IDGenerator();
$("#output").val(generator.generate());
}, false);
});
})();
```
```html
Generate
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 959 | 3,596 |
<issue_start>username_0: I have to call a function from one controller an other controller.
```
public function getquickviews(Request $request){
$report = new ReportController();
$report ->Applications($request->except('cl_e_start_date'));//it's not working its giving me error that it expect and instance of Request and passed array()
}
public function Applications(Request $request)
{
/*APP USAGE*/
}
```
and I have to pass instance of Request to Application function. But the issue I don't wanted to pass all the parameter from getquickviews Request like if I am getting email,phone,name on the getquickviews function but I only have to pass phone,email to Application function.<issue_comment>username_1: Change this line
```
$report ->Applications($request->except('cl_e_start_date'));
```
To
```
$report ->Applications($request);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: try as following (not sure it's gonna work) :
```
public function getquickviews(Request $request){
$returnedRequest = $request; // do whatever with your request here
return redirect()->route('SecondController.Applications', compact('returnedRequest'));
}
public function Applications(Request $request){
/*APP USAGE*/
}
```
Upvotes: 1 <issue_comment>username_3: I think this will work :
```
$report ->Applications($request->toArray());
```
Upvotes: 0 <issue_comment>username_4: You can keep the particular key and value you want and delete the rest from the `$request` before passing it to the function. First convert the $request to array by
```
$request->toArray()
```
and then delete the unwanted keys by doing
```
unset($request['key-here']);
```
and then pass it to the function
```
$report ->Applications($request);
```
Upvotes: -1 <issue_comment>username_5: Two ways to get requests into next method or any next level call.
First you can inject Request class depenednacy into that method for an example:
```
public function store(Request $request)
{
// Form Submits here
}
```
If you want to pass $request into other method for example to display data after insert you can do this way:
```
public function showStore(Request $request)
{
dd($request->get());
}
```
Then you can call this method from store method
```
$this->showStore($request);
```
or second is you can use request as metho into showStore or any n level call. Like this:
```
public function showStore()
{
dd(request()->all());
}
$this->showStore(); // You do not require any injection.
```
Good Luck!!!
Upvotes: 0 <issue_comment>username_6: You need to create a new instance of Request.
```
public function getquickviews(Request $request){
$report = new ReportController();
$content = new Request();
$content->something = $request->something;
$content->somethingElse = $request->somethingElse;
$report ->Applications($content);
}
```
and then you have to recieve it in:
```
public function Applications(Request $request)
{
/*APP USAGE*/
}
```
and that's it.
Regards.
Upvotes: 4 <issue_comment>username_7: To be able to create a custom request and thus use it to reference a post method in a controller, you need to first initiate an instance of Request as @martin Carrasco has described above:
the code below is a continuation of martin Carrasco
```
public function getquickviews(Request $request){
$report = new ReportController();
$content = new Request
([
'firstParam' => $request->param1,
'secondParam' => $request ->param2,
]);
$report ->Applications($content);
```
}
Try that n hope it works.
Upvotes: 1
|
2018/03/14
| 566 | 1,857 |
<issue_start>username_0: I'm trying to set a background image in react native.I want a background cover image. I've done like the below
```
{
this.state.details.map(a =>
{ a.content = a.content.replace(regex, '') } < /Text>
< RadioForm style= {{ width: 350 - 30 }} outerColor = "#080103" innerColor = "#FF5733" itemShowKey = "label" itemRealKey = "item" dataSource = { transform(a.options) } onPress = {(item)=>this.\_onSelect(item)}/>
)
}
const styles = StyleSheet.create({
image: {
flex: 1,
resizeMode: 'cover',
position: 'absolute',
width: "100%",
flexDirection: 'column'
},
textStyle: {
fontSize: 16,
color: '#000',
padding: 5,
},
});
```
But I'm getting something like this
[](https://i.stack.imgur.com/pkGc0.png)<issue_comment>username_1: What you need is `ImageBackground`component.
`import {ImageBackground} from 'react-native';`
```
```
That should do it.
Upvotes: 0 <issue_comment>username_2: ```
import React from 'react';
import { View, Image, StyleSheet } from 'react-native';
import { WINDOW } from '../assets/config.js';
class Splash extends React.Component{
render(){
return(
)
}
}
const styles = StyleSheet.create({
splashContainer: {
flex: 1
},
bgImage: {
flex: 1,
width: WINDOW.width,
height: WINDOW.height,
}
});
export default Splash;
```
try like this. This worked fine for me.
Upvotes: 0 <issue_comment>username_3: You might need to add the `ImageBackground` outside of your `ScrollView` and make sure `flex` is being passed to the `ImageBackground` `style'`
For example
```
{/\*Render the children here\*/}
```
Upvotes: 4 [selected_answer]<issue_comment>username_4: Use
source={your image path}>
Upvotes: 0
|
2018/03/14
| 679 | 2,425 |
<issue_start>username_0: I have copied an example from their own website but i do not know how to get it working.
[Link to their example](http://pycallgraph.slowchop.com/en/master/examples/basic.html#source-code)
This is my code:
```
from pycallgraph import PyCallGraph
from pycallgraph.output import GraphvizOutput
class Banana:
def eat(self):
pass
class Person:
def __init__(self):
self.no_bananas()
def no_bananas(self):
self.bananas = []
def add_banana(self, banana):
self.bananas.append(banana)
def eat_bananas(self):
[banana.eat() for banana in self.bananas]
self.no_bananas()
def main():
graphviz = GraphvizOutput()
graphviz.output_file = 'basic.png'
with PyCallGraph(output=graphviz):
person = Person()
for a in xrange(10):
person.add_banana(Banana())
person.eat_bananas()
if __name__ == '__main__':
main()
```
And this is the error i am receiving when trying to compile it:
```
File "test_pycallgraph.py", line 43, in
main()
File "test\_pycallgraph.py", line 35, in main
with PyCallGraph(output=graphviz):
'The command "{}" is required to be in your path.'.format(cmd))
pycallgraph.exceptions.PyCallGraphException: The command "dot" is required to be in your path.
```<issue_comment>username_1: It seems that the library you want to use makes an internal call to the the `dot` command. But since `dot` is not in your PATH, the library cannot find the `dot` executable and raises an exception.
You most likely need to install `dot`, which is a command line tool for drawing directed graphs. Make sure you have it installed.
If you already have it installed, make sure you add it’s location to your PATH. See [this Stack Overflow answer](https://stackoverflow.com/a/14638025) for more information about modifying your PATH.
Upvotes: 2 [selected_answer]<issue_comment>username_2: The previous answer was a bit too vague. You need to find dot.exe, which for me was in C:\Program Files (x86)\Graphviz2.38\bin so I went to the following:
control panel > system > advanced system settings > Environment Variables... and then in the bottom box for System Variables, find Path, select it and select edit, then select new and paste the path in. Now close and reopen cmd.exe and see simple type in 'dot' and hit enter. If there's no error, the path was setup properly.
Upvotes: 0
|
2018/03/14
| 1,158 | 4,413 |
<issue_start>username_0: I am using a SQL query and sql server in my application to display data, it gives a major performance hit.
When query gets executed the **CPU and DTU goes till 100%**
It is a major performance issue.
Query:-
```
SELECT *
FROM (SELECT Alls.*,
ROW_NUMBER()
OVER (
ORDER BY Alls.col1 DESC) AS RowNum,
COUNT(*)
OVER () AS TotalCount
FROM tab1 AllS
LEFT JOIN tab2 FF
ON Alls.col2 = FF.col2
WHERE ( ( ( @par1 IS NULL
AND 1 = 1 )
OR ( @par1 IS NOT NULL
AND '1' = fun1 (col3, ',', @par1, 'exact contains') ) )
AND ( ( @par2 IS NULL
AND 1 = 1 )
OR ( @par2 IS NOT NULL
AND ( Alls.col1 BETWEEN CONVERT(DATETIME, @par2) AND CONVERT(DATETIME, @par7) ) ) )
AND ( ( @par3 IS NULL
AND 1 = 1 )
OR ( @par3 IS NOT NULL
AND col4 IN (SELECT CONVERT(INT, Item)
FROM dbo.Split(@par3, ',')) ) )
AND ( ( ( @par4 IS NULL
AND col5 = NULL )
OR ( @par4 IS NOT NULL
AND col5 = @par4 ) )
OR ( ( @par5 IS NULL
AND col6 = NULL )
OR ( @par5 IS NOT NULL
AND col6 = @par5 ) )
OR ( ( @par6 IS NULL
AND col7 = NULL )
OR ( @par6 IS NOT NULL
AND col7 = @par6 ) )
AND ( ( @par8 IS NULL
AND 1 = 1 )
OR ( @par8 IS NOT NULL
AND col8 IS NULL ) )
AND ( ( ( @par9 IS NULL
AND 1 = 1 )
OR ( @par9 IS NOT NULL
AND col9 LIKE '%' + @par9 + '%' ) )
OR ( ( @par9 IS NULL
AND 1 = 1 )
OR ( @par9 IS NOT NULL
AND col8 = @par9 ) ) ) ) )
AND col10 = 1
AND col11 IS NULL) AS List
WHERE RowNum BETWEEN @startRowIndex AND ( @startRowIndex + @pageSize ) - 1
ORDER BY col1 DESC
```
Please suggest how to optimize the query.
Here is the schema:
```
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE tab1( [ID] [int] IDENTITY(1,1) NOT NULL, [col2] [uniqueidentifier] NOT NULL, [col5] [bit] NOT NULL, [col6] [bit] NOT NULL, [col7] [bit] NOT NULL, [col10] [bit] NOT NULL, [col1] [datetime] NOT NULL, [col4] [datetime] NOT NULL, [col3] [nvarchar](1000) NULL, [col11] [bit] NULL, [col8] [nvarchar](max) NULL, CONSTRAINT [PK_Alls] PRIMARY KEY CLUSTERED ( [col2] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) )
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE tab2( [Id] [int] NULL, [col2] [varchar](40) NULL, [col9] [varchar](max) NULL, [col1] [datetime] NULL ) GO SET ANSI_PADDING OFF GO
```<issue_comment>username_1: `AND 1 = 1` is literally useless here
`@par4 IS NULL AND col5 = NULL` - won't work
hit 1
=====
`AND '1' = fun1 (col3, ',', @par1, 'exact contains')`
hit 2
=====
`AND col4 IN (SELECT CONVERT(INT, Item) FROM dbo.Split(@par3, ','))`
hit 3
=====
`AND col9 LIKE '%' + @par9 + '%' )`
hit 4
=====
`Alls.col1 BETWEEN CONVERT(DATETIME, @par2) AND CONVERT(DATETIME, @par7)`
hit 5
=====
`... OR ... OR ... OR ... OR ... OR ...`
and the pagination itself too.
And please take a look at the link from <NAME>.
Upvotes: 2 <issue_comment>username_2: I have removed 1=1 and i believe it was not necessary as I am getting the same result.
Then I tried to optimize the OR OR conditions.
The main reason is the **JOIN**.
Now, I am searching an alternative for the **LEFT JOIN**
It will be pleasure to have more suggestions.
Upvotes: 0
|
2018/03/14
| 1,229 | 3,930 |
<issue_start>username_0: I have a checkbox when i selected i have on database the value '1' but when i dont select i have this erreur
{SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'actif' cannot be null (SQL: insert into `techniciens` (`user_id`, `actif`, `moyenne_avis`, `updated_at`, `created_at`) values (6, , 30.555, 2018-03-14 09:07:15, 2018-03-14 09:07:15))}
create.blade.php
```
@extends('Layouts/app')
@extends('Layouts.master')
@section('content')
@if(count($errors))
@foreach($errors ->all() as $message)
* {{$message}}
@endforeach
@endif
Ajouter Technicien
==================
{{csrf\_field()}}
Nom
@if ($errors->has('nom'))
**{{ $errors->first('nom') }}**
@endif
Prenom
@if ($errors->has('prenom'))
**{{ $errors->first('prenom') }}**
@endif
Telephone
@if ($errors->has('tel'))
**{{ $errors->first('tel') }}**
@endif
Mobile
@if ($errors->has('mobile'))
**{{ $errors->first('mobil') }}**
@endif
Role
@if ($errors->has('role'))
**{{ $errors->first('role') }}**
@endif
E-Mail Address
@if ($errors->has('email'))
**{{ $errors->first('email') }}**
@endif
Password
@if ($errors->has('password'))
**{{ $errors->first('password') }}**
@endif
Confirm Password
zoneintervention
@foreach($zoneintervention as $zoneintervention)
{{$zoneintervention->code\_postal}}
@endforeach
Moyenne Avis
Etat
@endsection
```
controler
```
public function create()
{
$zoneintervention = Zoneintervention::orderBy('id', 'desc')->get();
$metier = metier::orderBy('libelle_metier', 'desc')->get();
$tache = tache::orderBy('libelle_tache', 'desc')->get();
$user = user::orderBy('id', 'desc')->get();
return view('technicien.create')->with('zoneintervention',
$zoneintervention)->with('user',
$user);
}
/**
* Store a newly created resource in storage.
*
* @param
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$user = new user();
$user->nom = $request->input('nom');
$user->prenom = $request->input('prenom');
$user->tel = $request->input('tel');
$user->mobil = $request->input('mobil');
$user->role = $request->input('role');
$user->email = $request->input('email');
$user->password = $request-><PASSWORD>('<PASSWORD>');
$user->save();
$technicien = new technicien();
$technicien->user_id = $user->id;
$technicien->actif = $request->input('actif');
$technicien->moyenne_avis = $request->input('moyenne_avis');
$technicien->save();
$technicien->zoneintervention()->attach($request->zoneintervention_id);
return redirect('tarification/create');
}
```
route.php
```
Route::get('/technicien', 'TechnicienController@index');
Route::get('/technicien/create', 'TechnicienController@create');
Route::post('/technicien', 'TechnicienController@store');
```<issue_comment>username_1: It's an SQLSTATE[23000] Integrity constraint violation error which occurs if the rules you declared in migration file doesn't matches with the input from your form. So in order to resolve this error you need to just add **nullable()** to your database migration file where you have **'actif'** column declared in the up method.
```
$table->tinyInteger('actif')->nullable();
```
Upvotes: 0 <issue_comment>username_2: Use `$request->has()`
```
$technicien = new technicien();
$technicien->user_id = $user->id;
if($request->has('actif')){
$technicien->actif = $request->input('actif');
}else{
$technicien->actif = 0;
}
$technicien->moyenne_avis = $request->input('moyenne_avis');
$technicien->save();
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: Try to add hidden input with zero value, like this:
```
```
So if checkbox is checked, then `actif` value will be 1, if checkbox is unchecked, then `actif` value will be 0, because then hidden value will be used.
Upvotes: 2
|
2018/03/14
| 691 | 1,847 |
<issue_start>username_0: My ruby script filters a log and generates a hash like this
```
scores = {"Rahul" => "273", "John"=> "202", "coventry" => "194"}
```
by skipping multiple values for a key which is obvious
log file will be like this
>
> Rahul has 273 Rahul has 217 John has 202 Coventry has 194
>
>
>
Is it Possible to generate something like this
```
scores = {"Rahul" => "273", "Rahul" =>"217",
"John"=> "202", "coventry" => "194"}
scores = {"Rahul" => "273","217",
"John"=> "202", "coventry" => "194"}
```
Is there a way to forcefully write into a hash even though the key is already existing in the hash
I will be grateful to any help or suggestions<issue_comment>username_1: ```
"Rahul has 273 Rahul has 217 John has 202 Coventry has 194".
scan(/(\w+) has (\d+)/).group_by(&:shift)
#⇒ {"Rahul"=>[["273"], ["217"]],
# "John"=>[["202"]],
# "Coventry"=>[["194"]]}
```
For the values flattening please check the comment by <NAME> below.
Upvotes: 2 <issue_comment>username_2: To store your scores, you could create a hash which has an empty array as its default value:
```
scores = Hash.new { |hash, key| hash[key] = [] }
scores['Rahul'] #=> [] <- a fresh and empty array
```
You can now extract the values from the log and add it to the respective key's value. I'm using [`scan`](http://ruby-doc.org/core-2.5.0/String.html#method-i-scan) with a block: (using the pattern from [mudasobwa's answer](https://stackoverflow.com/a/49273850/477037))
```
log = 'Rahul has 273 Rahul has 217 John has 202 Coventry has 194'
log.scan(/(\w+) has (\d+)/) { |name, score| scores[name] << score.to_i }
scores #=> {"Rahul"=>[273, 217], "John"=>[202], "Coventry"=>[194]}
```
Although not required, I've converted each score to an integer before adding it to the array.
Upvotes: 2 [selected_answer]
|
2018/03/14
| 456 | 1,614 |
<issue_start>username_0: I'm trying to make a recursive function by using os.listdir(), and I am having troble looping to all my directories and list out all the files and directories.
I know it's better using os.tree() for solving this kind of problem, but i want to see how to solve this by using os.listdir().
Here are my current code:
```
#!/bin/usr/py
from os.path import abspath
from os.path import isfile, isdir
import os
import sys
dir = sys.argv[1]
def recursive(dir):
files = os.listdir(dir)
for obj in files:
if isfile(obj):
print obj
elif isdir(obj):
print obj
recursive(abspath(obj))
#no idea why this won't work???
recursive(dir)
```<issue_comment>username_1: Your issue comes from `abspath(obj)`, try replacing it by `os.path.join(dir, obj)` to have real path to your obj (I tested it on my env)
Upvotes: 3 [selected_answer]<issue_comment>username_2: Thanks Gabriel and Emilrn ! this was exactly what I was looking for to recursively get the list of files from a parent directory provided for one of my projects. Just leaving the updated code here for someone who needs it later.
```
#!/bin/usr/py
import os
import sys
dir = sys.argv[1]
def recursive(dir):
files = os.listdir(dir)
for obj in files:
if os.path.isfile(os.path.join(dir,obj)):
print ("File : "+os.path.join(dir,obj))
elif os.path.isdir(os.path.join(dir,obj)):
recursive(os.path.join(dir, obj))
else:
print ('Not a directory or file %s' % (os.path.join(dir, obj))
recursive(dir)
```
Upvotes: 1
|
2018/03/14
| 313 | 990 |
<issue_start>username_0: In the controller I add a (numerical) value to the controller:
```
this.myValue = Number(elem.toFixed(2));
```
I put it inside an input form:
```
```
the value is correct, everything is shown as expected on the screen but I got this warning message in console:
>
> The specified value "{{$ctrl.myValue}}" is not a valid number. The
> value must match to the following regular expression:
> -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?
>
>
>
Any ideas how to get rid of it?<issue_comment>username_1: As suggested by [<NAME>](https://stackoverflow.com/users/8495123/aleksey-solovey), if `value` is changed to an `ng-model` and curly brackets are replaced by quotes the warning message disappear in this case.
```
```
Upvotes: 0 <issue_comment>username_2: Use
```
$scope.myValue = 0;
```
in the controller to initialize the variable.and then use it as -
```
```
Then you can access it anywhere in the controller using $scope.myValue.
Upvotes: 1
|
2018/03/14
| 1,910 | 7,503 |
<issue_start>username_0: I'm new to swift and trying to figure out the best way to store user defaults. Here are my 3 initial VC classes of my app where i pass data from the on boarding view, to the start your plan view, to the user info (profile view) - which is where i need to store defaults for users. My issue is - the only user default that is storing is "name" and "monthly" pay seems to work as well. But the "daily budget default" and "daily savings default" (which are doubles) don't seem to store and appear on the 3rd screen, (users profile). I am not getting the correct reference.
**1st snippet** of code is from the on boarding view controller where i collect their info - to keep things short I'm only showing the calculateData IBAction. As of now - this is where i am trying to grab their user defaults.
**2nd VC** of info is the view directly after on boarding, where the user can review their info - once they press start from this VC- i create an new user object (should i just create an array of new User objects and store it under NSUserDefaults here?)
**3rd VC** - this is the actual user profile, where i need all of the user defaults to show. I am going to set this as the initial view controller & set up in app delegate, to load this page first if a user has previously done the on boarding screen.
Please and thank you for any help!
```
import UIKit
class ViewController: UIViewController, UITextFieldDelegate{
@IBAction func calculateDataButtonPressed(_ sender: UIButton) {
customerName = nameTextField.text!
if let payTotal = Double(monthlyAmountTextField.text!){
monthlyEarning = payTotal
}
if let savingsNumber = Double(desiredSavingsTextField.text!){
desiredSavingsAmount = savingsNumber
}
else {
displayLabel.text = "Enter input as so: 1299.39"
}
budgetForEachDay = ((monthlyEarning - desiredSavingsAmount) / 4.0) / 7.0
savingsForEachDay = (desiredSavingsAmount / 4.0) / 7.0
UserDefaults.standard.set(nameTextField.text, forKey: "name")
UserDefaults.standard.set(monthlyAmountTextField.text, forKey: "monthlyPay")
UserDefaults.standard.set(savingsForEachDay, forKey: "dailySavingsDefault")
UserDefaults.standard.set(budgetForEachDay, forKey: "dailyBudgetDefault")
//THE 4 USER DEFAULTS I NEED TO SAVE
```
Here is the NEXT CLASS THAT THE SEGUE LOADS Too- i create a new User object here - should i perhaps store User Defaults in a newUserObject array instead of how i am trying to go about it ?
```
import UIKit
class StartYourPlanViewController: UIViewController {
var nameFieldPassedOver : String?
var monthlyEarningPassedOver : Double?
var desiredSavingsPassedOver : Double?
var budgetToSpend : Double = 55.3
var saveEachDay : Double = 55.5
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var monthtlyEarningLabel: UILabel!
@IBOutlet weak var desiredSavingsLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.text = nameFieldPassedOver
monthtlyEarningLabel.text = "\(monthlyEarningPassedOver!)"
monthtlyEarningLabel.isHidden = true
desiredSavingsLabel.text = "\(desiredSavingsPassedOver!)"
desiredSavingsLabel.isHidden = true
}
func makeNewUserObject(){
let newUser = UserInfo(name: nameFieldPassedOver!, iWantToSave : desiredSavingsPassedOver!, monthlyIncome: monthlyEarningPassedOver!, budgetEachDay : budgetToSpend, youSaveEachDay : saveEachDay)
newUser.printUserBio()
}
@IBAction func startPlanButtonPressed(_ sender: UIButton) {
makeNewUserObject()
performSegue(withIdentifier: "GoToYourUserInfoView", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "GoToYourUserInfoView"{
let userInfoVC = segue.destination as! UserInfoViewController
userInfoVC.userNamePassedOver = nameFieldPassedOver
userInfoVC.userDailyBudgetPassedOver = budgetToSpend
userInfoVC.userMonthlyEarningsPassedOver = monthlyEarningPassedOver
userInfoVC.userDesiredSavingsPassedOver = desiredSavingsPassedOver
userInfoVC.userDailySavingsPassedOver = saveEachDay
}
}
}
```
AND here will end up being my main and initial VC- where i display the users information for them. I need to Set the default values of user defaults so that they appear on this page everytime an existing user opens the app
```
class UserInfoViewController : ViewController {
var userNamePassedOver : String?
var userDailyBudgetPassedOver : Double?
var userDailySavingsPassedOver : Double?
var userMonthlyEarningsPassedOver : Double?
var userDesiredSavingsPassedOver : Double?
var newAmountPassedBack : Double = 0.0
let monthlyPay = "monthlyPay"
let name = "name"
let dailySavingsDefault = "dailySavingsDefault"
let dailyBudgetDefault = "dailyBudgetDefault"
@IBOutlet weak var dailySavingsNumberLabel: UILabel!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var dailySpendingLimitLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if let name = UserDefaults.standard.value(forKeyPath: name) as? String{
userNameLabel.text = name
}
if let monthlyPay = UserDefaults.standard.value(forKeyPath: monthlyPay) as? String{
userMonthlyEarningsPassedOver = Double(monthlyPay)
}
if let dailySavingsDefault = UserDefaults.standard.value(forKeyPath: dailySavingsDefault) as? String{
dailySavingsNumberLabel.text = dailySavingsDefault
}
if let dailyBudgetDefault = UserDefaults.standard.value(forKeyPath: dailyBudgetDefault) as? String {
dailySpendingLimitLabel.text = dailyBudgetDefault
}
}
```<issue_comment>username_1: When you set the data is `userdefault` after it you have to synchronise your `userdefault` so that `userdefault` saves the pending data. Make sure you won't have any typo mistake with `userdefault` identifier.
Upvotes: 0 <issue_comment>username_2: Initially, You have to archive the objects into NSData then we can save it to the UserDefault and retrieve it from UserDefault when needed.
Example is shown below:-
1) Save object to UserDefault
```
let groups = [Group(id: 1, name: "group1", shortname: "g1"), Group(id: 2, name: "group2", shortname: "g2")]
var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: groups)
userDefaults.set(encodedData, forKey: "groups")
userDefaults.synchronize()
```
2) Retrieve Object from UserDefault
```
let decoded = userDefaults.object(forKey: "groups") as! Data
let decodedGroups = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Group]
```
Upvotes: 3 <issue_comment>username_3: If you want to store structs on UserDefaults:
```
// Save the selected timeZone on UserDefaults
if let encodedCity = try? JSONEncoder().encode(cityAndTimeZone) {
UserDefaults.standard.set(encodedCity, forKey: "cityAndTimeZone")
}
// To restore struct from UserDefaults
if let decodedData = UserDefaults.standard.object(forKey: "cityAndTimeZone") as? Data {
if let cityAndTimeZone = try? JSONDecoder().decode(CityAndTimeZone.self, from: decodedData) {
timezoneLabel.text = cityAndTimeZone.city
}
}
```
Upvotes: 0
|
2018/03/14
| 483 | 1,535 |
<issue_start>username_0: I've got a class which is inside a modal
This is the code:
```
#### Select Theme
Close
Submit
```
With this piece of code:
```
$("#mymdl").modal({
fadeDuration: 1000,
fadeDelay: 1,
closeClass: 'icon-remove',
closeText: 'X'
});
var mymodal1 = $('#mymdl');
mymodal1.find('#modal-data').html("Create");
```
But its not working... Can any one help?<issue_comment>username_1: ```js
$('.modal-content').find('.modal-body').append('append some html here
');
$('.modal-content').find('.modal-body').append('Hi
==
');
```
```html
Open Modal
×
#### Modal Header
Close
```
I think this is what you want. if it is i can explain you
Upvotes: 0 <issue_comment>username_2: Try this
```js
$(document).ready(function() {
$("#mymdl").modal({
fadeDuration: 1000,
fadeDelay: 1,
closeClass: 'icon-remove',
closeText: 'X'
});
var mymodal1 = $('#mymdl');
mymodal1.find('#timezone').html("Hi there");
});
```
```html
#### Select Theme
Close
Submit
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: Your DOM structure is wrong you wrote block element `div` inside `select` element which is invalid. It should be like following:
```
#### Select Theme
Close
Submit
```
Also you should write your code under a specific callback, in this case you should in `show.bs.modal` callback:
```
$('#mymdl').on('show.bs.modal', function (e) {
var mymodal1 = $('#mymdl');
mymodal1.find('#modal-data').html("HI
==
");
})
```
Upvotes: 1
|
2018/03/14
| 1,227 | 4,336 |
<issue_start>username_0: * I run a RancherOS to run docker containers
* I created a container on the GUI to run my databases (image: mysql, name: r-mysql-e4e8df05). Different containers use it.
* I can link other containers to it on the GUI
[](https://i.stack.imgur.com/9tYVq.png)
* This time I would like to automate the creation and starting of a container on jenkins, but the linking is not working well
**My command:**
```
docker run -d --name=app-that-needs-mysql --link mysql:mysql myimages.mycompany.com/appthatneedsmysql
```
I get error:
```
Error response from daemon: Could not get container for mysql
```
**I tried different things:**
1)
```
--link r-mysql-e4e8df05:mysql
```
Error:
```
Cannot link to /r-mysql-e4e8df05, as it does not belong to the default network
```
2)
Try to use `--net` options
Running: `docker network ls`
```
NETWORK ID NAME DRIVER SCOPE
c..........e bridge bridge local
4..........c host host local
c..........a none null local
```
* With `--net none` it succeeds but actually it is not working. The app cannot connect to the DB
* With `--net host` error message `conflicting options: host type networking can't be used with links. This would result in undefined behavior`
* With `--net bridge` error message: `Cannot link to /r-mysql-e4e8df05, as it does not belong to the default network`
I also checked on rancher GUI where this mysql runs:
[](https://i.stack.imgur.com/yQwxN.png)
It get a `continer IP` startin with: 10.X.X.X
I also tried to `add --net managed` but the error: `network managed not found`
I believe I miss understanding something in this docker linking process. **Please give me some idea, how can I make these work.**
(previously it was working when I created the same container and linked to the mysql in the GUI)<issue_comment>username_1: At first glance it seems that Rancher uses a managed network, which `docker network ls` does not show.
### Reproducing the problem
I used dummy alpine containers to reproduce this:
```
# create some network
docker network create your_invisible_network
# run a container belonging to this network
docker container run \
--detach \
--name r-mysql-e4e8df05 \
--net your_invisible_network \
alpine tail -f /dev/null
# trying to link this container
docker container run \
--link r-mysql-e4e8df05:mysql \
alpine ping mysql
```
Indeed I get `docker: Error response from daemon: Cannot link to /r-mysql-e4e8df05, as it does not belong to the default network.`
### Possible Solution
A workaround would be to create a [user-defined bridge network](https://docs.docker.com/network/bridge/) and simpy add your mysql container to it:
```
# create a network
docker network create \
--driver bridge \
a_workaround_network
# connect the mysql to this network (and alias it)
docker network connect \
--alias mysql \
a_workaround_network r-mysql-e4e8df05
# try to ping it using its alias
docker container run \
--net a_workaround_network \
alpine \
ping mysql
# yay!
PING mysql (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: seq=0 ttl=64 time=0.135 ms
64 bytes from 127.0.0.1: seq=1 ttl=64 time=0.084 ms
```
As you can see in the output pinging the mysql container via its DNS name is possible.
### Good to know:
* With a user-created bridge networks DNS resolution works out of the box without having to explicitly `--link` containers :)
* Containers can belong to several networks, this is why this works. In this case the mysql container belongs to both `your_invisible_network` and `a_workaround_network`
I hope this helps!
Upvotes: 1 <issue_comment>username_2: Hey @Tomi you can expose the mysql container on whatever port you like, from rancher. That way you dont have to link the container, then your jenkins spawned container connect to that on the exposed port on the host. You could also use jenkins to spin up the container within rancher, using the rancher cli. Thay way you dont have to surface mysql on the hosts network... a few ways to skin that cat with rancher.
Upvotes: 2
|
2018/03/14
| 1,938 | 5,719 |
<issue_start>username_0: I'm trying to get companies' info from government website and using Scrapy for it.My spider code is the following one.
### Spider code
```
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider
from ..items import CompaniesHouseItem
class SpendolaterSpider(scrapy.Spider):
name = 'spendolater'
allowed_domains = ['beta.companieshouse.gov.uk']
start_url = ['https://beta.companieshouse.gov.uk/company/10511127']
custom_settings = {"DOWNLOAD_DELAY": 1,}
def crawling(self, response):
domain = "https://beta.companieshouse.gov.uk/company/"
for url in response.css("a::attr('href')").extract():
if not url.startswith('https://'):
continue
if domain not in url:
yield scrapy.Request(url, callback=self.parse)
yield scrapy.Request(url, callback=self.parse_dir_contents)
def parse_item(self, response):
for contents in response.xpath('//*[@id="page-container"]'):
item = CompaniesHouseItem()
item["name"] = response.xpath('//*[@id="company-name"]').extract()
item["location"] = response.xpath('//*[@id="content-container"]/dl/dd').extract()
item['foundation'] = response.xpath('//*[@id="company-creation-date"]').extract()
items['type'] = response.xpath('//*[@id="company-type"]').extract()
items['SIC'] = response.xpath('//*[@id="sic0"]').extract()
yield item
```
It doesn't show any error when running but doesn't extract any info.
"Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)" message is shown in command line after running.
"items.py" file is as follows
### items.py
```
import scrapy
class CompaniesHouseItem(scrapy.Item):
name = scrapy.Field()
location = scrapy.Field()
foundation = scrapy.Field()
type = scrapy.Field()
SIC = scrapy.Field()
```
Output is as follows.
### Output
```
2018-03-14 17:51:56 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: companies_house)
2018-03-14 17:51:56 [scrapy.utils.log] INFO: Versions: lxml 4.1.1.0, libxml2 2.9.5, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted 17.9.0, Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)], pyOpenSSL 17.5.0 (OpenSSL 1.1.0g 2 Nov 2017), cryptography 2.1.4, Platform Windows-10-10.0.16299-SP0
2018-03-14 17:51:56 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'companies_house', 'DOWNLOAD_DELAY': 1, 'NEWSPIDER_MODULE': 'companies_house.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['companies_house.spiders']}
2018-03-14 17:51:57 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
'scrapy.extensions.telnet.TelnetConsole',
'scrapy.extensions.logstats.LogStats']
2018-03-14 17:51:57 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
'scrapy.downloadermiddlewares.retry.RetryMiddleware',
'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
'scrapy.downloadermiddlewares.stats.DownloaderStats']
2018-03-14 17:51:57 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
'scrapy.spidermiddlewares.referer.RefererMiddleware',
'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
'scrapy.spidermiddlewares.depth.DepthMiddleware']
2018-03-14 17:51:57 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2018-03-14 17:51:57 [scrapy.core.engine] INFO: Spider opened
2018-03-14 17:51:57 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2018-03-14 17:51:57 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2018-03-14 17:51:57 [scrapy.core.engine] INFO: Closing spider (finished)
2018-03-14 17:51:57 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'finish_reason': 'finished',
'finish_time': datetime.datetime(2018, 3, 14, 8, 51, 57, 239817),
'log_count/DEBUG': 1,
'log_count/INFO': 7,
'start_time': datetime.datetime(2018, 3, 14, 8, 51, 57, 231826)}
2018-03-14 17:51:57 [scrapy.core.engine] INFO: Spider closed (finished)
```
Any advice would be highly appreciated. Thanks in advance.<issue_comment>username_1: Because Scrapy, by default, read the first addresses to scrape in `start_urls` (not `start_url`) and start parsing with `parse` method (not `crawling`). Try a rename operation and relaunch your spider.
Upvotes: 1 <issue_comment>username_2: You dont have `def start_requets(self)` but `start_url` so Scrapy will scrape URLs from list `start_url` and use your callback method `parse`.
I mean, you are missing `def parse(self, response)` change `def crawling(self, response)` to `def parse(self, response)`
Also your code's logic is completely wrong, just think of code's flow before writing it.
Put the page in `start_url` which has company links, listing page i mean
Then create `def parse(self, response)` and create a for loop to iterate over each company link.
Upvotes: 1 [selected_answer]
|
2018/03/14
| 371 | 1,471 |
<issue_start>username_0: I need to create a new object and push it into an array of objects. When i try the code below it instead results in an integer which is the value of the array length.
```
const newThing = Object.assign(
{},
{
__typename: 'Group',
id: groupId,
},
);
// userGroups is an array of strings eg ['1', '2']
const newUserGroups = userGroups
.map(item => {
return Object.assign({}, { __typename: 'Group' }, { id: item });
})
.push( newThing );
console.log(newUserGroups);
```<issue_comment>username_1: Because Scrapy, by default, read the first addresses to scrape in `start_urls` (not `start_url`) and start parsing with `parse` method (not `crawling`). Try a rename operation and relaunch your spider.
Upvotes: 1 <issue_comment>username_2: You dont have `def start_requets(self)` but `start_url` so Scrapy will scrape URLs from list `start_url` and use your callback method `parse`.
I mean, you are missing `def parse(self, response)` change `def crawling(self, response)` to `def parse(self, response)`
Also your code's logic is completely wrong, just think of code's flow before writing it.
Put the page in `start_url` which has company links, listing page i mean
Then create `def parse(self, response)` and create a for loop to iterate over each company link.
Upvotes: 1 [selected_answer]
|
2018/03/14
| 824 | 3,056 |
<issue_start>username_0: I am new on json in C#. I use newtonsoft.json
I have a json file with data (array):
```
[
{
"firstName": "Joyce",
"lastName": "Huff",
"isActive": true,
"age": 59,
"gender": "female",
"eyeColor": "green",
"friends": [
"<NAME>"
]
},
{
"firstName": "Diann",
"lastName": "Patrick",
"isActive": true,
"age": 45,
"gender": "female",
"eyeColor": "blue",
"friends": [
"<NAME>",
"<NAME>"
]
},
{
"firstName": "Holt",
"lastName": "Erickson",
"isActive": false,
"age": 53,
"gender": "male",
"eyeColor": "brown",
"friends": [
"<NAME>",
"<NAME>",
"<NAME>"
]
},
{
"firstName": "Crystal",
"lastName": "Santiago",
"isActive": false,
"age": 31,
"gender": "female",
"eyeColor": "brown",
"friends": [
"<NAME>"
]
}
]
```
How to I read a json file containing array with C# and perform LINQ query on it? I found example on JObject to read json from file but I could not figure it out how do I handle json array. After reading json array, I would like to run query like: select count(\*) from person where age>40;
Please suggest me. Thank you in advance.<issue_comment>username_1: I would suggest creating a Class for the Object you're trying to read, if possible at least.
Then I would deserialize the JSON String to an `List`where T euqals your Modelclass.
```
List deserializedObject = JsonConvert.DeserializeObject(jsonString);
```
Wit this list you can then easily perform LINQ queries like
```
List selectedObjects = deserializedObject.Where(x => x.age > 31);
```
This gives you the object `selectedObjects` with only containing Objects where age > 31.
Upvotes: 2 <issue_comment>username_2: Define model:
```
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public bool isActive { get; set; }
public int age { get; set; }
public string gender { get; set; }
public string eyeColor { get; set; }
public List friends { get; set; }
}
```
[Read](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-read-from-a-text-file) and [deserialize](https://www.newtonsoft.com/json/help/html/DeserializeCollection.htm) JSON:
```
string json = System.IO.File.ReadAllText("test.json");
var people = Newtonsoft.Json.JsonConvert.DeserializeObject>(json);
```
Perform LINQ [query](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/basic-linq-query-operations):
```
var peopleOverForty = from p in people
where p.age > 40
select p;
```
Upvotes: 4 [selected_answer]
|
2018/03/14
| 955 | 2,560 |
<issue_start>username_0: I have a scenario where user can multiselect items and remove them, so I have two arrays:
1. With checkbox values (checked and index)
2. The actual items which need to filter based on checked values index.
here are two arrays and expected result using lodash.
```
const checked = [
{
index: 0,
checked: false
},
{
index: 1,
checked: true //note second index is checked so we need to filter out second index from items array.
},
];
const items = [
{
title: 'This is title 1',
description: 'This is description 1',
end_date: '2018-03-12 14:00:00',
location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
room: 401,
start_date: '2018-03-12 13:00:00',
},
{
title: 'This is title 2',
description: 'This is description 2',
end_date: '2018-03-12 14:00:00',
location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
room: 401,
start_date: '2018-03-12 13:00:00',
}
];
const result = [
{
title: 'This is title 1',
description: 'This is description 1',
end_date: '2018-03-12 14:00:00',
location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
room: 401,
start_date: '2018-03-12 13:00:00',
}
];
```<issue_comment>username_1: You need just to use `filter` function and get the index of the current object. Then using this index access the `n-th` item of the *checked* array (I provide this solution cause from the `checked` array it is visible that your array contains states for all checkboxes - checked and not checked) and check it's `checked` property.
```js
const checked = [
{ index: 0, checked: false },
{ index: 1, checked: true }
];
const items = [
{
title: 'This is title 1',
description: 'This is description 1',
end_date: '2018-03-12 14:00:00',
location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
room: 401,
start_date: '2018-03-12 13:00:00',
},
{
title: 'This is title 2',
description: 'This is description 2',
end_date: '2018-03-12 14:00:00',
location: '3577 Rue de Bullion, Montréal, QC H2X 3A1, Canada',
room: 401,
start_date: '2018-03-12 13:00:00',
}
];
const filtered = items.filter((item, index) => !checked[index].checked);
console.log(filtered);
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: You can simply do this.
```
var result=[];
checked.forEach(function (item) {
if(item.checked)
{
result.push(items[item.index]);
}
})
console.log(result);
```
Upvotes: 0
|
2018/03/14
| 908 | 2,705 |
<issue_start>username_0: I have JSON array like this
```
var array= [{id:1,name:'foo'},{id:2,name:'bar'}]
```
I would like to add a new key (eg:`isApproved`) to each object in the existing array
expected output:
```
var array= [{id:1,name:'foo',isApproved:true},{id:2,name:'bar',isApproved:true}]
```
I used the map function to achieve this
```
array.map(function(e,index){
e.isApproved[index]= true
}
```
But this not worked for me<issue_comment>username_1: You were really close. You do not need the index here. The map passes through every element of the array, so 'e' will be each object in your array.
```js
var array= [{id:1,name:'foo'},{id:2,name:'bar'}];
array.map(function(e){
e.isApproved = true;
});
console.log(array);
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: Try this, you don't need the index:
```js
var array= [{id:1,name:'foo'},{id:2,name:'bar'}];
array.map(value => value.isApproved = true);
console.log(array)
```
Upvotes: 2 <issue_comment>username_3: `e[index]` doesn't make sense since this `index` is meant for the `array` you are iterating.
Set the property directly to `e`
```
array.map(function(e,index){
e.isApproved = true;
}
```
Upvotes: 0 <issue_comment>username_4: With this code, you wont mutate objects inside your array
```
const arr = [{id:1,name:'foo'},{id:2,name:'bar'}];
const mapped = arr.map(element => Object.assign(element, {isApproved: true})
```
More new approach would be using spread operator:
```
const arr = [{id:1,name:'foo'},{id:2,name:'bar'}];
const mapped = arr.map(element => ({isApproved: true ,...element}))
```
Snippet
```js
const arr = [{id:1,name:'foo'},{id:2,name:'bar'}];
const mapped = arr.map(element => ({isApproved: true ,...element}))
console.log(mapped)
```
Upvotes: 3 <issue_comment>username_5: ```
var array= [{id:1,name:'foo'},{id:2,name:'bar'}]
array.forEach(function(e,index){
e.isApproved= true;
})
console.log(array);
```
You can use forEach instead of map.
Upvotes: 0 <issue_comment>username_6: Use the actual item 'e' in the map
Map also gives you the facility to alter each element and return them in a new array. This can be useful if you do not want your current array to alter its state rather you need a modified form of the same array.
check this code:
```
var array= [{id:1,name:'foo'},{id:2,name:'bar'}];
var modifiedArray = array.map(function(e,index){
return Object.assign({isApproved:true},e);
});
console.log(array);
console.log(modifiedArray);
```
Output:
```
//array
[{id: 1, name: "foo"},
{id: 2, name: "bar"}]
//modifiedArray
[{isApproved: true, id: 1, name: "foo"},
{isApproved: true, id: 2, name: "bar"}]
```
Upvotes: 2
|
2018/03/14
| 1,696 | 4,913 |
<issue_start>username_0: I need to make a POST-request in android. Before I tried it in Postman and it works fine.
[](https://i.stack.imgur.com/1ho2z.png)
But in Android (I'm using Retrofit2) it don't want to connect with server.
**My ApiService:**
```
@POST("home/info/")
Call getJson(@Body Post post);
```
**My RetrofitClient:**
```
Retrofit.Builder()
.baseUrl(http://api.beauty.dikidi.ru/)
.addConverterFactory(GsonConverterFactory.create())
.build();
```
**My Post body class**
```
private String city_id;
public String getCity_id() {
return city_id;
}
public void setCity_id(String city_id) {
this.city_id = city_id;
}
```
I tried different solutions: @Query, @Field. I tried to play with URL like [here](https://stackoverflow.com/a/35036515/7092611). My breakepoint in `OnResponse` is not reached. Please, help me to set up connection!
**Logs from Interceptor**
```
D/OkHttp: <-- 200 OK http://api.beauty.dikidi.ru/home/info/ (474ms)
Server: nginx
Date: Wed, 14 Mar 2018 09:56:27 GMT
Content-Type: application/json; charset="utf-8"
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Set-Cookie: lang=208f1b939dfd656bcfad0eac6c66f41806155878%7Eru; path=/; domain=.dikidi.ru; HttpOnly
03-14 09:56:25.913 5997-6029/example.TestProject D/OkHttp:
Expires: Mon, 26 Jul 1990 05:00:00 GMT
Last-Modified: Wed, 14 Mar 2018 09:56:27 GMT
Cache-Control: no-store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie:
cookie_name=3b9f5f43b88487ff1e44e0f6da790f25a8913101%7E5aa8f1cb5b7c31-
92789521; expires=Thu, 15-Mar-2018 09:56:27 GMT; Max-Age=86400; path=/;
domain=.dikidi.ru; HttpOnly
03-14 09:56:25.914 5997-6029/maxzonov.modersoft_testproject D/OkHttp: {"error":{"code":1,"message":"\u041e\u0448\u0438\u0431\u043a\u0430. city_id - \u043e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u044b\u0439 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440!"},"data":[]}
```
It shows that connection is OK but parametres are passing incorrectly.
>
> The problem with passing parametres was resolved. Now code inside in Retrofit is not called.
>
>
>
**Call snippet:**
```
ApiService apiService = RetrofitClient.getApiService();
Call call = apiService.getJson(CITY\_ID);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
int status = response.code();
String count = response.body().getData().getBlock().getShare().getCount();
Log.d("myLog", count);
getViewState().showShare(count);
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
```<issue_comment>username_1: Here is some steps for call post request in retrofit.
Make http request with retrofit.
```
public IWebInterface serviceCallApi() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(Constants.Web.CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(Constants.Web.CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(Constants.Web.CONNECTION_TIMEOUT, TimeUnit.SECONDS);
builder.addInterceptor(logging);
OkHttpClient client = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(add_your_base_url)
.client(client)
.addConverterFactory(JacksonConverterFactory.create())
.build();
return retrofit.create(IWebInterface .class);
}
```
Create interface which will append request parameter
```
public interface IWebInterface {
@POST("home/info/")
@FormUrlEncoded
Call getJson(@Field("city\_id") String title);
}
```
Now you already created model. fill this model as a body to your retrofit call
```
public boolean callApi(){
boolean isSuccess = false;
Call call = serviceCallApi.getJson(pass\_your\_city);
try {
Response response= call.execute();
if (response.code() == 200) {
ResponseData responseParser = response.body();
if (responseParser != null) {
isSuccess = true;
}
}
} catch (IOException e) {
Log.e("Exception", e.getMessage());
}
}
return isSuccess;
```
}
your model :
```
public class Post {
@SerializedName("city_id")
@Expose
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
```
here is the steps i did in my project for call POST retrofit.
Hope it will help you!!
Upvotes: 0 <issue_comment>username_2: Try this
```
@POST("home/info/{city_id}")
Call getData(@Path("city\_id") int cityId);
```
Upvotes: 1
|
2018/03/14
| 599 | 2,379 |
<issue_start>username_0: I know how to call instance method and class method.
I am a little bit confused that how to call below method from another class or method because it returns the string.
```
+ (NSString *)contentTypeForImageData:(NSData *)data;
```<issue_comment>username_1: Here is some steps for call post request in retrofit.
Make http request with retrofit.
```
public IWebInterface serviceCallApi() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(Constants.Web.CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(Constants.Web.CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(Constants.Web.CONNECTION_TIMEOUT, TimeUnit.SECONDS);
builder.addInterceptor(logging);
OkHttpClient client = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(add_your_base_url)
.client(client)
.addConverterFactory(JacksonConverterFactory.create())
.build();
return retrofit.create(IWebInterface .class);
}
```
Create interface which will append request parameter
```
public interface IWebInterface {
@POST("home/info/")
@FormUrlEncoded
Call getJson(@Field("city\_id") String title);
}
```
Now you already created model. fill this model as a body to your retrofit call
```
public boolean callApi(){
boolean isSuccess = false;
Call call = serviceCallApi.getJson(pass\_your\_city);
try {
Response response= call.execute();
if (response.code() == 200) {
ResponseData responseParser = response.body();
if (responseParser != null) {
isSuccess = true;
}
}
} catch (IOException e) {
Log.e("Exception", e.getMessage());
}
}
return isSuccess;
```
}
your model :
```
public class Post {
@SerializedName("city_id")
@Expose
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
```
here is the steps i did in my project for call POST retrofit.
Hope it will help you!!
Upvotes: 0 <issue_comment>username_2: Try this
```
@POST("home/info/{city_id}")
Call getData(@Path("city\_id") int cityId);
```
Upvotes: 1
|
2018/03/14
| 573 | 2,024 |
<issue_start>username_0: I have Rails API app. And 99% of the routes are JSON routes. however, I want to add one single route that will response with HTML. How can I do that?
This is my current setup and when I browse the route I see a string of HTML tags on the screen.
```
class ApplicationController < ActionController::API
include ActionController::MimeResponds
end
class DocumentPublicController < ApplicationController
respond_to :html
def show
html = "Holololo
========
"#, :content_type => 'text/html'
respond_to do |format|
format.html {render html: html, :content_type => 'text/html'}
end
end
end
```
Any ideas?<issue_comment>username_1: Most new APIs only need to serve JSON, yet it is common to see `respond_to` in API controllers. Here is an example:
```
def show
html = "Holololo
========
"
respond_to do |format|
format.html { render :json => html }
end
end
```
We can drop the `respond_to`, but if you hit the url without .json you’ll see it thinking you’re using HTML in the logs
```
Processing by PeopleController#index as HTML
```
If you want your route to respond as HTML, you can default that in the route to HTML
```
namespace :api, :defaults => {:format => :html} do
namespace :v1 do
resources :people
end
end
```
So you can drop the `respond_to` and let it have its curse, then default your route to take effect as HTML.
Upvotes: 0 <issue_comment>username_2: According to the [Layouts and Rendering Guide](http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-html):
>
> When using html: option, HTML entities will be escaped if the string is not marked as HTML safe by using html\_safe method.
>
>
>
So you just need to tell it the string is safe to render as html:
```
# modified this line, though could be done in the actual render call as well
html = "Holololo
========
".html_safe
respond_to do |format|
format.html {render html: html, :content_type => 'text/html'}
end
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 603 | 2,102 |
<issue_start>username_0: I searched on the web and didn't find any good answer for my problem. So this is my question:
I am using OpenCV and have a function called `replaceInvalidDisparties` and I have to search through the pixels and check if the actual value is `inf` and there is a standard function in `OpenCv` called `cvIsInf(double value)` to check if the value is `inf`, but somehow i always get segmentation fault.
```
using namespace cv;
cv::Mat replaceInvalidDisparities(const cv::Mat &original_disp)
{
cv::Mat output = orignal_disp.clone();
//access pixel
for(int i = 0; i< output.rows; i++)
{
for(int j=0; j(i,j));
}
}
}
```
But somehow it always give me a segmentation fault. Does anyone know the problem?<issue_comment>username_1: Most new APIs only need to serve JSON, yet it is common to see `respond_to` in API controllers. Here is an example:
```
def show
html = "Holololo
========
"
respond_to do |format|
format.html { render :json => html }
end
end
```
We can drop the `respond_to`, but if you hit the url without .json you’ll see it thinking you’re using HTML in the logs
```
Processing by PeopleController#index as HTML
```
If you want your route to respond as HTML, you can default that in the route to HTML
```
namespace :api, :defaults => {:format => :html} do
namespace :v1 do
resources :people
end
end
```
So you can drop the `respond_to` and let it have its curse, then default your route to take effect as HTML.
Upvotes: 0 <issue_comment>username_2: According to the [Layouts and Rendering Guide](http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-html):
>
> When using html: option, HTML entities will be escaped if the string is not marked as HTML safe by using html\_safe method.
>
>
>
So you just need to tell it the string is safe to render as html:
```
# modified this line, though could be done in the actual render call as well
html = "Holololo
========
".html_safe
respond_to do |format|
format.html {render html: html, :content_type => 'text/html'}
end
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 624 | 2,353 |
<issue_start>username_0: I have seen this issue in many sites such as the [Facebook Registration](https://www.facebook.com/)
Birthday dropdown lists or even [WebAim Accessible Forms](https://webaim.org/techniques/forms/controls). The problem is the following:
By using the screen reader I focus on a drop down list and select an element. After that, I try to leave the drop down element and move focus on the next element (by ctrl + alt + right arrow in VoiceOver or by Swiping right on Android). When I do this, instead of the focus moving to the next element, the screen reader announces the next element in the drop down list(although I have selected it and the list is now closed) and not the next element after the drop down list. This results in me getting stuck there and not being able to continue.
* Am I doing something wrong there while controlling the screen reader?
* Is there something that could change in the code of the sites I mentioned in order for this to be resolved?<issue_comment>username_1: Most new APIs only need to serve JSON, yet it is common to see `respond_to` in API controllers. Here is an example:
```
def show
html = "Holololo
========
"
respond_to do |format|
format.html { render :json => html }
end
end
```
We can drop the `respond_to`, but if you hit the url without .json you’ll see it thinking you’re using HTML in the logs
```
Processing by PeopleController#index as HTML
```
If you want your route to respond as HTML, you can default that in the route to HTML
```
namespace :api, :defaults => {:format => :html} do
namespace :v1 do
resources :people
end
end
```
So you can drop the `respond_to` and let it have its curse, then default your route to take effect as HTML.
Upvotes: 0 <issue_comment>username_2: According to the [Layouts and Rendering Guide](http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-html):
>
> When using html: option, HTML entities will be escaped if the string is not marked as HTML safe by using html\_safe method.
>
>
>
So you just need to tell it the string is safe to render as html:
```
# modified this line, though could be done in the actual render call as well
html = "Holololo
========
".html_safe
respond_to do |format|
format.html {render html: html, :content_type => 'text/html'}
end
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 1,265 | 4,897 |
<issue_start>username_0: I am trying to check if a username exists or not before the form that will trigger the insertion of a new username is submitted, so that I can notify the user of the availability (or not) of the username she has selected.
But my code doesn't works. Where is the problem? Here is my code:
```
php
$servername = "localhost";
$username = "zprestau01u";
$password = "<PASSWORD>";
$dbname = "zprestau01";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn-connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$username=$_POST['Name'];
$email = $_POST['Email'];
$password = $_POST['<PASSWORD>'];
//Query statement with placeholder
$query = "SELECT Name
FROM demotable
WHERE demotable.Name = '$username'";
//Put the parameters in an array
$params = array($username);
//Execute it
try {
$stmt = $conn->prepare($query);
$result = $stmt->execute($params);
} catch(PDOException $ex) {
echo $ex->getMessage());
}
//Now Check for the row count
if($stmt->rowCount > 0) {
echo "Account Exists";
} else{
$sql = "INSERT INTO demotable(Name,Email,Password) VALUES ('$username','$email','$password')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
}
$conn->close();
?>
```
N.B: At the same time I am trying to insert username in MySQL if it is
not existed.<issue_comment>username_1: The first thing is to add a security layer at a database level, to prevent the insertion of duplicated usernames. Assuming `Name` column corresponds to username, you need to configure your SQL database to understand Name as a unique key:
```
ALTER TABLE Demotable ADD UNIQUE (Name);
```
In this way, if you try to insert a row with an existing name, an exception will be created and the row with the duplicated username will not be inserted.
Checking before the form is submitted is a nice improvement on top of that. If you're trying to check the availability of a username before the form is submitted, for UX and user information purposes, then a good solution may be to use AJAX integrated within your PHP code. There is a [nice explanation](http://makitweb.com/check-username-availability-with-jquery-and-ajax/) elsewhere that you may want to check.
Though a lot of code is provided, you may pay special attention to the actual AJAX query and adapt it to your needs and those of your project. Using jQuery to make the ajax call it would look like this:
```
$(document).ready(function(){
$("#txt\_uname").keyup(function(){
var uname = $("#txt\_uname").val().trim();
if(uname != ''){
$("#uname\_response").show();
$.ajax({
url: 'uname\_check.php',
type: 'post',
data: {uname:uname},
success: function(response){
if(response > 0){
$("#uname\_response").html("<span class='not-exists'>\* Username Already in use.</span>");
}else{
$("#uname\_response").html("<span class='exists'>Available.</span>");
}
}
});
}else{
$("#uname\_response").hide();
}
});
});
```
Upvotes: 2 <issue_comment>username_2: If you want to check before submitting the form you can go for ajax only.check after click the submit button this will work you can try this out.
```
php
$servername = "xxxxxxxxx";
$username = "xxxxxxxxxx";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn-connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])) {
$username=$_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
//Query statement with placeholder
$query = "SELECT fname
FROM person
WHERE fname = '$username'";
// Execute it
try {
$stmt = $conn->prepare($query);
//for you no need to pass parameter inside execute statement
$result = $stmt->execute();
//After executing the query store the result like below
$stmt->store_result();
} catch(PDOException $ex) {
echo $ex->getMessage();
}
//Now Check for the row count
//you have to check numrows >0 like this
if($stmt->num_rows>0) {
echo "Account Exists";
die;
} else {
$sql = "INSERT INTO person(username,email,password) VALUES ('$username','$email','$password')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
}
}
$conn->close();
?>
```
Upvotes: 1 [selected_answer]
|
2018/03/14
| 716 | 2,235 |
<issue_start>username_0: Getting error `error: expression must have arithmetic or pointer type` in following code snippet. Not sure whats going wrong.
```
struct structX
{
union {
structA varA; /* structA is a structure */
structB varB; /* structB is a structure */
} unionX;
#define xa unionX.varA
#define xb unionX.varB
}
void foo(structX **sxpp) {
structX *sxp = *sxpp;
/* i want to do null check for xb */
if (sxp-> xb) /* error: expression must have arithmetic or pointer type */
{
...
}
}
```
I tried to deference the pointer as well, something like this, but no success.
```
if ((**sxpp).xb)
```<issue_comment>username_1: The problem in the below statement
```
structX *sxp = *sxpp;
```
It should be `struct structX *sxp = *sxpp;`
Or first `typedef` the structure as
```
typedef struct structX
{
union {
/* make sure below structure are typedefed above */
structA varA; /* structA is a structure */
structB varB; /* structB is a structure */
} unionX;
}structX;
```
And then create the variable as
```
structX *sxp = *sxpp;
```
Modify the `foo` function accordingly
```
void foo(structX **sxpp) { ... } /* if typedefed */
```
or
```
void foo(struct structX **sxpp) { ... } /* if not typedefed
```
**Edit** : Since your question doesn't explain about `structA` and `structB`. lets say `structB` looks like
```
typedef struct struct_b {
int y;
}structB;
```
the code block
```
if (sxp->xb) {
...
}
```
should be below one if you want to check whether member of `structB` is `NULL` or not
```
if (sxp->xb.y) { /* let say y is data member of structB */
...
}
```
Upvotes: 0 <issue_comment>username_2: In this statement:
```
if (sxp-> xb) { ... }
```
you are trying to evaluate a struct (`sxp->unionX.varB`) as either true or false. Your compiler is trying to tell you that this won't work. The expression inside an `if()` statement must either be an arithmetic value (e.g., `if (i < 10)`, where `i < 10` evaluates to 0 or 1), or a pointer (e.g., `f = fopen("a.txt", "r"); if (f) { ... }`).
You can't evaluate a struct in this way. Did you perhaps mean to check the value of an element of `varB` inside this union?
Upvotes: 1
|
2018/03/14
| 399 | 1,116 |
<issue_start>username_0: I have a Question. I have a json File this looks like so.
```
[{
"nagelplatten": [
{
"kg" : "1000",
"rabatt" : "3",
"fracht" : ""
}
],
"metalwebs": [
{
"kg" : "1",
"rabatt" : "4",
"fracht" : ""
}
]
}]
```
And my function looks so. So we can i become only "metalwebs"?
```
this.ns.getRabatt().subscribe(res => this.rabatte = res);
```
Thx<issue_comment>username_1: ```
this.ns.getRabatt().subscribe((res : any) => this.rabatte = res[0].metalwebs);
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: If you have array of multiple objects as above and you want to make an array of objects containing ony `metalwebs`
```
this.ns.getRabatt().subscribe(res =>
this.rabatte = Array.from(res,r=>{return {metalwebs:r.metalwebs}});
);
```
this will make your JSON as follow
```
[{
"metalwebs": [
{
"kg" : "1",
"rabatt" : "4",
"fracht" : ""
}
]
},
{
"metalwebs": [
{
"kg" : "2",
"rabatt" : "8",
"fracht" : ""
}
]
}]
```
Upvotes: 0
|
2018/03/14
| 1,262 | 5,240 |
<issue_start>username_0: I am trying to inject the ModelViewFactory object in the ViewModel and I get the following error. Have been working on this for days cant seem to figure it out.
```
public abstract interface MinutemanComponent {
^
com.xyz.minuteman.view.meeting.detail.MeetingItemDetailsViewModel is injected at
com.xyz.minuteman.injection.ViewModelModule.bindMeetingItemDetailsViewModel(meetingItemDetailsViewModel)
java.util.Map,javax.inject.Provider> is injected at
com.xyz.minuteman.injection.ViewModelFactory.(creators)
com.xyz.minuteman.injection.ViewModelFactory is injected at
com.xyz.minuteman.injection.ViewModelModule.bindViewModelFactory(viewModelFactory)
android.arch.lifecycle.ViewModelProvider.Factory is injected at
com.xyz.minuteman.view.meeting.list.MeetingListFragment.viewModelFactory
com.xyz.minuteman.view.meeting.list.MeetingListFragment is injected at
dagger.android.AndroidInjector.inject(arg0)
```
Here is my ViewModelFactory
```
class ViewModelFactory @Inject constructor(
private val creators: Map, @JvmSuppressWildcards Provider>)
: ViewModelProvider.Factory {
@Suppress("UNCHECKED\_CAST")
override fun create(modelClass: Class): T {
var creator: Provider? = creators[modelClass]
if (creator == null) {
for ((key, value) in creators) {
if (modelClass.isAssignableFrom(key)) {
creator = value
break
}
}
}
if (creator == null) throw IllegalArgumentException("unknown model class " + modelClass)
try {
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
```
}
Here is the Fragment where I am trying to inject the viewModelFactory
```
class MeetingListFragment : Fragment(), Injectable {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private lateinit var meetingsListViewModel: MeetingsListViewModel
private lateinit var adapter: MeetingAdapter
private val itemClickListener = View.OnClickListener { v: View ->
val meeting = v.tag as Meeting
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val v = inflater.inflate(R.layout.fragment_list_previous_meetings_layout, container, false)
setupRecyclerView(v)
meetingsListViewModel = ViewModelProviders.of(this, viewModelFactory).get(MeetingsListViewModel::class.java)
meetingsListViewModel!!.getAllMeetings().observe(this, Observer { r ->
if (r != null) {
adapter.setItems(r)
}
})
return v;
}
private fun setupRecyclerView(v: View) {
val recyclerView = v.findViewById(R.id.recyclerview\_meeting\_list)
val layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
recyclerView?.layoutManager = layoutManager
adapter = MeetingAdapter(ArrayList(), recyclerView.context, itemClickListener)
recyclerView?.adapter = adapter
val dividerItemDecoration = DividerItemDecoration(recyclerView?.context,
layoutManager.orientation)
recyclerView?.addItemDecoration(dividerItemDecoration)
}
```
}
Here is the ViewModel Module where I have the Provider methods for the ViewModels
```
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(MeetingsListViewModel::class)
abstract fun bindMeetingsListViewModel(meetingsListViewModel: MeetingsListViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(MeetingItemDetailsViewModel::class)
abstract fun bindMeetingItemDetailsViewModel(meetingItemDetailsViewModel: MeetingItemDetailsViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(AddMeetingViewModel::class)
abstract fun bindAddMeetingViewModel(addMeetingViewModel: AddMeetingViewModel): ViewModel
@Binds
abstract fun bindViewModelFactory(viewModelFactory: ViewModelFactory): ViewModelProvider.Factory
}
```
And here is the FragmentBuilderModule as well
```
@Module
abstract class FragmentBuilderModule {
@ContributesAndroidInjector
abstract fun contributeMeetingListFragment(): MeetingListFragment
}
```
Here is the App Component
```
@Singleton
@Component(modules = [AndroidSupportInjectionModule::class,
ActivityBuilderModule::class,
MinutemanModule::class])
interface MinutemanComponent {
fun inject(minutemanApplication: MinutemanApplication)
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: MinutemanApplication): Builder
fun build(): MinutemanComponent
}
}
```<issue_comment>username_1: It looks like you never use your `ViewModelModule`. Change your `MinutemanComponent` to the following:
```
@Singleton
@Component(modules = [AndroidSupportInjectionModule::class,
ActivityBuilderModule::class, MinutemanModule::class, ViewModelModule::class])
interface MinutemanComponent {
fun inject(minutemanApplication: MinutemanApplication)
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: MinutemanApplication): Builder
fun build(): MinutemanComponent
}
}
```
Upvotes: 0 <issue_comment>username_2: Not all the provided ViewModels in the ViewModelModule had an @Inject on the constructor, I added that to all of them and it solved my problem.
Upvotes: 2
|
2018/03/14
| 1,069 | 3,647 |
<issue_start>username_0: I am running `SpringBoot Application` just checked server logs and got several errors like this. I can't understand what can cause it as the error appears everyday after 12/24 hours.
Tomcat Version running on `8.5.11`
```
2018-03-04 17:03:26 [http-nio-8080-exec-85] INFO o.a.coyote.http11.Http11Processor - Error parsing HTTP request header
Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:421)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:667)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
```<issue_comment>username_1: This may happen because of parsing HTTPS headers instead of HTTP. Try:
1. Adding:
`logging.level.org.springframework.web: trace`
`logging.level.org.apache: trace`
to your application.properties and see what does Spring says to you.
2. Check if there are any scheduled activity at that time which refers to other resource encrypted by SSL. See also: [java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens](https://stackoverflow.com/questions/42218237)
Upvotes: 4 <issue_comment>username_2: I had this error in a Spring Boot 2 (2.0.1.RELEASE) application that was configured to serve HTTPS on port 8443 and redirect port 8080 HTTP traffic to port 8443.
On Microsoft Edge, the application worked as expected, with `http://localhost:8080` redirecting to `https://localhost:8443`. On Chrome 66 however, this would only work once, and then Chrome would complain that "localhost sent an invalid response" (`ERR_SSL_PROTOCOL_ERROR`).
The server log said:
`DEBUG 11440 --- [nio-8080-exec-1] o.a.coyote.http11.Http11InputBuffer: Received [ <> ]
INFO 11440 --- [nio-8080-exec-1] o.apache.coyote.http11.Http11Processor: Error parsing HTTP request header`
It turns out that Chrome was adding `localhost` to its [HSTS list](https://www.thesslstore.com/blog/clear-hsts-settings-chrome-firefox/)
because Spring Boot sent back a `Strict-Transport-Security: max-age=31536000 ; includeSubDomains` header back for
<https://localhost:8443>. So essentially, this issue happened because the client (i.e., browser) was trying to speak HTTPS to an HTTP endpoint.
Adding a `.headers().httpStrictTransportSecurity().disable();` in
`extends WebSecurityConfigurerAdapter.configure` fixed the issue, as noted in [this StackOverflow question](https://stackoverflow.com/questions/49201779/spring-boot-do-not-send-hsts-header).
Upvotes: 2 <issue_comment>username_3: As I have answered in [this similar question](https://stackoverflow.com/a/58696829/1119473), check if you are not accidentally requesting with HTTPS protocol instead of HTTP protocol. If you don't configure SSL on Tomcat and you send HTTPS request, it will result to this weird message..
Upvotes: 3
|
2018/03/14
| 868 | 2,950 |
<issue_start>username_0: I'm having some issues while trying to copy content of a variable into a file:
```
echo "$template" >> "debug.conf"
```
if I check the content of debug.conf it's empty.
$template variable is populated with the following code:
```
template="$(cat /home/scripts/debug-template)"
```
and debug-template file content is:
```
cat debug-template
Enabled=1
OfflReboot=1
HOFailBB=1
OfflineBB=1
AcuPcapSize=20
RngRspBB=1
T4TimeBB=1
MaxBbTarballs=50
MaxPcapTarBalls=100
tcpdump() {
command tcpdump $@ 'udp or tcp'
}
```
the command is executed as a root so there aren't permission issues.
Anyone could help me to figure out what could be causing the problem?
Thanks for your precious help.<issue_comment>username_1: This may happen because of parsing HTTPS headers instead of HTTP. Try:
1. Adding:
`logging.level.org.springframework.web: trace`
`logging.level.org.apache: trace`
to your application.properties and see what does Spring says to you.
2. Check if there are any scheduled activity at that time which refers to other resource encrypted by SSL. See also: [java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens](https://stackoverflow.com/questions/42218237)
Upvotes: 4 <issue_comment>username_2: I had this error in a Spring Boot 2 (2.0.1.RELEASE) application that was configured to serve HTTPS on port 8443 and redirect port 8080 HTTP traffic to port 8443.
On Microsoft Edge, the application worked as expected, with `http://localhost:8080` redirecting to `https://localhost:8443`. On Chrome 66 however, this would only work once, and then Chrome would complain that "localhost sent an invalid response" (`ERR_SSL_PROTOCOL_ERROR`).
The server log said:
`DEBUG 11440 --- [nio-8080-exec-1] o.a.coyote.http11.Http11InputBuffer: Received [ <> ]
INFO 11440 --- [nio-8080-exec-1] o.apache.coyote.http11.Http11Processor: Error parsing HTTP request header`
It turns out that Chrome was adding `localhost` to its [HSTS list](https://www.thesslstore.com/blog/clear-hsts-settings-chrome-firefox/)
because Spring Boot sent back a `Strict-Transport-Security: max-age=31536000 ; includeSubDomains` header back for
<https://localhost:8443>. So essentially, this issue happened because the client (i.e., browser) was trying to speak HTTPS to an HTTP endpoint.
Adding a `.headers().httpStrictTransportSecurity().disable();` in
`extends WebSecurityConfigurerAdapter.configure` fixed the issue, as noted in [this StackOverflow question](https://stackoverflow.com/questions/49201779/spring-boot-do-not-send-hsts-header).
Upvotes: 2 <issue_comment>username_3: As I have answered in [this similar question](https://stackoverflow.com/a/58696829/1119473), check if you are not accidentally requesting with HTTPS protocol instead of HTTP protocol. If you don't configure SSL on Tomcat and you send HTTPS request, it will result to this weird message..
Upvotes: 3
|
2018/03/14
| 1,271 | 3,889 |
<issue_start>username_0: I have 8 logos in black&white version and I would like to prepare a classic hover effect with color version of a single logo.
I am pretty sure that this effect can be done with a few lines of jQuery code but I am not advanced in it.
I just need to change on hover letter in this source from bw to color in both directions (mouseenter/leave).
I figured out this script but for every single logo I need prepare a new "clone" lines:
```
$('#footer-company li').on('mouseleave', function() {
$(this).find('img').attr('src', 'bw-company1.png');
});
$('#footer-company li').on('mouseover', function() {
$(this).find('img').attr('src', 'color-company1.png');
});
```
BW version structure:
```
* 
* 
* 
* 
* 
* 
* 
* 
```
COLOR structure
```
* 
* 
* 
* 
* 
* 
* 
* 
```<issue_comment>username_1: You can use pure CSS [`filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/filter)
```css
.grey {
filter: grayscale(100%);
}
```
```html

```
---
You can persist black-white and color images path in custom `data-` prefix attributes which can be retrieved using `.data(key)` and set value using [`.attr(attributeName, function)`](http://api.jquery.com/attr/#attr-attributeName-function)
*HTML*
```
* 
```
*Script*
```
$('#footer-company li').on('mouseleave', function() {
$(this).find('img').attr('src', function(){
return $(this).data('bw');
});
});
$('#footer-company li').on('mouseover', function() {
$(this).find('img').attr('src', function(){
return $(this).data('color');
});
});
```
Upvotes: 0 <issue_comment>username_2: Here is an idea with **pure CSS** to change the content of the image as I don't think jQuery or JS is needed here:
```css
img:hover {
content:var(--h);
}
```
```html

```
And if you want some transition you can try this:
```css
span {
display: inline-block;
}
img {
vertical-align: top;
transition: 1s;
}
span:hover img {
opacity: 0;
}
```
```html

```
Upvotes: 3 [selected_answer]<issue_comment>username_3: If you're set on using jQuery, I'd recommend looking in to the `.hover()` function : <https://api.jquery.com/hover/>
Then I'd select the image add a CSS grayscale filter on hover. So:
```
$('#footer-company li img').hover(
function() {
$(this).css('filter','grayscale(100%)');
}, function() {
$(this).css('filter','grayscale(0%)');
}
);
```
However, as has been pointed out, you could do this all quite simply with just CSS `:hover` rule: <https://developer.mozilla.org/en-US/docs/Web/CSS/:hover>
Upvotes: 0 <issue_comment>username_4: Maybe try this
```js
$('li').on('mouseenter', function(){
$(this).attr('data-src1', $(this).css('background-image'));
$(this).css('background-image', 'url('+$(this).attr('data-src2')+')');
});
$('li').on('mouseleave', function(){
$(this).css('background-image', $(this).attr('data-src1'));
});
```
```css
li {
background-repeat: no-repeat;
}
```
```html
*
*
*
```
Upvotes: 0 <issue_comment>username_5: Just use the `filter: grayscale` function:
```
img {
-webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */
filter: grayscale(100%);
}
img:hover {
-webkit-filter: grayscale(0%); /* Safari 6.0 - 9.0 */
filter: grayscale(0%);
}
```
**note:** This is not supported in Internet Explorer, Edge 12, or Safari 5.1 and earlier.
Upvotes: 0
|
2018/03/14
| 299 | 1,052 |
<issue_start>username_0: Is there any default keyboard shortcut to close all tabs except the active one? It can be done by right-clicking the tab and choosing `Close Others` but I'd like to do this using only my keyboard.
[](https://i.stack.imgur.com/AVPdH.png)<issue_comment>username_1: It's not possible to access the tab context menu using the keyboard.
There's an [open issue](https://youtrack.jetbrains.com/issue/IDEABKL-6219) against IntelliJ for this.
Their suggestion is to add that action (tab > close others) to a [quick list](https://www.jetbrains.com/help/idea/2017.1/configuring-quick-lists.html) and you can then invoke the quick list action via a keyboard shortcut.
Upvotes: 2 <issue_comment>username_2: `ctrl`+`shift`+`a` and write `Close Others`. Select the one with `Editor Close Actions`.
Or assign it your own shortcut.
Open `Settings` > `Keymap`. Search for `Close others` (or find it under `Main menu` > `Window` > `Editor tabs`.
Upvotes: 4 [selected_answer]
|
2018/03/14
| 293 | 1,136 |
<issue_start>username_0: org.apache.commons.cli has interface like this:
`public Option.Builder type(Class type)`
Sets the type of the Option.
Parameters:
```
type - the type of the Option
```
Returns:
```
this builder, to allow method chaining
```
If I want to build an option with type "int", how should I call this function?<issue_comment>username_1: It seems you are asking how to express the Class of int.
Try `int.class`.
Upvotes: 2 <issue_comment>username_2: You need to use `Number.class` for `int` or `Integer`.
So just to give you an idea:
```
Options options = new Options();
options.addOption(
OptionBuilder.withDescription("description")
...
.withType(Number.class)
...
.create());
```
Upvotes: 2 <issue_comment>username_3: Try using this:
```
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("integer-option")
.withDescription("description")
.withType(Number.class)
.hasArg()
.withArgName("argname")
.create());
```
Upvotes: 2
|
2018/03/14
| 329 | 1,383 |
<issue_start>username_0: So I'm making a chat app. I use ajax to check for new entry(message) in database every 0.5sec. If there is then display the message. Is that too much to ask the server? Im using a cheap shared hosting service. From my experience so far, half the time message is fast and smooth, the other time, especially during peak time, messages disappear and the ajax request fail half the time. Sometimes even connection to database itself comes back fail. I want to know if its me asking too much from the server or my server is bad I should consider changing. (or both)<issue_comment>username_1: It seems you are asking how to express the Class of int.
Try `int.class`.
Upvotes: 2 <issue_comment>username_2: You need to use `Number.class` for `int` or `Integer`.
So just to give you an idea:
```
Options options = new Options();
options.addOption(
OptionBuilder.withDescription("description")
...
.withType(Number.class)
...
.create());
```
Upvotes: 2 <issue_comment>username_3: Try using this:
```
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("integer-option")
.withDescription("description")
.withType(Number.class)
.hasArg()
.withArgName("argname")
.create());
```
Upvotes: 2
|
2018/03/14
| 2,145 | 7,061 |
<issue_start>username_0: this is my android code when we run application and it is automatically close when login method is call on the clicking of the button
>
> FATAL EXCEPTION: main Process: soubhagya.hostinger, PID: 25611
> java.lang.IllegalStateException: Could not execute method for
> android:onClick at
> android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
> at android.view.View.performClick(View.java:5640)
>
> at android.view.View$PerformClick.run(View.java:22455)
>
> at android.os.Handler.handleCallback(Handler.java:751)
>
> at android.os.Handler.dispatchMessage(Handler.java:95)
>
> at android.os.Looper.loop(Looper.java:154)
>
> at android.app.ActivityThread.main(ActivityThread.java:6165)
>
> at java.lang.reflect.Method.invoke(Native Method)
>
> at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
> at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
>
> Caused by: java.lang.reflect.InvocationTargetException
>
> at java.lang.reflect.Method.invoke(Native Method)
>
> at
> android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
> at android.view.View.performClick(View.java:5640)
>
> at android.view.View$PerformClick.run(View.java:22455)
>
> at android.os.Handler.handleCallback(Handler.java:751)
>
> at android.os.Handler.dispatchMessage(Handler.java:95)
>
> at android.os.Looper.loop(Looper.java:154)
>
> at android.app.ActivityThread.main(ActivityThread.java:6165)
>
> at java.lang.reflect.Method.invoke(Native Method)
>
> at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
> at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
>
> Caused by: java.lang.NullPointerException: Attempt to invoke virtual
> method 'android.text.Editable android.widget.EditText.getText()' on a
> null object reference
>
> at soubhagya.hostinger.Login.logIn(Login.java:51)
>
> at soubhagya.hostinger.Login.radhaJi(Login.java:106)
>
> at java.lang.reflect.Method.invoke(Native Method)
>
> at
> android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
> at android.view.View.performClick(View.java:5640)
>
> at android.view.View$PerformClick.run(View.java:22455)
>
> at android.os.Handler.handleCallback(Handler.java:751)
>
> at android.os.Handler.dispatchMessage(Handler.java:95)
>
> at android.os.Looper.loop(Looper.java:154)
>
> at android.app.ActivityThread.main(ActivityThread.java:6165)
>
> at java.lang.reflect.Method.invoke(Native Method)
>
> at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
> at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
>
>
>
Here's the Login activity.
```
public class Login extends AppCompatActivity {
//web url string
public static final String LOGIN_URL="http://abhinavin.000webhostapp.com/userregistration/login.php";
public static final String KEY_EMAIL="email";
public static final String KEY_PASSWORD="<PASSWORD>";
public static final String LOGIN_SUCCESS="success";
public static final String SHARED_PREF_NAME="tech";
public static final String EMAIL_SHARED_PREF ="email";
public static final String LOGGEDIN_SHARED_PREF="loggedin";
private EditText editTextEmail;
private EditText editTextPassword;
private Button btn_SignIn;
private boolean loggedIn=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//this is text fields
editTextEmail=findViewById(R.id.email);
editTextPassword=findViewById(R.id.password);
btn_SignIn=findViewById(R.id.btn_signup);
}
//End of onCreate method
this login method is call on the click of button
private void logIn() {
//error is in this line i think.
//get value of email from edit text
final String email = editTextEmail.getText().toString();
//get value of password from edit text
final String password = editTextPassword.getText().toString();
StringRequest stringRequest=new StringRequest(Request.Method.POST, LOGIN_URL, new Response.Listener() {
//override the onResponse method
@Override
public void onResponse(String response) {
//check condition
if (response.trim().equalsIgnoreCase(LOGIN\_SUCCESS)) {
SharedPreferences sharedPreferences = Login.this.getSharedPreferences(SHARED\_PREF\_NAME, Context.MODE\_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(LOGGEDIN\_SHARED\_PREF, true);
editor.putBoolean(EMAIL\_SHARED\_PREF, Boolean.parseBoolean(email));
editor.commit();
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
} else {
Toast.makeText(Login.this, "Invalid password", Toast.LENGTH\_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
//overridre getParams
@Override
protected Map getParams() throws AuthFailureError {
Map prams=new HashMap<>();
//put the data in map
prams.put(KEY\_EMAIL, email);
prams.put(KEY\_PASSWORD,<PASSWORD>);
//return prams
return prams;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
End of login method
//overtide the onResume method
@Override
protected void onResume() {
super.onResume();
//get SharedPreferences
SharedPreferences sharedPreferences=getSharedPreferences(SHARED\_PREF\_NAME,Context.MODE\_PRIVATE);
loggedIn=sharedPreferences.getBoolean(LOGGEDIN\_SHARED\_PREF ,false);
if(loggedIn)
{
//set Intent object
Intent i=new Intent(Login.this, MainActivity.class);
//StartActivity
startActivity(i);
}
}
//this is onclick function
public void btn\_Click(View view) {
//call login function
logIn();
}
}
```
xml code in this code edit text and button are defined
```
xml version="1.0" encoding="utf-8"?
```
this is my xml code in whis we can design ui of our application<issue_comment>username_1: It seems you are asking how to express the Class of int.
Try `int.class`.
Upvotes: 2 <issue_comment>username_2: You need to use `Number.class` for `int` or `Integer`.
So just to give you an idea:
```
Options options = new Options();
options.addOption(
OptionBuilder.withDescription("description")
...
.withType(Number.class)
...
.create());
```
Upvotes: 2 <issue_comment>username_3: Try using this:
```
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("integer-option")
.withDescription("description")
.withType(Number.class)
.hasArg()
.withArgName("argname")
.create());
```
Upvotes: 2
|
2018/03/14
| 503 | 1,855 |
<issue_start>username_0: After executing the following code to generate a copy of a text file with Python, the `newfile.txt` doesn't have the exact same file size as `oldfile.txt`.
```
with open('oldfile.txt','r') as a, open('newfile.txt','w') as b:
content = a.read()
b.write(content)
```
While `oldfile.txt` has e.g. 667 KB, `newfile.txt` has 681 KB.
Does anyone have an explanation for that?<issue_comment>username_1: I tried on Linux / Ubuntu. It works as expected, the file-size of both files is perfectly equal.
At this point, i guess this behavior does not relate to python, maybe it depends on your filesystem (compression) or operating system.
Upvotes: 0 <issue_comment>username_2: There are various causes.
You are opening a file as text file, so the bytes of file are interpreted (decoded) into python, and than encoded. So there could be changes.
From `open` documentation (<https://docs.python.org/3/library/functions.html#open>):
>
> When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller.
>
>
>
So if the original file were ASCII (e.g. generated in Windows), you will have the `\r` removed. But when writing back the file you can have no more the original `\r` (if you are in Linux or MacOs) or you will have always `\r\n`, if you are on Windows (which it seems the case, because you file increase in size).
Also encoding could change text. E.g. BOM mark could be removed (or added), and potentially (but AFAIK it is not done implicitly), unneeded codes could be removed (you can have some extra code in Unicode, which change the behaviour of nearby codes. One could add more of one of them, but only the last one is effective.
Upvotes: 2 [selected_answer]
|
2018/03/14
| 603 | 2,266 |
<issue_start>username_0: I have to sort 3 arrays using jquery but order of the result should be same
The fist array is for text answers second is for Image answer and third is for Audio answer after sorting all array should be in same order , but It have to sort when question change
```
var Textanswers = plugin.config.randomSort || plugin.config.randomSortAnswers ?
question.a.sort(function () { return (Math.round(Math.random()) - 0.5); }) :
question.a;
var Imageanswer= plugin.config.randomSort || plugin.config.randomSortAnswers ?
question.imga.sort(function () { return (Math.round(Math.random()) - 0.5); }) :
question.imga;
var Audioanswer= plugin.config.randomSort || plugin.config.randomSortAnswers ?
question.auda.sort(function () { return (Math.round(Math.random()) - 0.5); }) :
question.auda;
```<issue_comment>username_1: I tried on Linux / Ubuntu. It works as expected, the file-size of both files is perfectly equal.
At this point, i guess this behavior does not relate to python, maybe it depends on your filesystem (compression) or operating system.
Upvotes: 0 <issue_comment>username_2: There are various causes.
You are opening a file as text file, so the bytes of file are interpreted (decoded) into python, and than encoded. So there could be changes.
From `open` documentation (<https://docs.python.org/3/library/functions.html#open>):
>
> When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller.
>
>
>
So if the original file were ASCII (e.g. generated in Windows), you will have the `\r` removed. But when writing back the file you can have no more the original `\r` (if you are in Linux or MacOs) or you will have always `\r\n`, if you are on Windows (which it seems the case, because you file increase in size).
Also encoding could change text. E.g. BOM mark could be removed (or added), and potentially (but AFAIK it is not done implicitly), unneeded codes could be removed (you can have some extra code in Unicode, which change the behaviour of nearby codes. One could add more of one of them, but only the last one is effective.
Upvotes: 2 [selected_answer]
|
2018/03/14
| 427 | 1,705 |
<issue_start>username_0: I am trying figure out how to listen to event when the user turns on or off the location in the settings. I tried `navigator.geolocation.watchposition` but didn't have much success, since it does not listen to the respective event.<issue_comment>username_1: I tried on Linux / Ubuntu. It works as expected, the file-size of both files is perfectly equal.
At this point, i guess this behavior does not relate to python, maybe it depends on your filesystem (compression) or operating system.
Upvotes: 0 <issue_comment>username_2: There are various causes.
You are opening a file as text file, so the bytes of file are interpreted (decoded) into python, and than encoded. So there could be changes.
From `open` documentation (<https://docs.python.org/3/library/functions.html#open>):
>
> When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller.
>
>
>
So if the original file were ASCII (e.g. generated in Windows), you will have the `\r` removed. But when writing back the file you can have no more the original `\r` (if you are in Linux or MacOs) or you will have always `\r\n`, if you are on Windows (which it seems the case, because you file increase in size).
Also encoding could change text. E.g. BOM mark could be removed (or added), and potentially (but AFAIK it is not done implicitly), unneeded codes could be removed (you can have some extra code in Unicode, which change the behaviour of nearby codes. One could add more of one of them, but only the last one is effective.
Upvotes: 2 [selected_answer]
|
2018/03/14
| 591 | 1,736 |
<issue_start>username_0: I want to loop through the value of objects of an array that has latitude and longitude together as a value (but separated with a comma).
What I want to achieve is to split the latitude and longitude and store them separately like this:
[](https://i.stack.imgur.com/Ka50V.jpg)
This is how my data looks like. The `key` I'm interested in is the `location`:
[](https://i.stack.imgur.com/cXF9j.jpg)<issue_comment>username_1: Just use `split` function on the string and pass the separator, which is `,`. You need to do this for each item in the array.
```
const coordinates = topDeals.map(item => {
const [latitude, longitude] = item.location.split(',');
return { latitude, longitude };
});
```
Example of `split`
```js
const coordinates = '3.213213,5.3556';
const [longitude, latitude] = coordinates.split(',');
console.log(longitude);
console.log(latitude);
```
Upvotes: 2 <issue_comment>username_2: Use `split` and `map`
```
var markerCordinates = topDeals.map( s => {
var location = s.location.split( "," );
return { latitude : +location[0], latitude : +location[1] }
})
```
Upvotes: 1 <issue_comment>username_3: **Try this working demo :**
```js
var jsonObj = [{
"key": "<KEY>",
"location": "4.648580,7.935496"
},{
"key": "jlterokkl",
"location": "14.648580,45.935496"
},{
"key": "weriojsd",
"location": "31.648580,-9.935496"
}];
var arr = [];
for (var i in jsonObj) {
var latlong = jsonObj[i].location.split(",");
arr.push({"latitude": latlong[0],"longitude": latlong[1]})
}
console.log("Array", arr);
```
Upvotes: 1
|
2018/03/14
| 348 | 968 |
<issue_start>username_0: My URL will look something like this :
>
> "/eshop/products/SMART+TV+SAMSUNG+UE55H6500SLXXH+3D/productDetail/ger\_20295028/"
>
>
>
Where product names can keep changing here
`SMART+TV+SAMSUNG+UE55H6500SLXXH+3D` and product id here `ger_20295028`. I tried writing a regex which is wrong.
How can I correct it for the above URL?
Regex:
`.*/products/[^/]*?/productDetail/[^/]*?/([^/].*?)/[^/]*?/([^/]*)(/.*?)*$`<issue_comment>username_1: You use ? (single character) instead of \* (any number) and you also have much more parts at the end than the example you've given. Try something like this
`.*/products/[^/]*/productDetail/[^/]*/`
Upvotes: 1 <issue_comment>username_2: You should read up on quantifiers (the `?` means once or zero times, you are confusing it with `*`). This regex might work for you:
```
/^.*\/products\/[^\/]+\/productDetail\/[^\/]+\/$/
```
Try it online [here](https://regex101.com/r/ckbr1e/1).
Upvotes: 0
|
2018/03/14
| 373 | 1,466 |
<issue_start>username_0: I am getting following error when ii try to run the code I know the error is in the append function I don't know how to handle with escape characters
```
function check()
{
if(usertype==null)
{
alert('please select user type');
}
else
{
$('#registerusers').hide();
if(usertype=='individual')
{
$('#agent').html();
$('#vendor').html();
$('#service').html();
$('#'+usertype).append('Name: Contact Info: Birthday: Login Info: Previous Next ');
$('#'+usertype).removeClass('hid');
}
else if(usertype=='agent')
{
$('#individual').html();
$('#vendor').html();
$('#service').html();
$('#'+usertype).html(' as
---
');
$('#'+usertype).removeClass('hid');
}
alert(usertype);
}
}
```<issue_comment>username_1: You use ? (single character) instead of \* (any number) and you also have much more parts at the end than the example you've given. Try something like this
`.*/products/[^/]*/productDetail/[^/]*/`
Upvotes: 1 <issue_comment>username_2: You should read up on quantifiers (the `?` means once or zero times, you are confusing it with `*`). This regex might work for you:
```
/^.*\/products\/[^\/]+\/productDetail\/[^\/]+\/$/
```
Try it online [here](https://regex101.com/r/ckbr1e/1).
Upvotes: 0
|
2018/03/14
| 1,006 | 3,116 |
<issue_start>username_0: How to convert one var to two var List?
Below is my input variable:
```
val input="[level:1,var1:name,var2:id][level:1,var1:name1,var2:id1][level:2,var1:add1,var2:city]"
```
I want my result should be:
```
val first= List(List("name","name1"),List("add1"))
val second= List(List("id","id1"),List("city"))
```<issue_comment>username_1: First of all, `input` is **not a valid json**
```
val input="[level:1,var1:name,var2:id][level:1,var1:name1,var2:id1][level:2,var1:add1,var2:city]"
```
**You have to make it *valid json RDD*** ( as you are going to use apache spark)
```
val validJsonRdd = sc.parallelize(Seq(input)).flatMap(x => x.replace(",", "\",\"").replace(":", "\":\"").replace("[", "{\"").replace("]", "\"}").replace("}{", "}&{").split("&"))
```
Once you have *valid json rdd, you can easily convert that to `dataframe`* and *then apply the logic you have*
```
import org.apache.spark.sql.functions._
val df = spark.read.json(validJsonRdd)
.groupBy("level")
.agg(collect_list("var1").as("var1"), collect_list("var2").as("var2"))
.select(collect_list("var1").as("var1"), collect_list("var2").as("var2"))
```
You *should get desired output in `dataframe`* as
```
+------------------------------------------------+--------------------------------------------+
|var1 |var2 |
+------------------------------------------------+--------------------------------------------+
|[WrappedArray(name1, name2), WrappedArray(add1)]|[WrappedArray(id1, id2), WrappedArray(city)]|
+------------------------------------------------+--------------------------------------------+
```
And you can *convert the array to list if required*
To get the values as in the question, you can do the following
```
val rdd = df.collect().map(row => (row(0).asInstanceOf[Seq[Seq[String]]], row(1).asInstanceOf[Seq[Seq[String]]]))
val first = rdd(0)._1.map(x => x.toList).toList
//first: List[List[String]] = List(List(name1, name2), List(add1))
val second = rdd(0)._2.map(x => x.toList).toList
//second: List[List[String]] = List(List(id1, id2), List(city))
```
I hope the answer is helpful
Upvotes: 3 [selected_answer]<issue_comment>username_1: `reduceByKey` is the important function to achieve your required output. More explaination on [step by step reduceByKey explanation](https://stackoverflow.com/a/49166009/5880706)
You can do the following
```
val input="[level:1,var1:name1,var2:id1][level:1,var1:name2,var2:id2][level:2,var1:add1,var2:city]"
val groupedrdd = sc.parallelize(Seq(input)).flatMap(_.split("]\\[").map(x => {
val values = x.replace("[", "").replace("]", "").split(",").map(y => y.split(":")(1))
(values(0), (List(values(1)), List(values(2))))
})).reduceByKey((x, y) => (x._1 ::: y._1, x._2 ::: y._2))
val first = groupedrdd.map(x => x._2._1).collect().toList
//first: List[List[String]] = List(List(add1), List(name1, name2))
val second = groupedrdd.map(x => x._2._2).collect().toList
//second: List[List[String]] = List(List(city), List(id1, id2))
```
Upvotes: 2
|
2018/03/14
| 704 | 2,375 |
<issue_start>username_0: I have a project hierarchy like this:
```
file.pro
src/
files.cpp
include/
headers.h
build/
files.o
bin/
finalExecutable
```
What to specify in the `.pro` file so that the Makefile generated by `qmake` takes the `.cpp` files from my `src/` directory and put the executable in the `build` directory?
For the `include` part, I have added `INCLUDEPATH += include/*`, and it seems to work other than the fact that while including any `file.h` I have to write `#include` instead of `#include` .
How to put it in the `.pro` file so that I can include headers like `#include` .
I tried to add `SOURCES += src/*`, but it shows an error:
```
error: No rule to make target 'sourceFiles/*', needed by 'mydialog.o'. Stop.
```
How to go about specifying the `include`, `src` and the `build` directories?<issue_comment>username_1: This should be easy. Just include this in your `.pro` file
```
MOC_DIR = ./build/moc
OBJECTS_DIR = ./build/obj
RCC_DIR = ./build/qrc
UI_DIR = ./build/uic
```
and voilà, the folder `build` and its subdirectories are created as soon as you execute qmake.
Also when you have local includes, you should not use `#include` it should be `#include "localheader.h"`
Upvotes: 2 <issue_comment>username_2: Qmake files that specify build directories as source subdirectories, and that assume that qmake is executed in the source folder, are essentially broken. The recommended way to build any project (even non-Qt projects!) is to do it out of source. I.e.:
```
# suppose the sources are in myproject
mkdir myproject-build
cd myproject-build
qmake ../myproject && make # for qmake projects
cmake ../myproject && make # for cmake projects
../myproject/configure && make # for autotools projects
```
The sensible thing to do, of course, is to hardlink (or copy) all the executables into some common subfolder of the build directory. This requires some more gymnastics. E.g.:
```
EXTRA_BINFILES += $$PWD/src/myproject # target name in src.pro
DESTDIR = $$OUT_PWD/bin
QMAKE_PRE_LINK += $$QMAKE_MKDIR_CMD $$DIR
for(FILE, EXTRA_BINFILES){
QMAKE_POST_LINK += \
$$QMAKE_COPY $$shell_path($$FILE) $$shell_path($$DIR) $$escape_expand(\\n\\t)
}
```
See [this question](https://stackoverflow.com/questions/3984104/qmake-how-to-copy-a-file-to-the-output) for more insight.
Upvotes: 1
|
2018/03/14
| 1,567 | 5,928 |
<issue_start>username_0: I have the application property `APP_ID` that should be randomly generated (UUID) and that should have the same value for the entire Spring Boot application.
What I did was the following: I defined in the `application.properties` file the `APP_ID=${random.uuid}`.
The UUID gets created successfully, however for every property reference `@Value("${APP_ID}")` I will get a different UUID.
Example: In class `Foo` I want to use the `appId`:
```
@Value("${APP_ID}")
private String appId;
```
In class `Bar` I want to use the `appId`, too:
```
@Value("${APP_ID}")
private String appId;
```
However, the `appId` in `Bar` is always different to the `appId` in `Foo`.
I have read in this [thread](https://github.com/spring-projects/spring-boot/issues/7009) that this behavior is the correct one.
What would be proper implementation to always get the same `APP_ID`?<issue_comment>username_1: One way to do it (as suggested by [wilkinsoa](https://github.com/wilkinsona) in [this thread](https://github.com/spring-projects/spring-boot/issues/7009)) is to "bind a single random value into a `@ConfigurationProperties` annotated bean and then use that bean to configure anything else that needed the same value."
This results in an `application.properties` file:
```
app.id=${random.uuid}
```
The configuration properties file is:
```
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String id;
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
}
```
The class using the id:
```
@Component
public class DoStuff {
private AppProperties appProperties;
@Autowired
public DoStuff(AppProperties appProperties) {
this.appProperties = appProperties;
}
}
```
Upvotes: 3 <issue_comment>username_2: You can generate random value as constant for your test.
```
package com.yourdomain.config;
import org.apache.commons.lang3.RandomUtils;
public class TestConfig {
public static final long RANDOM_LONG = RandomUtils.nextLong();
}
```
and then reference it like:
```
integration.test.random.seed=#{T(com.yourdomain.config.TestConfig).RANDOM_LONG}
rabbitmq.queue=queueName_${integration.test.random.seed}
```
Upvotes: 2 <issue_comment>username_3: I think I've found the most simple but harder to document solution.
The issue with using a class to store the value and autowiring is that you still lose the stateful-ness of the environmental variable. If someone makes a mistake and tries to reference it again you could easily run into some errors.
```
@Configuration
public class FileSharingConfiguration {
private final static UUID app_id = UUID.randomUUID();
@PostConstruct
private void init() {
System.setProperty("app.instance-id", app_id.toString());
}
}
```
I wouldn't rely on #{random.uuid} because it makes references stateless, so I generate my own in the program. Then in a post construction sequence you push that value into environmental variables.
This solution is better when you are forced to reference the same property multiple times (e.g: Thymeleaf templates) and they are read at runtime.
A slight disadvantage is that the property won't show up in the config files, unless you initialize them with a default value. So you have to find other ways of documenting it.
The major disadvantage still is that there's no guarantee that @Value("...") will initialize after you've set the environmental property. The Autowiring solution overcomes this problem by forcing the initialization order. But with this one you only need
```
@Autowired
private AppConfig config;
```
to cause them to be initialized after, you could also use @DependsOn and you don't need to use a getter.
In my opinion there needs to be a better way to do this, random properties being stateless makes them impractical for anything other than testing. But they certainly don't want doing it considering they have created so many workarounds for assigning and reading back random port numbers.
Upvotes: 2 <issue_comment>username_4: You can put system property directly in properties file if it is not set.
The following code:
1. Checks for `APP_UUID` system prop.
2. If `APP_UUID` is not set, sets random `UUID` to `APP_UUID` system prop, and sets the same value to `APP_ID` spring prop.
3. If `APP_UUID` is set, uses this value for `APP_ID` spring prop.
Code (for YAML format. For .properties format "" marks should be omitted):
```
APP_ID: "#{systemProperties['APP_UUID'] = (systemProperties['APP_UUID'] ?: '${random.uuid}') }"
```
Note: System prop can have same name as spring prop, so:
```
APP_ID: "#{systemProperties['APP_ID'] = (systemProperties['APP_ID'] ?: '${random.uuid}') }"
```
Upvotes: 2 <issue_comment>username_5: You can inject directly a UUID to your .properties file:
```
service.uuid=#{T(java.util.UUID).randomUUID().toString()}
```
This technique can be used on environments without Spring Boot.
Upvotes: 2 <issue_comment>username_6: After trying different Methods this was the one working in all cases.
```
public static void main(String[] args) {
System.setProperty("APP_UUID", UUID.randomUUID().toString());
SpringApplication app = new SpringApplication(Restdemo1Application.class);
}
```
Then reference it in the config
```
info:
app:
uuid: ${APP_UUID}
spring:
cloud:
stream:
binders:
solace-broker:
environment:
solace:
java:
client-name: ${info.app.name:-}/${spring.profiles.active}/${info.app.uuid}
```
The approach with:
```
#{T(com.yourdomain.config.TestConfig).RANDOM_LONG}
```
and
```
"#{systemProperties['APP_UUID'] = (systemProperties['APP_UUID'] ?: '${random.uuid}') }"
```
did not work for be because some frameworks (for example spring cloud stream with solace) do not evaluate the custom expressions.
Upvotes: 2
|
2018/03/14
| 2,089 | 7,214 |
<issue_start>username_0: I am looking for a regular expression which matches the pattern src="\*.js", but this should not be enclosed in a comment.
consider the following
```
```
Extended sample input, described by OP as "correct":
```
```
The result should not match line 1 and 2 (where the content is enclosed with comment). It should only match line 3 and 4 (3-end, except comment-end line, for extended sample input).
So far I have this regexp which selects all my .js files but also the ones that are commented out: `(src=\")+(\S)+(.js)`
I am looking for a regex which only selects the script tags with a .js src attribute that are not surrounded by a comment.
I would also like to mention that I am using this regular expression in an Oracle PL SQL query.<issue_comment>username_1: I've put a negative look-ahead before the end of your regex, but mind that if there's a commented part after the `src` it will likewise be ignored.
```
(src=\")+(\S)+(\.js\")+(?!.*-->)(.*)
```
**Edit:**
I managed something similiar without the lookahead (which PL/SQL doesn't have):
```
(src=\")(\S)+(\.js\")[^(--)\n]+(\n|$)
```
Upvotes: 2 <issue_comment>username_2: For e.g. this sample input:
```
```
This regex: `src="[^"]*\.js\">(\s*)*(\s*
)*` is "any number of complete comments, if they do not contain `>` "
- `(<!--[^>]*)?$` is "an optional start of a non-`>` comment at the end of a line"
- `\s*` allowing optional white space
Note, at some point of possible complexity of relevant input, regexes stop being the right tool. Beyond, a dedicated tool, i.e. a parser for XML/html whatever is the choice.
For me that point is reached when the possibility occurs of the relevant input being "hidden" inside a multiline comment. I feel that you turned the question into a moving target, by first confirming that expecting relevant input on one line is allowed (apart from a comment starting afterwards) but then changed the rules, by adding contradicting sample input. At one point you did describe the sample input I proposed as "correct".
The (very funny) XML/regex discussing QA linked in the comments demonstrates the hell you can end up in, if you do not draw the line early enough.
When restricted into a given environment, e.g. SQL server, the special abilities of that environment should be leveraged. Surely processing the non-commented parts of the input by SQL mechanisms to achieve a some steps further goal is possible. I.e. drop your immediate idea of how to proceed and take a little detour in thinking. Try to make sure that you do not exhaust yourself on a XY-problem.
Upvotes: 2 <issue_comment>username_3: Here is my solution : one simple negative lookbehind.
`(?`
This matches all the src attributes in your extended example, but not those preceded by `<!--</code>. It might just be enough, tell me if I missed some specific cases ;)`
Here is my solution running on your extended example : <https://regex101.com/r/rmHkbm/1>
EDIT : This is working in javascript, I don't know for ORACLE PL/SQL. Is there any way to test it without installing an Oracle database ?
Upvotes: 0 <issue_comment>username_4: I don't know if you can do what you want with a single regular expression, especially since Oracle's implementation of regular expressions does not support lookaround. But there are some things you can do with SQL to get around these limitations. The following will extract the matches for the pattern, first by removing comments from the text, then by matching the patter `src=".*\.js"` in what remains. Multiple results are retrieved using `CONNECT BY`:
```
SELECT html_id, REGEXP_SUBSTR(clean_html, 'src=".*\.js"', 1, LEVEL, 'i') AS match
FROM (
SELECT html_id, REGEXP_REPLACE(html_text, '', '', 1, 0, 'n') AS clean_html
FROM (
SELECT 1 AS html_id, '
' AS html_text
FROM dual
)
)
CONNECT BY REGEXP_SUBSTR(clean_html, 'src=".*\.js"', 1, LEVEL, 'i') IS NOT NULL
AND PRIOR html_id = html_id
AND PRIOR DBMS_RANDOM.VALUE IS NOT NULL;
```
If these results are stored in a table somewhere, then you would do the following:
```
SELECT html_id, REGEXP_SUBSTR(clean_html, 'src=".*\.js"', 1, LEVEL, 'i') AS match
FROM (
SELECT html_id, REGEXP_REPLACE(html_text, '', '', 1, 0, 'n') AS clean_html
FROM mytable
)
CONNECT BY REGEXP_SUBSTR(clean_html, 'src=".*\.js"', 1, LEVEL, 'i') IS NOT NULL
AND PRIOR html_id = html_id
AND PRIOR DBMS_RANDOM.VALUE IS NOT NULL;
```
It seems strange but the final two lines is necessary to avoid duplicate results.
Results as follows:
```
| HTML_ID | MATCH |
+---------+------------------------------------+
| 1 | src="jquery.serialize-object.js" |
| 1 | src="jquery.serialize-object.js" |
| 1 | src="jquery.serialize-object.js" |
| 1 | src="jquery.serialize-object.js" |
| 1 | src="jquery.cookie.js" |
+---------+------------------------------------+
```
[**SQL Fiddle HERE.**](http://sqlfiddle.com/#!4/83826/2/0)
Hope this helps.
**EDIT:** Edited according to my comment below:
```
SELECT html_id, REGEXP_SUBSTR(clean_html, 'src="[^"]*\.js"', 1, LEVEL, 'i') AS match
FROM (
SELECT html_id, REGEXP_REPLACE(html_text, '', '', 1, 0, 'n') AS clean_html
FROM (
SELECT 1 AS html_id, '
' AS html_text
FROM dual
)
)
CONNECT BY REGEXP_SUBSTR(clean_html, 'src="[^"]*\.js"', 1, LEVEL, 'i') IS NOT NULL
AND PRIOR html_id = html_id
AND PRIOR DBMS_RANDOM.VALUE IS NOT NULL;
```
**EDITED**
If you're searching a `CLOB` rather than a `CHAR` column, the first line of the `CONNECT BY` clause should look like this. `REGEXP_SUBSTR()` will return a `CLOB` if the relevant column is a `CLOB`, and the comparison just takes forever in this case:
```
CONNECT BY DBMS_LOB.SUBSTR(REGEXP_SUBSTR(clean_html, 'src="[^"]*\.js"', 1, LEVEL, 'i'), 4000, 1) IS NOT NULL
```
Hope this helps.
Upvotes: 3 [selected_answer]<issue_comment>username_5: I don't think it's possible to do what you want using a single regular expression without negative lookaround. But, you can do it by logically combining two similar regular expressions in a way that's easy to do in SQL. The basic idea is:
```
[MATCH_EXPR] AND NOT [COMMENTED_MATCH_EXPR]
```
Assume we have a table `data` with a column `line` (lines of code), we could select the lines of interest with something like:
```
SELECT line
FROM data
WHERE REGEXP_LIKE(line, 'src="[^"]+.js"') AND NOT REGEX_LIKE(line, '<!--.*src="[^"]+.js"');
</code>
```
You can update the regular expressions to be more precise and/or do something more sophisticated with them, e.g. capture the file names, but the approach would be the same.
This approach is not bulletproof in that it would fail to find lines that consist of two
Upvotes: 0 <issue_comment>username_6: I have tried the below on <https://livesql.oracle.com>, so probably will work for you. assuming an uncommented line starts with `'. It matches the lines like`
```
```
query with regular expressions:
```
select "SRC" from "TABLE_1"
where REGEXP_LIKE (SRC, '^\$')
or REGEXP\_LIKE (SRC, '^\\<\!\-\-.+\-\-\>$')
or REGEXP\_LIKE (SRC, '^\$');
```
Upvotes: 0
|
2018/03/14
| 1,065 | 3,862 |
<issue_start>username_0: I want to create some test java files with different sizes (100kb-500kb). In that case I am modifying simple hello world.
**The program will be never executed** so creating objects inside class wont be called.
I'd like to create some constants like in C/C++ language that will be saved in file, not in runtime memory
I am working with midlet library and somehow I cant create static/final variables outside the class.
```
package HelloWorld;
import javax.microedition.midlet.*;
//cant create consts here?
public class HelloWorld extends MIDlet {
public HelloWorld() {
System.out.println("Constructor");
}
public void startApp() throws MIDletStateChangeException {
System.out.println("startApp");
System.out.println("\nHello World\n");
destroyApp(true);
}
public void pauseApp() {
System.out.println("pauseApp()");
}
public void destroyApp(boolean cond) {
System.out.println("destroyApp(" + cond + ")");
notifyDestroyed();
}
//public String[][][] toppings = new String[200000][200000][20000];
}
```
Whats the simple and effective way to increase size of java build output file? The output format will be .jrc<issue_comment>username_1: All you did was declare an array, you didn't assign any values, so you're still writing a "null."
Have a look at the [Arrays.fill()](https://docs.oracle.com/javase/9/docs/api/java/util/Arrays.html) documentation. Also try asking a question that includes some code with a solution that can be worked because this is kind of vague, and you're also misunderstanding how [creating objects](https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html) works in java.
Upvotes: 0 <issue_comment>username_2: I'll assume to start with that you are talking about the size of ".class" files.
>
> Does initialization of that multi-vector in HellWorld class constructor will do it?
>
>
>
Actually, no. That initialization is actually performed by a single bytecode instruction. Irrespective of the size of the array. You can make your ".class" bigger by adding dimensions to the array, but not enough to generate *large* ".class" files.
>
> Isnt it called after program start?
>
>
>
Yes it is ... but that doesn't affect the size of the class file.
---
Now if you are talking about the amount of memory needed to *run* the program, then an array of that size *will* take a lot of memory:
* one `String[][][]` array with 200,000 elements for the first dimension
* 200,000 `String[][]` arrays with 200,000 elements for the second dimension
* 40,000,000,000 `String[]` arrays with 20,000 elements for the third dimension.
That is a huge amount of memory. But the memory is only allocated at runtime. So much memory that your program won't run on a typical laptop / desktop.
(Which leads me to think that this is not what you are asking about!)
As I said, the ".class" file will be tiny, since the allocation performed using a single bytecode instruction ... with 3 operands: one for each dimension.
---
>
> Whats the simple and effective way to increase size of java build output file?
>
>
>
Classes with lots of large methods or constructors.
Classes with lots of distinct literal strings (preferably large).
However, be aware that the class file format imposes some limits on these things; see <https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.11>
---
>
> I am working with midlet library and somehow I cant create static/final variables outside the class.
>
>
>
That's because Java doesn't allow it. All variables must be declared inside classes (or interfaces). Java is different to C / C++ in many respects, and this is just one of them.
I suggest that you take the time to read a Java tutorial or textbook, rather than guessing how the language works based on knowledge of C and C++.
Upvotes: 1
|
2018/03/14
| 500 | 1,885 |
<issue_start>username_0: I'm using angular 4 and a quill editor. but I get an error of `quill Invalid Quill container`. I change the name of the container but it still returns the error and cannot identify the container id. I create my quill object in ngOninit but it's not working! these are my codes:
```
import * as Quill from 'quill';
quill;
this.quill = new Quill('#editor-container', {
modules: {
toolbar: { container: '#toolbar-toolbar' }
},
theme: 'snow'
});
```
and this is HTML file:
```
---
```<issue_comment>username_1: There other people looking into this, in my case moving the logic to `ngOnInit` solved the problem. Or just check when trying to initialize quill to have the dom element rendered.
Upvotes: 0 <issue_comment>username_2: Unfortunately I am not an Angular expert but I had exactly the same issue with Vue.js.
The problem was that Quill was initiated before the DOM container element was properly rendered. If you can make it sure (use a later lifecycle hook or try to initiate the toolbar in the options, not in the markup), it should work.
Upvotes: 4 <issue_comment>username_3: Quill was called before DOM container is rendered. You can delay constructing Quill by using setTimeOut
```
var editorId = "some-id-name"
setTimeout( () =>
{
var container = document.getElementById(editorId);
var editor = new Quill( container );
}, 3000 );
// 3000 millisec is maybe too long but too make sure that the problem is from creating
// Quill before DOM
```
Upvotes: 2 <issue_comment>username_4: To add to some of the existing answers; using **ngAfterViewInit()** removed the need for a manual delay in my usecase.
```js
ngAfterViewInit(): void {
this.quill = new Quill('#editor-container', {
modules: {
toolbar: {
container: '#toolbar-toolbar'
}
},
theme: 'snow'
});
}
```
Upvotes: 1
|
2018/03/14
| 625 | 2,447 |
<issue_start>username_0: I'm very new in ionic, I'm trying to add records in cards and it added successfully but when i try to add new record it added into same card doesn't create new card with data.I tried with nested component but it won't work. Please help me. Below is my code
.html file
```
{{bindlcdetail}}
```
.ts file
```
addLocalConveyance(): void {
this.bindlcdetails.push(`Allotted Type= ${this.allottedtype}`,
`vehicle Type= ${this.vehicletype}`,
`From Location= ${this.fromlocation}`,
`To Location= ${this.tolocation}`,
`From Date= ${this.fromdate}`,
`To Date= ${this.todate}`,
`KMs= ${this.kms}`,
`Amount= ${this.amount}`);
this.fromlocation = '';
this.tolocation = '';
this.fromdate = null;
this.todate = null;
this.kms = null;
this.amount = null;
}
```
Update
i want output like in img
```
https://i.stack.imgur.com/doQqb.png
```<issue_comment>username_1: There other people looking into this, in my case moving the logic to `ngOnInit` solved the problem. Or just check when trying to initialize quill to have the dom element rendered.
Upvotes: 0 <issue_comment>username_2: Unfortunately I am not an Angular expert but I had exactly the same issue with Vue.js.
The problem was that Quill was initiated before the DOM container element was properly rendered. If you can make it sure (use a later lifecycle hook or try to initiate the toolbar in the options, not in the markup), it should work.
Upvotes: 4 <issue_comment>username_3: Quill was called before DOM container is rendered. You can delay constructing Quill by using setTimeOut
```
var editorId = "some-id-name"
setTimeout( () =>
{
var container = document.getElementById(editorId);
var editor = new Quill( container );
}, 3000 );
// 3000 millisec is maybe too long but too make sure that the problem is from creating
// Quill before DOM
```
Upvotes: 2 <issue_comment>username_4: To add to some of the existing answers; using **ngAfterViewInit()** removed the need for a manual delay in my usecase.
```js
ngAfterViewInit(): void {
this.quill = new Quill('#editor-container', {
modules: {
toolbar: {
container: '#toolbar-toolbar'
}
},
theme: 'snow'
});
}
```
Upvotes: 1
|
2018/03/14
| 444 | 1,349 |
<issue_start>username_0: I have a following table.
```
id name data
1 DAN xxxxxxxxx
2 ANTONY xxxxxxxxx
3 DAN xxxxxxxxx
4 DAN xxxxxxxxx
5 JOSEPH xxxxxxxxx
6 ANTONY xxxxxxxxx
7 JOSEPH xxxxxxxxx
```
I want to first sort the table using ID and then group by name.
eg.
```
7 JOSEPH xxxxxxxxx
5 JOSEPH xxxxxxxxx
6 ANTONY xxxxxxxxx
2 ANTONY xxxxxxxxx
4 DAN xxxxxxxxx
3 DAN xxxxxxxxx
1 DAN xxxxxxxxx
```
I tried various combinations of ORDER BY and also tried ORDER BY FIELD but unable to get the desired result<issue_comment>username_1: Try using
```
select *, (select max(id) from tab t2 where t2.name = t1.name) m
from tab t1
order by m desc, id desc;
```
[dbfiddle demo](http://dbfiddle.uk/?rdbms=mariadb_10.2&fiddle=6185bb9d2fbd11bcee3ad29c6271c437)
Upvotes: 3 [selected_answer]<issue_comment>username_2: You could also use *window function* to get the maximum id for each name and use them for ordering purpose.
```
SELECT *,
MAX(id) OVER(PARTITION BY name ORDER BY id DESC) Ord
FROM table t
ORDER BY Ord DESC
```
Upvotes: 0 <issue_comment>username_3: You can use a subquery in the `order by`, so you can express this as:
```
select t.*
from t
order by (select max(id) from t t2 where t2.name = t.name) desc, id desc;
```
Upvotes: 0
|
2018/03/14
| 863 | 2,946 |
<issue_start>username_0: Following this tutorial: <https://reacttraining.com/react-router/web/example/auth-workflow>.
Trying to reproduce the code:
```
const PrivateRoute = ({ component: Component, ...rest }) => (
fakeAuth.isAuthenticated ? (
) : (
)
}
/>
);
```
In TypeScript:
```
import * as React from 'react';
import { Route, RouterProps } from 'react-router';
interface Props extends RouterProps {
component: React.Component;
}
const PrivateRoute = ({ component: Component, ...rest }: Props) => {
return (
}
/>
);
};
export default PrivateRoute;
```
But it would always fail. Tried different variations. The one I've posted the most recent one. Getting:
[](https://i.stack.imgur.com/L3G2j.png)
It seems to me that I have to pass Generic for the Component type, but I don't know how.
**EDIT:**
The closest solution so far:
```
interface Props extends RouteProps {
component: () => any;
}
const PrivateRoute = ({ component: Component, ...rest }: Props) => {
return (
}
/>
);
};
```
And then:
```
```<issue_comment>username_1: You want to pass a component constructor, not a component instance:
```
import * as React from 'react';
import { Route, RouteProps } from 'react-router';
interface Props extends RouteProps {
component: React.ComponentType;
}
const PrivateRoute = ({ component: Component, ...rest }: Props) => {
return (
}
/>
);
};
export default PrivateRoute;
class Foo extends React.Component {
}
let r =
```
**Edit**
A more complete solution should be generic and use `RouteProps` instead `RouterProps`:
```
import * as React from 'react';
import { Route, RouteProps } from 'react-router';
type Props = RouteProps & P & {
component: React.ComponentType;
}
const PrivateRoute = function (p: Props) {
// We can't use destructuring syntax, because : "Rest types may only be created from object types", so we do it manually.
let rest = omit(p, "component");
let Component = p.component;
return (
}
/>
);
};
// Helpers
type Diff = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T];
type Omit = Pick>;
function omit(value:T, ... toRemove: TKey[]): Omit{
var result = Object.assign({}, value);
for(let key of toRemove){
delete result[key];
}
return result;
}
export default PrivateRoute;
class Foo extends React.Component<{ prop: number }>{
}
let r =
```
Upvotes: 5 <issue_comment>username_2: After a few hours and some investigation, here is the solution that fits my requirements:
```
import * as React from 'react';
import { Route, RouteComponentProps, RouteProps } from 'react-router';
const PrivateRoute: React.SFC =
({ component: Component, ...rest }) => {
if (!Component) {
return null;
}
return (
) => }
/>
);
};
export default PrivateRoute;
```
---
* No `any`;
* No extra complexity;
* Composition pattern retained;
Upvotes: 3
|
2018/03/14
| 834 | 2,921 |
<issue_start>username_0: In my app, I have a menu that routes content via ID but I also have a detailed view where the content should be displayed (via the same ID).
I'm trying to display objects by their ID via button click and I'm not sure how I could pass the ID value to the item-detail component for it to display the content by ID.
All the data I need is made available in a service.
I already route via ID and this works fine
```
path: ':id',
component: ItemDetailComponent,
data:
{
title: 'Item Detail',
}
```
**item.component.html** (menu component)
Here I trigger an event
```
```
**item.component.ts** (menu component)
Here I get the id of the object
```
getId(datavalue: number)
{
console.log(datavalue);
}
```
When I click on the button I get the correct ID in my console log.
Now I want to display the content in the detailed view by ID but I'm not sure how I could pass the ID to this component.
**item-detail.component.html**
Maybe something like this?
```
Text Content
------------
{{glossar[datavalue]?.textContent}}
```
Any help appreciated!<issue_comment>username_1: You want to pass a component constructor, not a component instance:
```
import * as React from 'react';
import { Route, RouteProps } from 'react-router';
interface Props extends RouteProps {
component: React.ComponentType;
}
const PrivateRoute = ({ component: Component, ...rest }: Props) => {
return (
}
/>
);
};
export default PrivateRoute;
class Foo extends React.Component {
}
let r =
```
**Edit**
A more complete solution should be generic and use `RouteProps` instead `RouterProps`:
```
import * as React from 'react';
import { Route, RouteProps } from 'react-router';
type Props = RouteProps & P & {
component: React.ComponentType;
}
const PrivateRoute = function (p: Props) {
// We can't use destructuring syntax, because : "Rest types may only be created from object types", so we do it manually.
let rest = omit(p, "component");
let Component = p.component;
return (
}
/>
);
};
// Helpers
type Diff = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T];
type Omit = Pick>;
function omit(value:T, ... toRemove: TKey[]): Omit{
var result = Object.assign({}, value);
for(let key of toRemove){
delete result[key];
}
return result;
}
export default PrivateRoute;
class Foo extends React.Component<{ prop: number }>{
}
let r =
```
Upvotes: 5 <issue_comment>username_2: After a few hours and some investigation, here is the solution that fits my requirements:
```
import * as React from 'react';
import { Route, RouteComponentProps, RouteProps } from 'react-router';
const PrivateRoute: React.SFC =
({ component: Component, ...rest }) => {
if (!Component) {
return null;
}
return (
) => }
/>
);
};
export default PrivateRoute;
```
---
* No `any`;
* No extra complexity;
* Composition pattern retained;
Upvotes: 3
|
2018/03/14
| 649 | 2,150 |
<issue_start>username_0: I am trying to generate a big table using kable on R.
I would like to group some rows using names stored in an object but can't find how to do this.
This is what I have:
```
kable(Baseline, "html") %>%
kable_styling("striped") %>%
add_header_above(c(" " = 1, "My score" = 4)) %>%
group_rows(index= c(" "=3, "Age" = 4, "BMI" = 4))
```
In this example I only have 3 categories to subclassify the rows but in reality I have more so wanted to know if it was possible to call an object containing names and number of rows to include instead of writing each factor like:
```
kable(Baseline, "html") %>%
kable_styling("striped") %>%
add_header_above(c(" " = 1, "My score" = 4)) %>%
group_rows(index= nametable)
```
Where nametable contains names and number of rows corresponding to this name.
Hope this is clear...
Thank you<issue_comment>username_1: Using the iris dataset:
```
library(tidyverse)
library(kableExtra)
# split the dataset, creating a df for each category from the variable you'll use to group the rows
split_Table <- iris %>%
split(.$Species) %>%
discard(function(x) nrow(x) == 0) %>%
map(., ~ select(., -Species)) # remove Species from split dfs
num_rows <- map(1:length(names(split_Table)), function(x){
nrow(split_Table[[x]])
}) %>% unlist() # create function to count frequency of each category
split_Table %>%
bind_rows() %>%
kable("html", align = "c") %>%
kable_styling(full_width = T) %>%
group_rows(index = setNames(num_rows, names(split_Table)),
label_row_css = "background-color: #666; color: #fff;")
# create table with grouped rows
```
Hope this helps!
Upvotes: 0 <issue_comment>username_2: A bit shorter ...
```
library(tidyverse)
library(kableExtra)
counts <- table(iris$Species)
iris %>%
arrange(Species) %>% # same order as table results
select(-Species) %>%
kable("html", align = "c") %>%
kable_styling(full_width = T) %>%
group_rows(index = setNames(counts, names(counts)),
label_row_css = "background-color: #666; color: #fff;")
```
Upvotes: 1
|