text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Jquery submit not posting values to controller
When i use
$("#FormEthernet").submit();
Form is posted, action is hit in my controller, but there is no data passed, all inputs are null.
(The parameters dictionary contains a null entry...)
Here is my form
@using (Html.BeginForm("MyAction", "MyController",FormMethod.Post, new { id = "FormEthernet",name="FormEthernet" }))
{
<div id="dialog-formEthernet" title="Update Ethernet Config">
<p class="validateTips">
All form fields are required.</p>
<fieldset>
<div>
Phone Number</div>
<div>
<input type="text" name="TNEthernet" id="TNEthernet" />
</div>
<div>
Up</div>
<div>
<input type="text" name="Up" id="Up" /></div>
<div>
Down</div>
<div>
<input type="text" name="Down" id="Down" /></div>
</fieldset>
</div>
}
Any ideas?
JQUERY Bug?
update
here is my controller
[HttpPost]
public ActionResult MyAction(string TNEthernet,string Up, string Down)
{
return RedirectToAction("MyOtherAction", new { id = TNEthernet });
}
And Some Fiddler (Sent)
POST http://localhost:4814/MyController/MyAction HTTP/1.1
Host: localhost:4814
Connection: keep-alive
Content-Length: 0
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Origin: http://localhost:4814
User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:4814/MyController/MyOtherAction/11255
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: .ASPXAUTH=C20491A7FB3B40E5761.......E2EE4291A5D
Here is what calls my submit:
$("#dialog-formEthernet").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Set Configuration": function () {
var bValid = true;
allFields.removeClass("ui-state-error");
bValid = bValid && ensureTN(TNEthernet);
//up and down
bValid = bValid && checkRegexp(UP, /^\d+$/, "Upload");
bValid = bValid && checkRegexp(DOWN, /^\d+$/, "Download");
if (bValid) {
alert($("#Up").val()); //this works
$("#FormEthernet").submit();
}
},
Cancel: function () {
$(this).dialog("close");
}
},
close: function () {
allFields.val("").removeClass("ui-state-error");
}
});
My HTML source
<form action="/MyController/MyAction" id="FormEthernet" method="post" name="FormEthernet"><div id="dialog-formEthernet" title="Update Ethernet Config">
<p class="validateTips">
All form fields are required.</p>
<fieldset>
<div>
Phone Number</div>
<div>
<input type="text" name="TNEthernet" id="TNEthernet" />
</div>
<div>
Up</div>
<div>
<input type="text" name="Up" id="Up" /></div>
<div>
Down</div>
<div>
<input type="text" name="Down" id="Down" /></div>
<input id="FOO" name="FOO" type="text" value="FOO!" />
<input type="submit" />
</fieldset>
</div>
</form>
A:
added this right before .submit()
$("#dialog-formEthernet").parent().appendTo($("#FormEthernet"));
and solved!
See here:
jQuery UI Dialog with ASP.NET button postback
To quote "Chad Rupper"
:
Primarily its because jquery moves the dialog outside of the Form tags using the DOM. Move it back inside the form tags and it should work fine. You can see this by inspecting the element in Firefox.
The code: Robert MacLean
Forgive me for shaking you all up a bit!
| {
"pile_set_name": "StackExchange"
} |
Q:
Seg fault when printing array after passing to function, please explain behaviour
So i am attempting to pass a string array (char** arguments) to a function, fill the array with values and then print those values after returning from the function. The problem occurs when I try to print the first value of "arguments" which gives me a segmentation fault. Why is this? when I print the values in the "getArguments" function all goes as expected. I am new to C and yes this is an assignment. I am not looking for you to write this code for me however I would like an explanation of this behaviour as I try to understand this concept.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define BUFFERSIZE 81
int getArguments(char** arguments, char* argument);
void getPath(char* pathBuffer);
int checkForDirectoryChange(char **arguments, int num_args);
int main(int argc, char *argv[]){
char * command;
char ** arguments = NULL;
char * cd_path;
int len, pid, ret_code, cd_requested = 1;
char buffer[BUFFERSIZE];
/* Get user input and the first token */
printf("Enter a command: > ");
command = fgets(buffer,BUFFERSIZE,stdin);
printf("The command entered was %s",buffer);
len = strlen(buffer);
if(buffer[len-1] == '\n')
buffer[len-1]='\0';
cd_requested = getArguments(arguments, command);
printf("The argument passed is now: %s\n", arguments[0]);
if(cd_requested == 0){
fprintf(stdout,"Change directory requested.\n");
}
/*
char * pathBuf;
getPath(pathBuf);
free the memory allocated */
/*
pid = fork();
if(pid){
wait(NULL);
}else{
ret_code = execvp(*arguments, arguments);
if(ret_code){
printf("The fork failed, exiting.");
exit(0);
}
}*/
}
int getArguments(char** arguments, char* command){
int n_spaces = 0,i;
char *token;
token = strtok(command, " ");
/* Loop until we have gotten all of the tokens */
while (token) {
arguments = realloc (arguments, sizeof (char*) * ++n_spaces);
if (arguments == NULL){
printf("Memory allocation failed: token - %d\n", n_spaces);
exit (-1); /* memory allocation failed */
}
arguments[n_spaces-1] = token;
token = strtok (NULL, " ");
}
/* realloc one extra element for the last NULL */
arguments = realloc (arguments, sizeof (char*) * (n_spaces+1));
arguments[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("arguments[%d] = %s\n", i, arguments[i]);
return strcmp("cd",arguments[0]);
}
int checkForDirectoryChange(char** arguments, int num_args){
return 0;
}
void getPath(char* pathBuffer){
size_t n;
n = confstr(_CS_PATH, NULL, (size_t) 0);
pathBuffer = malloc(n);
if (pathBuffer == NULL)
abort();
confstr(_CS_PATH, pathBuffer, n);
}
A:
It is because getArguments() only reassigned the copy of pointer to pointer of characters inside itself. arguments in main() was not updated.
You should define getArguments() as
int getArguments(char*** arguments, char* command) {
/* ... */
while (token) {
*arguments = realloc (*arguments, sizeof (char*) * ++n_spaces);
if (*arguments == NULL){
printf("Memory allocation failed: token - %d\n", n_spaces);
exit (-1); /* memory allocation failed */
}
(*arguments)[n_spaces-1] = token;
token = strtok (NULL, " ");
}
/* ... */
}
And call it as the following inside main().
cd_requested = getArguments(&arguments, command);
| {
"pile_set_name": "StackExchange"
} |
Q:
Doubts regarding $L_p$ space
I had to dive into the basic definitions and properties of $L_p$ spaces as part of a course project I am doing. (More specifically while I was trying to understand Barbalet's Lemma). It was my first time in this topic and I have got really confused now. It would be great if you could answer some of my questions with a numerical example if possible.
What exactly is an essentially bounded function?
The definition I know of is:-
function $f:[0,1]→ℝ $ is called essentially bounded if there is a number $M $ such that $|f(x)|≤M $ for almost all $ x∈(0,1)$. (That is, the inequality holds on some set $E$ such that $(0,1)$∖E has zero measure.)
Why is $f(x)=x^{−1/(p+1)}$ which defines an element of $L_p((0,1))$ not essentially bounded.
I would also like to ask what is the use of equivalence class of function in such cases?
Also, what would be the set consisting of "almost everywhere" in any appropriate example (maybe above one)?
Does essentially bounded function imply it belongs to $L_{\infty}$ space?
How can a function have $\|f\|_p = 0$ but $f \ne 0$.
Please explain as if I don't know anything. I am not very sure how much I have understood. I am asking the question only after reading many answers and online lecture notes.
A:
1) An essentially bounded function is exactly what you described. The $f$ you gave is not essentially bounded, because for any real number $M$, there exists $\varepsilon>0$ such that $f(x)>M$ for all $x\in (0,\varepsilon)$. This shows that it is not essentially bounded because $(0,\varepsilon)$ has positive measure.
2) You wrote in part (1) that "the inequality holds on some set $E$ such that $(0,1)\setminus E$ has zero measure". This means precisely that the inequality holds almost everywhere. Your example doesn't apply because that $f$ is not essentially bounded. Consider the function $g:(0,1)\to\mathbb{R}$ given by
$$
g(x) = \begin{cases}
n & \text{if}\ x=1/n\ \text{for some}\ n\in\mathbb{N},\,n\geq 2 \\
0 & \text{otherwise}.
\end{cases}
$$
Then $g(x)=0\leq 1$ for all $x\in(0,1)\setminus\{1/n\mid n\in\mathbb{N},\,n\geq 2\}$ and $\{1/n \mid n\in\mathbb{N},\,n\geq2\}$ is a measure zero set. Thus $g=0$ a.e., which is another way of saying that the equivalence class of $g$ is equal to the equivalence class of the zero function $0$ under the "equal a.e." equivalence relation.
3) Yes, by definition $L_\infty(0,1)$ is the space of all essentially bounded functions from $(0,1)$ into $\mathbb{R}$. Some authors consider the quotient of this space by the "equal a.e." equivalence relation, but in practice the two are the same.
4) Do you mean $\|f\|_p=0$ but $f\ne0$? Consider the function $g$ given in (2). Then $\|g\|_p=0$, but $g\ne0$. Now we do have $g=0$ a.e., so some would write $g=0$ and it would be understood that the equality here is with respect to the "equal a.e." equivalence relation.
| {
"pile_set_name": "StackExchange"
} |
Q:
pass MYSQL table data into HTML
I have a file uploadpostinfo.php,
<html>
<head>
</head>
<body>
<?php
error_reporting(E_ALL);
$db = "pickeqco_postinfo";
$link = mysqli_connect($host, $user, $pass, $db);
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "Success: A proper connection to MySQL was made! The $db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
if (!mysqli_select_db($link, $db)) {
echo "Database not selected";
}
$sql = "SELECT id, topic, bullet1, bullet2, expl, source FROM postinformation";
$res = $list->query($sql);
if ($res->num_rows > 0) {
echo "<table><tr><th>ID</th><th>topic</th></tr>";
// output data of each row
while($row = $res->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["topic"]." ".$row["bullet1"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
//echo nl2br("\n\n$topic\n$bullet1\n$bullet2\n$expl\n$source\n\n");
?>
</body>
</html>
I want to get values from the database table and insert it into my index.html file. The uploadpostinfo.php and index.html are in the same directory, but are different files.
<form action="uploadpostinfo.php" method="post">
<input name="submit" type="submit" value="getdata"/>
</form>
Can someone please help me get the mysql table data into my html code?
A:
you are passing result variable but the data is in $res So change
while($row = $result->fetch_assoc()) {
to
while($row = $res->fetch_assoc()) {
| {
"pile_set_name": "StackExchange"
} |
Q:
AddressSanitizer: How could we know that object file/executable in C is compiled with AddressSanitizer?
We are planning to integrate AddressSanitizer tool into our build infrastructure.
For that i am working on our GNUmake files to compile all my C code with AddressSanitizer (adding flag :-fsanitize=address). Now i would like to verify whether created object file or executable is compiled with
AddressSanitizer or not.
Is there any way i can verify the same.
I am just trying to run nm | grep asan :-
It gives following undefined reference symbols.
U __asan_init
U __asan_option_detect_stack_use_after_return
U __asan_register_globals
U __asan_report_load1
U __asan_report_load4
U __asan_stack_malloc_1
U __asan_unregister_globals
I am not sure whether it is right way of checking. It shows undefined reference as above. I am not sure whether i am doing right way of integrated AddressSanitizer in our build system. Is it fine just to compile code with ( -fsanitize=address) ? or still i need to do something here for successful usage of AddressSanitizer.
Please help me in this. Thanks in Advance.
A:
Grepping for reference for Asan functions (usually __asan_report_) in symbol table is fine when checking object files. For linked executables it also works in most cases (except when you link with GCC and -static-libasan -s).
| {
"pile_set_name": "StackExchange"
} |
Q:
Websphere CE issue in Eclipse EE
I have downloaded the Websphere 2.1 App Server and verified that it works fine. I now wanted to use eclipse EE to manage it by adding the server to the server tab. Everything seems to work fine when going through the setup but when I go to start the server I get the error message:
ERROR [GBeanInstanceState] Error while starting; GBean is now in the FAILED state: abstractName="org.apache.geronimo.framework/j2ee-system/2.1.4/car?ServiceModule=org.apache.geronimo.framework/j2ee-system/2.1.4/car,j2eeType=AttributeStore,name=AttributeManager"
java.io.IOException: Unable to write manageable attribute files to directory /opt/IBM/WebSphere/AppServerCommunityEdition/var/config
at org.apache.geronimo.system.configuration.LocalAttributeManager.ensureParentDirectory(LocalAttributeManager.java:573)
at org.apache.geronimo.system.configuration.LocalAttributeManager.load(LocalAttributeManager.java:327)
....
I was wondering if anyone had experience with this particular issue?
A:
Problem self SOLVED: Seems the java IOException was simply because Eclipse did not have the correct privileges to write to the config/ directory. A simple sudo eclipse would suffice.
| {
"pile_set_name": "StackExchange"
} |
Q:
Delete provisioning profile from Xcode 5
I've struggling with this for hours. I have 2 same provisioning profiles I've created and the new profile didn't substitute the old one (which expires 6 days earlier than the new one). Through the XCode 5 menu I can't seem to delete the duplicate provisioning profile. Any workaround in this situation?
A:
If you delete the profile from the Apple development a/c and hit refresh in XCode (Using xcode>Preferences>Accounts) then these profiles will be gone.
You can remove them from the this directory on your machine:
"~/Library/MobileDevice/Provisioning\ Profiles"
A:
In the Xcode Preferences, go to Accounts, then go to your apple ID, then click "View Details"
Click the provisioning profile which you would like to delete, then press the "delete" key ONCE. Then click the refresh icon for manually update the list(pretty counterintuitive...).
Using this method I was able to delete all but one copy of the same provisioning profile, after which the delete does nothing.
A:
You probably don't need to delete the duplicate profiles. Just go to
Xcode / Preferences / Accounts / / View Details
and hit the refresh button.
I did this and my duplicate provisioning profiles disappeared. Now when I post builds to TestFlight the distribution lists are all correct.
| {
"pile_set_name": "StackExchange"
} |
Q:
Weighted Decision Trees using Entropy
I'm building a binary classification tree using mutual information gain as the splitting function. But since the training data is skewed toward a few classes, it is advisable to weight each training example by the inverse class frequency.
How do I weight the training data? When calculating the probabilities to estimate the entropy, do I take weighted averages?
EDIT: I'd like an expression for entropy with the weights.
A:
The Wikipedia article you cited goes into weighting. It says:
Weighted variants
In the traditional formulation of the mutual information,
each event or object specified by (x,y) is weighted by the corresponding probability p(x,y). This assumes that all objects or events are equivalent apart from their probability of occurrence. However, in some applications it may be the case that certain objects or events are more significant than others, or that certain patterns of association are more semantically important than others.
For example, the deterministic mapping {(1,1),(2,2),(3,3)} may be viewed as stronger (by some standard) than the deterministic mapping {(1,3),(2,1),(3,2)}, although these relationships would yield the same mutual information. This is because the mutual information is not sensitive at all to any inherent ordering in the variable values (Cronbach 1954, Coombs & Dawes 1970, Lockhead 1970), and is therefore not sensitive at all to the form of the relational mapping between the associated variables. If it is desired that the former relation — showing agreement on all variable values — be judged stronger than the later relation, then it is possible to use the following weighted mutual information (Guiasu 1977)
which places a weight w(x,y) on the probability of each variable value co-occurrence, p(x,y). This allows that certain probabilities may carry more or less significance than others, thereby allowing the quantification of relevant holistic or prägnanz factors. In the above example, using larger relative weights for w(1,1), w(2,2), and w(3,3) would have the effect of assessing greater informativeness for the relation {(1,1),(2,2),(3,3)} than for the relation {(1,3),(2,1),(3,2)}, which may be desirable in some cases of pattern recognition, and the like.
http://en.wikipedia.org/wiki/Mutual_information#Weighted_variants
A:
State-value weighted entropy as a measure of investment risk.
http://www56.homepage.villanova.edu/david.nawrocki/State%20Weighted%20Entropy%20Nawrocki%20Harding.pdf
| {
"pile_set_name": "StackExchange"
} |
Q:
How to operate logic operation of all columns of a 2D numpy array
Let's say I have the following 2D NumPy array consisting of four rows and three columns:
>>> a = numpy.array([[True, False],[False, False], [True, False]])
>>> array([[ True, False],
[False, False],
[ True, False]], dtype=bool)
What would be an efficient way to generate a 1D array that contains the logic or of all columns (like [True, False])?
I searched the web and found someone referring to sum(axis=) to calculate the sum.
I wonder if there is some similar way for logic operation?
A:
Yes, there is. Use any:
>>> a = np.array([[True, False],[False, False], [True, False]])
>>> a
array([[ True, False],
[False, False],
[ True, False]], dtype=bool)
>>> a.any(axis=0)
array([ True, False], dtype=bool)
Note what happens when you change the argument axis to 1:
>>> a.any(axis=1)
array([ True, False, True], dtype=bool)
>>>
If you want logical-and use all:
>>> b.all(axis=0)
array([False, False], dtype=bool)
>>> b.all(axis=1)
array([ True, False, False], dtype=bool)
>>>
Also note that if you leave out the axis keyword argument, it works across every element:
>>> a.any()
True
>>> a.all()
False
A:
NumPy has also a reduce function which is similar to Python's reduce. It's possible to use it with NumPy's logical operations. For example:
>>> a = np.array([[True, False],[False, False], [True, False]])
>>> a
array([[ True, False],
[False, False],
[ True, False]])
>>> np.logical_or.reduce(a)
array([ True, False])
>>> np.logical_and.reduce(a)
array([False, False])
It also has the axis parameter:
>>> np.logical_or.reduce(a, axis=1)
array([ True, False, True])
>>> np.logical_and.reduce(a, axis=1)
array([False, False, False])
The idea of reduce is that it cumulatively applies a function (in our case logical_or or logical_and) to each row or column.
| {
"pile_set_name": "StackExchange"
} |
Q:
Any use case for SOAP over SMTP/JMS?
I've frequently used SOAP over HTTP for web services that so far worked great and with REST this is only choice we're left with.
I would like to know If you've come across a use case/scenario in your projects that needs SOAP over SMTP or SOAP over JMS type of communication? I'm just trying to understand uses of SMTP or JMS with SOAP?
A:
Both SMTP, and most JMS implementations, provide queueing of messages. If you need to reliably send a message to an endpoint that may not be available, they are both reasonable choices.
JMS implementations often add additional properties, such as in-order delivery, the ability to select the appropriate level of assurance (eg: at least once, only once, etc), the ability to load-balance processing more easily, and various topologies such as broadcast or fan-out.
These are really properties of the underlying transport, and would be equally valid if you replaced SOAP with "custom JSON", XML, or any other message encoding in your question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cisco FWSM -> ASA upgrade broke our mail server
We send mail with unicode asian characters to our mail server on the other side of our WAN... immediately after upgrading from a FWSM running 2.3(2) to an ASA5550 running 8.2(5), we saw failures on mail jobs that contained unicode and other text encoded as Base64.
The symptoms are pretty clear... using the ASA's packet capture utility, we snagged the traffic before and after it left the ASA...
access-list PCAP line 1 extended permit tcp any host 192.0.2.25 eq 25
capture pcap_inside type raw-data access-list PCAP buffer 1500000 packet-length 9216 interface inside
capture pcap_outside type raw-data access-list PCAP buffer 1500000 packet-length 9216 interface WAN
I downloaded the pcaps from the ASA by going to https://<fw_addr>/pcap_inside/pcap and https://<fw_addr>/pcap_outside/pcap... when I looked at them with Wireshark > Follow TCP Stream, the inside traffic going into the ASA looks like this
EHLO metabike
AUTH LOGIN
YzFwbUlciXNlck==
cZUplCVyXzRw
But the same mail leaving the ASA on the outside interface looks like this...
EHLO metabike
AUTH LOGIN
YzFwbUlciXNlck==
XXXXXXXXXXXX
The XXXX characters are concerning... I fixed the issue by disabling ESMTP inspection:
wan-fw1(config)# policy-map global_policy
wan-fw1(config-pmap)# class inspection_default
wan-fw1(config-pmap-c)# no inspect esmtp
wan-fw1(config-pmap-c)# end
The $5 question... our old FWSM used SMTP fixup without issues... mail went down at the exact moment that we brought the new ASAs online... what specifically is different about the ASA that it is now breaking this mail?
Note: usernames / passwords / app names were changed... don't bother trying to Base64-decode this text.
A:
Are there UTF-8 characters in the 'real' version of that username (after decoding)? If the inspection has triggered on it, I'm guessing there's a reason that it's picked that specific line.
But maybe not; the inspection feature is more akin to the chaos monkey than an IPS. Personally, the only things the inspection features have really provided for me have been headaches (through overly aggressive sanitizing of perfectly valid traffic) and security vulnerabilities. From a quick search:
CVE-2011-0394 (reboot of the ASA from inspect skinny)
CVE-2012-2472 (CPU DoS from inspect sip)
CVE-2012-4660/4661/4662 (more reboots, you get the idea)
My recommendation is to not lose much sleep over needing to turn off aspects of the ASA's protocol inspection; the endpoint server applications (or a targeted security platform like a web application firewall) tend to do a much better job of enforcing protocol compliance anyway.
| {
"pile_set_name": "StackExchange"
} |
Q:
Como fornecer uma quantidade específica de strings a serem testadas?
Consigo testar se uma string fornecida pelo usuário é um palíndromo ou não (palavra ou frase que pode ser lida de trás pra frente ignorando espaços e letras maiúsculas e minúsculas como, por exemplo: Socorram me subi no onibus em Marrocos), utilizando o código:
string = raw_input()
stringSemEspacos = string.replace(' ', '')
stringTodaMinuscula = stringSemEspacos.lower()
stringInvertida = stringTodaMinuscula[::-1]
if stringInvertida == stringTodaMinuscula:
print "SIM"
else:
print "NAO
Preciso escrever um programa que, antes de receber as strings a serem testadas, receba primeiro um número inteiro, que corresponda a quantidade de strings que devem ser testadas. Se o usuário quiser testar 4 strings, o número 4 deve ser a primeira entrada no programa, seguido das 4 strings que serão testadas, e o programa deve julgar cada string e imprimir as 4 respostas, entre Sim e Não. Como fazer para o programa receber a quantidade de strings estabelecida, fazer o julgamento e só então ser encerrado?
Como estou fazendo:
i = 0
quantidade = int(raw_input())
while i < quantidade:
i += 1
string = raw_input()
stringSemEspacos = string.replace(' ', '')
stringTodaMinuscula = stringSemEspacos.lower()
stringInvertida = stringTodaMinuscula[::-1]
if stringInvertida == stringTodaMinuscula:
print "SIM"
else:
print "NAO"
A:
Você pode solicitar que o usuário informe a quantidade de palavras a serem lidas, para isso, pode usar a variável quantidade que vai guardar a quantidade de palavras, e em seguida definir uma variável i que será incrementada em um loop while e verificar se i é menor que quantidade, e dentro do loop fazer a leitura.
Veja um exemplo:
i = 0
quantidade = input("Quaintidade de palavras a seram lidas: ")
while (i < quantidade):
palavra = raw_input("Palavra: ")
print (palavra)
i += 1
Entrada:
3
Entrada:
Palavra1
Saída:
Palavra1
Entrada:
Palavra2
Saída:
Palavra2
Entrada:
Palavra3
Saída:
Palavra3
Veja a adaptação para solucionar o problema de verificação de palavras.
Código:
def ehPalindromo(palavra):
stringSemEspacos = palavra.replace(' ', '')
stringTodaMinuscula = stringSemEspacos.lower()
stringInvertida = stringTodaMinuscula[::-1]
if stringInvertida == stringTodaMinuscula: return "SIM"
else: return "NAO"
i = 0
palavras = []
quantidade = input("Quaintidade de palavras a seram lidas: ")
while (i < quantidade):
palavras.append(raw_input("Palavra: "))
i += 1
for p in palavras:
print("A palavra {} eh Palindromo: {}".format(p, ehPalindromo(p)))
Entrada:
2
Entrada:
ovo
Entrada:
ave
Saída:
A palavra ovo eh Palindromo: SIM
A palavra ave eh Palindromo: NAO
Primeiro eu definir uma lista palavras que vai guardar as palavras informadas pelo usuário de acordo com a quantidade especificada no inicio do programa, em seguida obtive a quantidade de palavras que deve ser informada e guardei na variável quantidade, e fiz a leitura das palavras e guardei na lista palavras e por fim fiz a exibição de todas palavras digitadas e validadas através do método ehPalindromo() que retorna SIM ou NAO.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cell of matrices to csv matlab
I have a problem converting my results to a csv file.
My cell is like this:
[1403x36 double] [1290x36 double] [1813x36 double] [1363x36 double] [1286x36 double]
[1355x36 double] [1194x36 double] [1130x36 double] [1277x36 double] [1494x36 double]
[1447x36 double] [1455x36 double] [1817x36 double] [1434x36 double] [1536x36 double]
I want my CSV file to have (rows x 36).
I tried already cell2csv and i did a loop of fprint also, but neither of them worked.
Thank you in advance.
A:
As with the other users who have commented, it's not clear to me what the desired structure or ordering of the contents of your CSV should be, but here is an example workflow that assumes you would be comfortable first reshaping your cell array into an Q x 1 size (in column-major order), and then concatenating the contents in each cell into an Mx36 matrix.
myCell = {rand(10,36),rand(5,36); rand(4,36),rand(7,36)};
myCell = myCell(:);
myMatrix = cell2mat(myCell);
csvwrite('filename.csv',myMatrix);
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Using multiple databases in firebase makes each of them has its own usage?
I am using firebase database in my Android app. The download limit for the database is 10 GB/month. If I upgraded my app to Blaze plan and made another database will each one of them will be able to download up to10 GB?
If I split the data between them will the data be able to be downloaded up to 20GB/month for free?
A:
firebaser here
The free quota applies to a project, not to a database. Even if you switch to the Blaze plan and create multiple databases, only the first 10GB of outbound traffic will be free.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't open dmg for combo update to 10.14: corrupt image
I've downloaded macOSUpdCombo10.14.6.dmg from the official apple site twice now in order to update my 10.10 to 10.14, both times when I try to open the dmg I am told that it can't be opened as the image is corrupt.
I'm at a loss, this isn't happening with other dmg files I have, I've run the disk utility function verify on my drive and it reports no errors.
Is it the file? Am I doing something wrong? Any insights would be appreciated.
A:
Get macOS Mojave directly from the App Store and install it. This will give you the most recent version of 10.14.6, you won't need to run the combo updater afterwards.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to search for commit by Change-Id in Gerrit?
Gerrit generated a Change-Id in commit message. Is it possible to search for a commit by this Change-Id?
A:
The trick is search by "message:" instead of "change:". Change-Id is part of the commit message and searchable. "change:" must refer to some other field.
| {
"pile_set_name": "StackExchange"
} |
Q:
WPF binding with .NET object not communicating the data
I am following a tutorial on WPF data binding. I am trying to bind to a .NET object's property to a XAML control but the control does not display the expected data. These are what I believe to be the relevant sections of code:
In procedural code: (Note: removed ObservableCollection in PhotoGallery after original post)
Namespace PhotoGallery
Partial Public Class MainWindow
Inherits Window
Private photos As New Photos
...
End Class
Namespace PhotoGallery
Public Class Photos
Inherits Collection(Of Photo)
...
End Class
In XAML (Solution/Project name is Ch13-PhotoGallery):
<Window x:Class="PhotoGallery.MainWindow"
...
xmlns:local="clr-namespace:Ch13_PhotoGallery.PhotoGallery"
...>
<Window.Resources>
<local:Photos x:Key="Photos"/>
</Window.Resources>
And this is the control that is not displaying the data, which is the size of the Photos collection:
<Label x:Name="numItemsLabel" Background="AliceBlue" FontSize="8" Content="{Binding Source={StaticResource Photos}, Path=Count}"/>
When I typed in the < Label >, Intellisense popped up 'Count' for the Path property, so I think that tells me I have everything defined correctly.
If I add this line of procedural code behind to the refresh() method:
numItemsLabel.Content = photos.Count
Then the count is displayed correctly.
But I'm not getting the binding in XAML to display Photos.Count.
A:
This creates a new instance of the Photos class:
<local:Photos x:Key="Photos"/>
If you want to bind to the Photos collection that you have created in your MainWindow.xaml.vb file you should expose it as a public property - you can only bind to properties but not fields - and set the DataContext of the window to an instance of the class where this property is defined, i.e. the window class itself in your case:
Class MainWindow
Public Property Photos As Photos
Public Sub New()
' This call is required by the designer.
InitializeComponent()
DataContext = Me
...
End Sub
End Class
You can the bind directly to the property:
<Label x:Name="numItemsLabel" Background="AliceBlue" FontSize="8" Content="{Binding Path=Photos.Count}"/>
| {
"pile_set_name": "StackExchange"
} |
Q:
Access gmail account through cmd prompt in linux
I want to login to Gmail through cmd prompt. Please provide solutions.
A:
You can try mutt email client.
tutorial.
| {
"pile_set_name": "StackExchange"
} |
Q:
find polygons within a radius of one point (of a table of points)
I'd like to perform a select by location analysis in PostGIS that first selects the geometry of ONE point out of a table (of many points). Creates then a circumference around it and checks which geometries (polygons) of a second table lie within that circumference.
I came up with this but am somehow stuck..
SELECT t2.name, t2_area
FROM ( SELECT geom
FROM views.sites
WHERE site_id LIKE 'AB_10003' ) t1, spatial.land_use t2
WHERE ST_DWithin(t1.geom, t2.geom, 1000) -- radius of 1000m
the SRID of my geometries is 31467. Any help?
A:
While your SQL looks logically correct, it's not well formed. You are thinking procedurally, and you should think more schematically. In "correct" SQL your logic would be:
SELECT sl.name, sl.area
FROM views.sites vs
JOIN spatial.land_use sl
ON ST_DWithin(vs.geom, sl.geom, 1000)
WHERE vs.site_id = 'AB_10003'
Use "join" clauses for conditions that use values from two tables, and put other conditions into the "where" clause, and then let the database sort out the most efficient execution path: it will do better than you.
| {
"pile_set_name": "StackExchange"
} |
Q:
animating multiple markers in OpenLayers 3
I am creating animations of migrating sea animals across the Pacific using OpenLayers. I would like each "animal" to trace a track as it goes over time. At the head of the track will be an icon/marker/overlay representing that animal. I have gotten this to work for one track, but although I am able to grow the track of each animal as a linestring constructed segment by segment, I am unable to specifically assign an icon/marker/overlay to each track. Instead, I am only able to animate one icon on one track. The rest of the linestring tracks proceed, but they do not have an icon at the head of the track as it is traced out. Here is my code. Any help appreciated.
// draw tracks
function makeLineString(id, species, multipointCoords, tracksTime) {
// layer structure and style assignment
var trackSource = new ol.source.Vector();
var trackLayer = new ol.layer.Vector({
source: trackSource,
style: BWtrackStyle
});
map.addLayer(trackLayer);
var lineString = new ol.geom.LineString([
ol.proj.fromLonLat(multipointCoords[0][0])
]);
var trackFeature = new ol.Feature({
geometry: lineString
});
if (species === "Blue Whale") {
trackFeature.setStyle([BWtrackStyle, shadowStyle]);
};
trackSource.addFeature(trackFeature);
// icon-marker-overlay styling
var BW2205005icon = document.getElementById('BW2205005icon');
var BW2205005marker = new ol.Overlay({
positioning: 'center-center',
offset: [0, 0],
element: BW2205005icon,
stopEvent: false
});
map.addOverlay(BW2205005marker);
var BW2205012icon = document.getElementById('BW2205012icon');
var BW2205012marker = new ol.Overlay({
positioning: 'center-center',
offset: [0, 0],
element: BW2205012icon,
stopEvent: false
});
map.addOverlay(BW2205012marker);
var coordinate, i = 1,
length = multipointCoords[0].length;
var currentTime = tracksTime[0][0];
var nextTime = tracksTime[0][1];
speedOption = 100; // the highter this value, the faster the tracks, see next line
var transitionTime = (nextTime - currentTime) / speedOption;
console.log(transitionTime);
var timer;
timer = setInterval(function() {
segmentConstruction(id, multipointCoords, tracksTime);
}, transitionTime);
function segmentConstruction(id, multipointCoords, tracksTime) {
coordinate = ol.proj.fromLonLat(multipointCoords[0][i]);
lineString.appendCoordinate(coordinate);
console.log(id);
if (id === "BW2205005") {
BW2205005marker.setPosition(coordinate);
} else {
BW2205012marker.setPosition(coordinate);
};
if (i >= length - 1) {
clearInterval(timer);
} else {
i++;
clearInterval(timer);
currentTime = tracksTime[0][i];
nextTime = tracksTime[0][i + 1];
transitionTime = (nextTime - currentTime) / speedOption;
timer = setInterval(function() {
segmentConstruction(id, multipointCoords, tracksTime);
}, transitionTime);
};
};
};
A:
I think your overlay is being reused for each line. In any case, it would probably be simpler and more performant to use a point feature instead of the overlay, as follows:
add a new style to your layer for points (circle, image, etc.)
add a point feature representing the head of each line
update the coordinates of the point feature when necessary
In other words, each animal would have a linestring and a point feature. The style on the layer would include the stroke style for the line and the icon style for the point.
You could also style the points independently by giving each point feature it's own style, or using a style function on the layer.
| {
"pile_set_name": "StackExchange"
} |
Q:
using 'auto' in std::map
I'm parsing a JSON file, the values can consist of integer, string or float. Normally I have a map defined like this:
std::map<std::string, std::string> myMap;
The problem is I'm not clear how to use map if there can be different data types, I tried:
std::map<std::string, auto> myMap;
but I get an error:
'auto' is not allowed here
Is there I way I can use it with different data types or do I need to define an object, which can contain different data types, for example:
Class MyObject
{
private:
int integerValue;
std::string stringValue;
public:
void setValue( std::string value, int type );
}
MyObject::setValue( std::string value, int type )
{
if( type == 0 )
stringValue = value;
else if( type == 1 )
integerValue = stoi( value );
}
Or is there a better way to do this? Thanks!
A:
In order to achieve what you ask, use:
std::map<std::string, std::any> myMap;
For example:
#include <map>
#include <string>
#include <any> // Since C++17
main()
{
std::map<std::string, std::any> myMap;
std::string strName{ "Darth Vader" };
int nYear = 1977;
myMap["Name"] = strName;
myMap["Year"] = nYear;
std::string strS = std::any_cast<std::string>(myMap["Name"]); // = "Darth Vader"
int nI = std::any_cast<int>(myMap["Year"]); // = 1977
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Add Cyrillic character е in a latin character phrase
I aim to add the unicode character U+0435 in the middle of a sentence in latin characters multiple times. Any fast and light-code idea to do it?
Thanks!
Example:
\begin{document}
Adding the cyrillic character е in this sentence crashes
the document so I have to delete the character е.
\end{document}
A:
You have to declare a font encoding that supports cyrillic, for instance T2A. Then, as the commands for producing the characters don't have (for efficiency reason) a default encoding, you have to add it for the characters you need.
\documentclass{article}
\usepackage[T2A,T1]{fontenc}
\usepackage[utf8]{inputenc}
\DeclareTextSymbolDefault{\cyre}{T2A}
\DeclareTextSymbolDefault{\cyrf}{T2A}
\begin{document}
Adding the cyrillic character е in this sentence doesn't crash
the document so I don't have to delete the character е.
It doesn't crash even with ф.
\end{document}
The names of the letters are easy, usually. For the uppercase Е it's \CYRE and so on. You find them in the file t2aenc.def, lines 102–165.
A hack for enabling all letters in one swoop:
\documentclass{article}
\usepackage[T2A,T1]{fontenc}
\usepackage[utf8]{inputenc}
\begingroup
\makeatletter
\providecommand\@gobblethree[3]{}
\let\DeclareFontEncoding\@gobbletwo
\let\DeclareFontSubstitution\@gobblefour
\let\DeclareTextAccent\@gobblethree
\let\@tempa\@empty
\renewcommand\DeclareTextCommand[2]{\renewcommand\@tempa}
\let\DeclareTextComposite\@gobblefour
\def\DeclareTextSymbol#1{\expandafter\decidecyr\string#1....\decidecyr{#1}}
\def\decidecyr#1#2#3#4#5\decidecyr#6{%
\lowercase{\def\@tempa{#1#2#3#4}}\edef\@tempb{\string\cyr}%
\ifx\@tempa\@tempb
\expandafter\declarecyr\expandafter#6%
\else
\expandafter\@gobbletwo
\fi
}
\newcommand\declarecyr[3]{%
\toks@=\expandafter{\the\toks@\DeclareTextSymbolDefault{#1}{T2A}}}
\toks@={}
\input{t2aenc.def}
\expandafter\endgroup\the\toks@
\begin{document}
Adding the cyrillic character е in this sentence doesn't crash
the document so I don't have to delete the character е.
It doesn't crash even with ф.
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to apply an alpha mask to a FlxCamera?
I'm trying to implement this camera but one of the obstacles I'm facing right now, is the merging of two cameras (what he describes here).
At first I tried to make a non-rectangular camera, but I don't think it's possible without changing a lot of things in the way HaxeFlixel renders.
And then I found the alphaMask() function in the FlxSpriteUtil package and I think it would be a better solution.
Not only would it solve my problem, it would actually permit all kinds of funky-shaped cameras, you just have to create the right mask!
But the new problem is that I don't know how to (and again, if it's possible without changing a bit the FlxCamera) apply it to the camera.
Internally, the FlxCamera might use a FlxSprite, but only in blit render mode, and I am in tiles render mode (haven't found how to change, not good enough solution in my opinion), which uses a Flash Sprite instead and I don't know what to do with it.
So in short, do you have an idea how to apply an AlphaMask to a FlxCamera? Or another way to achieve what I'm trying to do?
PS: If you want to have a look at the (ugly and frenchly commented) code, it's over here!
A:
You can render the contents of a FlxCamera to a FlxSprite (though it does require conditional code based on the render mode). The TurnBasedRPG tutorial game uses this for the wave effect in the combat screen, see CombatHUD.hx:
if (FlxG.renderBlit)
screenPixels.copyPixels(FlxG.camera.buffer, FlxG.camera.buffer.rect, new Point());
else
screenPixels.draw(FlxG.camera.canvas, new Matrix(1, 0, 0, 1, 0, 0));
Here's a code example that uses this to create a HaxeFlixel-shaped camera:
package;
import flixel.tweens.FlxTween;
import flash.geom.Matrix;
import flixel.FlxCamera;
import flixel.FlxG;
import flixel.FlxSprite;
import flixel.FlxState;
import flixel.graphics.FlxGraphic;
import flixel.system.FlxAssets;
import flixel.util.FlxColor;
import openfl.geom.Point;
using flixel.util.FlxSpriteUtil;
class PlayState extends FlxState
{
static inline var CAMERA_SIZE = 100;
var maskedCamera:FlxCamera;
var cameraSprite:FlxSprite;
var mask:FlxSprite;
override public function create():Void
{
super.create();
maskedCamera = new FlxCamera(0, 0, CAMERA_SIZE, CAMERA_SIZE);
maskedCamera.bgColor = FlxColor.WHITE;
maskedCamera.scroll.x = 50;
FlxG.cameras.add(maskedCamera);
// this is a bit of a hack - we need this camera to be rendered so we can copy the content
// onto the sprite, but we don't want to actually *see* it, so just move it off-screen
maskedCamera.x = FlxG.width;
cameraSprite = new FlxSprite();
cameraSprite.makeGraphic(CAMERA_SIZE, CAMERA_SIZE, FlxColor.WHITE, true);
cameraSprite.x = 50;
cameraSprite.y = 100;
cameraSprite.cameras = [FlxG.camera];
add(cameraSprite);
mask = new FlxSprite(FlxGraphic.fromClass(GraphicLogo));
var redSquare = new FlxSprite(0, 25);
redSquare.makeGraphic(50, 50, FlxColor.RED);
add(redSquare);
FlxTween.tween(redSquare, {x: 150}, 1, {type: FlxTween.PINGPONG});
}
override public function update(elapsed:Float):Void
{
super.update(elapsed);
var pixels = cameraSprite.pixels;
if (FlxG.renderBlit)
pixels.copyPixels(maskedCamera.buffer, maskedCamera.buffer.rect, new Point());
else
pixels.draw(maskedCamera.canvas);
cameraSprite.alphaMaskFlxSprite(mask, cameraSprite);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Strcpy and Strcat garbage chars
I have 2 strings: 'name1' and 'name2'.
name1 is always of type something.inp and I want name 2 to be of type something.pts.
so if name1 is 'data.inp', i wanted name2 to be 'data.pts'.
I tried doing the following, but with no success, since when I print name2 I get some garbage values right before 'pts'.
name1=(char*)malloc((strlen(argv[2])+1)*sizeof(char));
name2=(char*)malloc(1+(strlen(name1))*sizeof(char));
strcpy(name1, argv[2]);
strncpy(name2, name1, strlen(name1)-3);
strcat(name2, "pts");
Help will be greatly appreciated.
A:
You can do it remplacing the last characters :
name1 = argv[2];
name2 = name1;
name2[name2.length()-3] = 'p';
name2[name2.length()-2] = 't';
name2[name2.length()-1] = 's';
| {
"pile_set_name": "StackExchange"
} |
Q:
Do animals know God exists?
I remember a scene from the Telugu movie Sri Ramadasu in which animals such as elephants, deer and peacocks are filled with ecstasy when Lord Vishnu descends to earth as Lord Rama, and welcomed Him. Now my questions are:
Do animals really know God exists? Or was it just picturization in the film? (You can see that particular scene here).
There is another story that Rama warmly stroked squirrel for the little help it could do while building Ramasethu. You can find the story from here. Does it mean that animals can recognize God (here Squirrel chants Rama-Nama and helps Him) in whatever form he exists? (Here Rama was human and some people who lived at that time saw him as human except Supraja and some other sages).
A:
Gajendra elephant got Moksha by chanting name of Lord Vishnu. Once Gajendra elephant went to a lake to drink water. One crocodile came and barked at elephant's feet. Crocodile was very strong and it holds elephant in water only. Gajendra elephant continuosly chanted Lord Vishnu's name and Lord Vishnu came to rescue it. Thus an elephant got Moskha.
Nandhi is also devotee of Lord Shiva. Garuda is devotee of Vishnu and so on many deity has animals as their vehicle.
This describes that even animals know GOD exists and they can get moksha too.
Actually human is also one animal and Lord Shiva/Harihar is Pashupati.
Read More Here at Wikipedia
| {
"pile_set_name": "StackExchange"
} |
Q:
Is the use of "for i := x to y" well defined behaviour, if x > y?
The intuitive answer would be that the loop is never entered. And this seems to be case in all tests I could come up with. I'm still anxious and always test it before entering the loop.
Is this necessary?
A:
No, it is not necessary.
The documentation clearly states :
for counter := initialValue to finalValue do statement
or:
for counter := initialValue downto finalValue do statement
...
If initialValue is equal to finalValue, statement is executed exactly once. If initialValue is greater than finalValue in a for...to statement, or less than finalValue in a for...downto statement, then statement is never executed.
There is no need for anxiety.
If we want to examine further what happens, let's make a few examples. Consider first :
program Project1;
{$APPTYPE CONSOLE}
var
i : integer;
begin
for i := 2 to 1 do WriteLn(i);
end.
This produces a compiler hint:
[dcc32 Hint] Project1.dpr(6): H2135 FOR or WHILE loop executes zero times - deleted
So the compiler will simply throw away a loop with constants that produce no loop iterations. It does this even with optimizations turned off - no code is produced for the loop at all.
Now let's be a bit more clever :
program Project1;
{$APPTYPE CONSOLE}
var
i, j, k : integer;
begin
j := 2;
k := 1;
for i := j to k do WriteLn(i);
end.
This actually compiles the loop. The output is as below:
Project1.dpr.8: for i := j to k do WriteLn(i);
004060E8 A1A4AB4000 mov eax,[$0040aba4] {$0040aba4 -> j = 2}
004060ED 8B15A8AB4000 mov edx,[$0040aba8] {$0040aba8 -> k = 1}
004060F3 2BD0 sub edx,eax {edx = k - j = -1}
004060F5 7C2E jl $00406125 {was k-j < 0? if yes, jmp to end.}
004060F7 42 inc edx {set up loop}
004060F8 8955EC mov [ebp-$14],edx
004060FB A3A0AB4000 mov [$0040aba0],eax
00406100 A118784000 mov eax,[$00407818] {actual looped section}
00406105 8B15A0AB4000 mov edx,[$0040aba0]
0040610B E8E8D6FFFF call @Write0Long
00406110 E8C3D9FFFF call @WriteLn
00406115 E8EECCFFFF call @_IOTest
0040611A FF05A0AB4000 inc dword ptr [$0040aba0] {update loop var}
00406120 FF4DEC dec dword ptr [ebp-$14]
00406123 75DB jnz $00406100 {loop ^ if not complete}
Project1.dpr.9: end.
00406125 E88EE1FFFF call @Halt0
So, the very first thing a loop does is to check whether it needs to execute at all. If the initial is greater than the final (for a for..to loop) then it skips straight past it entirely. It doesn't even waste the cycles to initialize the loop counter.
| {
"pile_set_name": "StackExchange"
} |
Q:
TypeError: data.map is not a function
Im really stuck on this figuring out what did I miss, Im not that expert about javascript, if someone can please tell me what I did wrong, I really appreciate.
I have a working code:
if (value_ == "group") {
fetch("http://localhost/someapi"+value_).then(r => { return r.json()})
.then(json => {
var data = `{ "group" : [{"name":"foo","tag":"bar"},{"name":"bool","tag":"lean"}] }`;
var data = JSON.parse(data);
var groupName = data.group.map(current => current.name);
var groupTag = data.group.map(current => current.tag);
console.log(data);
console.log(`json: ${data.group[0].name}`);
});
}
the code above will work and get every data I wanted, but the json is from the:
var data = `{ "group" : [{"name":"foo","tag":"bar"},{"name":"bool","tag":"lean"}] }`;
then I tried to get the json from the URL which return the same value as the var data above. But it doesn' work.
which I did change var data = JSON.parse(data); into data = JSON.parse(json)
and delete "var data = { "group" : [{"name":"foo","tag":"bar"},{"name":"bool","tag":"lean"}] };"
And it does give an error: (node:10868) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected end of JSON input
I also tried this code:
fetch("http://localhost/someapi"+value_).then(r => { return r.json()})
.then(json => {
parseJSON(JSON.stringify(json));
function parseJSON(str){
var data = JSON.parse(str);
var groupName = data.group.map(current => current.name);
var groupTag = data.group.map(current => current.tag);
console.log(data);
console.log(`json: ${data.group[0].name}`);
}
});
}
this give me error: (node:12668) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'map' of undefined.
Thanks and pardon my english.
A:
You don't need to execute JSON.parse manually because the content of json variable in the third line of your example is already an object.
Try this:
fetch("http://localhost/someapi"+value_)
.then(r => r.json())
.then(json => {
var groupName = json.group.map(current => current.name);
var groupTag = json.group.map(current => current.tag);
console.log('groupName', groupName);
console.log('groupTag', groupTag);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Python function to implement an image-processing pipeline
I have written the following function to process images. Now I am not sure if it's pythonic or considered as spaghetti code. I know being flat is better than nested, but I don't see a way around it.
I could easily apply list comprehensions if the "if" statements are only resolving true/false, but each step depends on the output of the previous steps, so I don't think I could use itertools.
def get_image(width, height, collection_sku, order_id, name, handle):
"""image processing pipeline"""
# Check-1 image exception should be checked before proceeding further
# covers both images in exception(currently bookshelves) list and also personal true doors
# 1. bookshelves need to be cropped
# 2. personal images needs to be added in the required size
if helpers.image_exception(collection_sku):
# Step-1 Find image folder
directory_sizes = helpers.find_directory(width, height)
if directory_sizes is not None:
# Step-2 Find the image from the given folder.
key = helpers.find_image(directory_sizes, collection_sku)
if key is not None:
requires_resize = helpers.should_resize(width, height)
requires_flip = helpers.should_flip(handle) and not helpers.flip_exception(collection_sku)
# Check-2 check whether image requires resizing or flipping
if requires_resize or requires_flip:
# Step-3 Create local directory to store temporary images
location, is_created = helpers.local_directory(
order_id)
if is_created:
# Step-4 Download image
image = helpers.download_image(key, location, name)
if image is not None:
width_px = helpers.cm_to_pixel(width)
height_px = helpers.cm_to_pixel(height)
image_modified = False
# Step-5.1 Resize image
if requires_resize:
helpers.resize_image(image, width_px, height_px)
image_modified = True
# Step-5.2 Flip image
if requires_flip:
helpers.flip_image(image)
image_modified = True
# Step-6 Upload image
if image_modified:
helpers.upload_image(image, key)
# Step-3 No local dir created
# Step-4 Can't download image
# Step-5.1 Can't resize image
# Step-5.2 Can't flip image
# Step-6 Can't upload image
return None
# Check-2 if no image processing required then copy image over
helpers.copy_image(key, target=None) # TODO
return True
# raise exception in sub job
# Check-1 if image door image cannot be processed
# Step-1 if directory not available
# Step-2 if image not available
return None
A:
As Reinderien mentions, you can decrease some of the complexity of your code by inverting your if-statements. While I cannot test this because I do not have your whole code, here is how it could be done:
def get_image(width, height, collection_sku, order_id, name, handle):
"""image processing pipeline"""
# Check-1 image exception should be checked before proceeding further
# covers both images in exception(currently bookshelves) list and also personal true doors
# 1. bookshelves need to be cropped
# 2. personal TD images needs to be added in the required size when it's submitted by the user.
if not helpers.image_exception(collection_sku):
return None
# Step-1 Find image folder
directory_sizes = helpers.find_directory(width, height)
if directory_sizes is None:
return None
# Step-2 Find the image from the given folder.
key = helpers.find_image(directory_sizes, collection_sku)
if key is None:
return None
requires_resize = helpers.should_resize(width, height)
requires_flip = helpers.should_flip(handle) and not helpers.flip_exception(collection_sku)
# Check-2 check whether image requires resizing or flipping
if requires_resize or requires_flip:
# Step-3 Create local directory to store temporary images
location, is_created = helpers.local_directory(
order_id)
if not is_created:
return None
# Step-4 Download image
image = helpers.download_image(key, location, name)
if image is not None:
width_px = helpers.cm_to_pixel(width)
height_px = helpers.cm_to_pixel(height)
image_modified = False
# Step-5.1 Resize image
if requires_resize:
helpers.resize_image(image, width_px, height_px)
image_modified = True
# Step-5.2 Flip image
if requires_flip:
helpers.flip_image(image)
image_modified = True
# Step-6 Upload image
if image_modified:
helpers.upload_image(image, key)
# Step-3 No local dir created
# Step-4 Can't download image
# Step-5.1 Can't resize image
# Step-5.2 Can't flip image
# Step-6 Can't upload image
# Check-2 if no image processing required then copy image over
helpers.copy_image(key, target = None) # TODO
return True
# raise exception in sub job
# Check-1 if image door image cannot be processed
# Step-1 if directory not available
# Step-2 if image not available
This, for me, vastly increases readability -- before, it was hard to figure out which if-statements do what (especially with fragments of code at the ends of them). However, your comments are useful in describing the process as it goes along.
I'm sure it could be flattened more, but this should demonstrate the idea of it. Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
(Pre)select checkboxes in a ListActivity using 'simple_list_item_checked'
I'm using the ListActivity class in conjunction with the simple_list_item_checked-layout which implements simple list items with checkboxes. Everything is working fine - clicking added items calls onListItemClick() and I can check/uncheck respective checkboxes of entries via the 'View v' parameter.
However what I wasn't able to figure out yet is, how to (pre)select checkboxes without any userinteraction?
Minimal so far working code snippet showing my intend:
package org.test;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
public class TestActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> list_elems = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked);
list_elems.add("foobar");
//TODO: check added entry labeled "foobar"
setListAdapter(list_elems);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
CheckedTextView check = (CheckedTextView)v;
check.setChecked(!check.isChecked());
}
}
Thanks a lot in advance!
daten
A:
This works for me:
You have to set the choicemode of the underlying ListView to single or multiple.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> list_elems = new ArrayAdapter<String>(this, Android.R.layout.simple_list_item_checked);
list_elems.add("foobar");
//TODO: check added entry labeled "foobar"
setListAdapter(list_elems);
ListView lv = getListView();
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setItemChecked(0, true);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove sub IEnumerable from IEnumerable
I have a IEnumerable<Byte> from which I want to remove a sequence of bytes that could appear only once. The first array can be quite big but the second one cannot exceed 50bytes
What is the best way (and fastest way) to do that ?
Thanks for your help !
A:
You can create static method for that, something like this:
public static class Helper
{
public static IEnumerable<byte> RemoveSubSequence(this IEnumerable<Byte> sequence, IEnumerable<Byte> subSequence)
{
List<byte> list = sequence.ToList();
byte[] subSequenceList = subSequence.ToArray();
int i = 0;
int count = 0;
for (; i < list.Count && count != subSequenceList.Length; i++)
for (int i2 = 0; i2 < subSequenceList.Length && count != subSequenceList.Length; i2++)
if (list[i + i2] == subSequenceList[i2]) count++; else count = 0;
list.RemoveRange(i - 1, count);
return list;
}
}
Then you can use it like:
IEnumerable<byte> bytes = new byte[] { 5, 7, 6, 9, 1, 5, 7, 6, 7, 0, 6, 4, 0, 6, 4, 8 };
IEnumerable<byte> subSequence = new byte[] { 6, 7, 0, 6, 4, 0, 6, 4, 8 };
bytes = bytes.RemoveSubSequence(subSequence);
foreach (var item in bytes) Console.Write(item + " ");
Console.WriteLine("\n\n");
Output : 5, 7, 6, 9, 1, 5, 7,
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I specify a 'supertype' relation in C# generic constraints?
I have a collection class with an Equals method that I want to pass in a method to do equality checking between each item. Furthermore, I want to allow the delegate type to operate on superclasses of T as well as T itself:
public delegate bool EqualityComparer<T>(T x, T y);
public class Collection<T>
{
//...
public bool Equals<U>(Collection<T> other, EqualityComparer<U> eq) where T : U
{
// code using eq delegate to test equality between
// members of this and other collection
}
}
Unfortunately, the compiler borks over this ('Collection.Equals()' does not define type parameter 'T'). Is there any way of specifying this type of constraint/operation?
A:
No, I'm afraid you can't specify a constraint like that. (I've wanted it too on occasion.)
You could write a static generic method with two type parameters in a non-generic class though:
public delegate bool EqualityComparer<T>(T x, T y);
public class Collection
{
public static Equals<T, U>(Collection<T> first,
Collection<T> second,
EqualityComparer<U> comparer) where T : U
{
}
}
and you could even make that call an instance method on the generic class if you like:
// Implementing the static method:
return first.Equals(second, new EqualityComparer<T>(comparer));
where the collection's instance method would just be:
public bool Equals(Collection<T> other, EqualityComparer<T> eq)
{
// ...
}
This uses the contravariance available for creating delegates from C# 2 onwards.
| {
"pile_set_name": "StackExchange"
} |
Q:
Observable stops emitting when nested error handler calls onExceptionResumeNext
In the following code, I have a nested observable. The sendMessage in the flatMap calls the sendMessage function which is also an observable. If an exception occurs in this nested observable, the onExceptionResumeNext is suppose to catch the exception, process the exception and then continue on as though nothing happened. The exception does get caught but once the processing on the exception completes, no further emissions are made in the stream. Not even the doOnComplete is called. In essence, the onExceptionResume next just hangs.
I have tried onErrorReturnItem but have the same result. I have not found a single example in Stackoverflow or elsewhere for that matter that even shows onExceptionResumeNext or onErrorResumeNext or onErrorReturnItem inside a nested observable and after a day of working on it, I suspect that it may not be possible to support a nested error handler.
NOTE: In the onExceptionResumeNext I am currently just returning
Observable.empty<MessageToSend>()
In my actual code, I have code to process the exception and I tried returning an observable as well as just returning the data. Doesn't matter what I do - it always hangs.
fun postMessages() {
val msgToSendPublisher = BehaviorSubject.createDefault(MessageToSend())
msgToSendPublisher
.flatMap { _ ->
App.context.repository.getMessageToSend().toObservable()
}
.doOnError { error ->
if (error is EmptyResultSetException)
App.context.repository.setSendStatusToNotSendingForAllMessages()
}
.doOnNext { messageToSend ->
App.context.repository.updateMessage(messageToSend)
}
.flatMap { messageToSend ->
App.context.repository.sendMessage(messageToSend)
}
.doOnNext { messageToSend ->
messageToSend.dateSent = Date()
App.context.repository.updateDateLastMessageSent(messageToSend)
}
.doOnNext { messageToSend ->
if (messageToSend.totalMessagesToSend == 1)
App.context.repository.updateSendStatus(messageToSend, MessageSendStates.NOT_SENDING)
else
Observable.just(messageToSend)
}
.doOnNext {
msgToSendPublisher.onNext(it)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ messageToSend ->
},
{ ex ->
onMessagesSent()
},
{
onMessagesSent()
}
)
}
fun sendMessage(messageToSend: MessageToSend): Observable<MessageToSend> {
val obs = Observable.fromCallable {
if (messageToSend.totalMessagesToSend == 3)
throw Exception("Couldn't send to recipient.")
messageToSend
}.map {
storeMessageSent(messageToSend)
}.onExceptionResumeNext {
Observable.empty<MessageToSend>() // Hangs here.
).doOnComplete {
addNewMessageIfRequired(messageToSend, newMessage)
}
return obs
}
UPDATE:
I decided to test out a sample code I found that uses onExceptionResumeNext. It looks like this:
Observable.fromArray(1, 2, 3)
.doOnNext {
if (it == 2) {
throw (RuntimeException("Exception on 2"))
}
}
.onExceptionResumeNext(
Observable.just(10)
)
.subscribe(
{
var x = it
},
{
var x = it
},
{
var x = 0
x++
}
)
If you put a breakpoint on the line inside of the onExceptionResumeNext, it will get called every single time you run the observable for the first time and not just when the exception is thrown. This is clearly a behavior that is not identified in the RxJava documentation. Any developer will be under the impression that it will only get called when an exception is thrown. In the example above, setting the value to 10 is not really an issue. It's effectively just setting up the return value for the case when an exception occurs. However, if this was more elaborate code that stores stuff in the database (which my app does), it will get called when the observable is initialized - which is really bad. In spite of this discovery, it still does not solve my problem in that no further items are emitted. What I did discover in the sample code is that when onExceptionResumeNext is called, the onComplete is also called. Too bad the documentation doesn't mention that either.
A:
You may want to use defer to defer execution of function calls that result in side-effects upon call:
Observable<Integer> createFallback() {
System.out.println("Why is this executing now?!");
return Observable.empty();
}
Observable.<Integer>error(new Exception())
.onExceptionResumeNext(createFallback())
.subscribe();
The createFallback runs because you specified it to run by invoking it. If the sequence is rewritten, it should become more apparent why:
Observable<Integer> fallback = createFallback();
Observable.<Integer>error(new Exception())
.onExceptionResumeNext(fallback)
.subscribe();
Now if you comment out the error-observable part, does it still execute createFallback()? Yes and RxJava is not even involved at that point yet.
If you want the side-effects to not happen to createFallback this way, you have to defer the execution of the entire method, there is an operator for that purpose: defer:
Observable.<Integer>error(new Exception())
.onExceptionResumeNext(Observable.defer(() -> createFallback()))
.subscribe();
I presume this looks something like this in Kotlin:
Observable.error(new Exception())
.onExceptionResumeNext(Observable.defer { createFallback() })
.subscribe()
| {
"pile_set_name": "StackExchange"
} |
Q:
Change attribute after resize ? AngularJS
I use angular-ui carousel ,and my directive now looks like this
<ui-carousel slides="value"
slides-to-show="calculateGamesCount"
slides-to-scroll="calculateGamesCount">
...
</ui-carousel>
Directive scope:
show: '=slidesToShow',
scroll: '=slidesToScroll',
From parent controller i get "calculateGamesCount" , but after window resize carousel directive attrs dont change, its stay the same.
$scope.calculateGamesCount = Math.floor(( window.innerWidth - 90 ) / 232 );
// Get value after resize
angular.element($window).bind('resize',function(){
$scope.$apply(function(){
$scope.calculateGamesCount = Math.floor(( window.innerWidth - 90 ) / 232 ) ;
});
});
How i can fix it ?
A:
Well there's workaround for your condition. You can have following generic directive which watches change in window size. Then you can watch the windowWidth variable in your controller which set every time there's change in window width inside directive. Inside watch function you first delete the ui-carousel component on your view by using ng-if then assign newly calculated value of calculateGamesCount & then make ng-if to true. By doing this your directive will be re-rendered every time there's change in window width.
app.directive('resize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
scope.getWindowDimensions = function () {
return {
'h': w.height(),
'w': w.width()
};
};
scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
scope.windowHeight = newValue.h;
scope.windowWidth = newValue.w;
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});
Inside controller add this code:
$scope.$watch('windowWidth', function(n, o){
$scope.showCarousel = false;
$timeout(function(){
$scope.calculateGamesCount = Math.floor(( window.innerWidth - 90 ) / 232 );
$scope.toShow = angular.copy($scope.calculateGamesCount);
console.log($scope.calculateGamesCount);
$scope.showCarousel = true;
});
});
You can have resize directive on any parent element of ui-carousel tag directive.
Working plunker example: https://plnkr.co/edit/ebi2b2z9o1IlbIMBcu8r?p=preview
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding a horizontal rule between caption and lstlisting inside a tcolorbox
I have example listings for a book.
I'd like a horizontal rule the width of the tcolorbox between the caption and the listing.
The code used to produce it:
\documentclass[letterpaper,oneside,12pt]{book}
\usepackage{listings}
\usepackage[most]{tcolorbox}
\usepackage{caption}
\usepackage{xcolor}
\definecolor{shadecolor}{gray}{0.95}
\definecolor{captionbox}{cmyk}{0.43, 0.35, 0.35,0.01}
\tcbset{colback=captionbox!5!white,colframe=captionbox!75!black}
\BeforeBeginEnvironment{lstlisting}{\begin{tcolorbox}[toprule=3mm]\vskip-.5\baselineskip}
\AfterEndEnvironment{lstlisting}{\end{tcolorbox}}
\DeclareCaptionFormat{listing}{\parbox{\textwidth}{#1#2#3}}
\captionsetup[lstlisting]{format=listing,skip=10pt}
\lstset{numbers=none}
\begin{document}
\begin{lstlisting}[caption=Sample code block]
This is a code block
\end{lstlisting}
\end{document}
My only constraint is that I need to use the listings package and lstlisting because Pandoc requires that for listings. I am happy to replace anything else to produce the same effect of a box around the caption and listing with the rule between the caption and listing and a similar style feel.
A:
Update: changed overlay first to overlay unbroken and first for the line to also appear in unbroken boxes. My mistake.
Too bad you can't use tcblistings, which seems to have been made specifically for this purpose and internally uses listings (I've read but not verified this).
Although I do not like "specific" solutions (i.e. solutions which need manual fiddling), I nonetheless propose this to you simply because it "works":
\documentclass[letterpaper,oneside,12pt]{book}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{tcolorbox}
\tcbuselibrary{breakable}
\tcbuselibrary{skins}
\usepackage{caption}
\usepackage{tikz}
\usepackage{lipsum}
\definecolor{shadecolor}{gray}{0.95}
\definecolor{captionbox}{cmyk}{0.43, 0.35, 0.35,0.01}
\tcbset{%
colback=captionbox!5!white,%
colframe=captionbox!75!black,%
top=1mm,% %% Used to manually align the caption with the horizontal line
%
%% Create a new "style" for your titled listings tcolorbox
mylistingwithtitle/.style = {%
breakable,%
%% Use tcolorbox's internal tikz object name (frame) to draw a horizontal line
overlay unbroken and first={\draw[shorten >=1.4pt, shorten <=1.4pt] ([yshift=-3em]frame.north west) -- ([yshift=-3em]frame.north east);}%
}%
}
\BeforeBeginEnvironment{lstlisting}{%
\begin{tcolorbox}[enhanced, toprule=3mm, mylistingwithtitle]%
\vskip-.5\baselineskip%
}
\AfterEndEnvironment{lstlisting}{\end{tcolorbox}}
\DeclareCaptionFormat{listing}{\parbox{\textwidth}{#1#2#3}}
\captionsetup[lstlisting]{format=listing,skip=15pt}
\begin{document}
%% This following line is only useful to execute \lipsum[1-4] inside the listing
\lstset{numbers=none, escapeinside={(*}{*)}}
\begin{lstlisting}[caption=Sample code block]
This is a code block
(*\lipsum[1-4]*)
\end{lstlisting}
\end{document}
If you change the caption formatting, you will need to manually fiddle with the vertical spacing, i.e the top=1mm option for the tcolorbox and the [yshift=-3em] to draw the horizontal line. You will also have to fiddle with the latter option, along with the shorten >=1.4pt and shorten <=1.4pt options, if you decide to change the formatting (top line, border width, inner margins, etc.) of the tcolorbox.
I took the liberty to add the breakable option to the tcolorbox to allow it to break over several pages.
Output:
| {
"pile_set_name": "StackExchange"
} |
Q:
Функция возвращающая табличное значение в SQL Server
Приветствую.
Имеется созданная функция возвращающая табличное значение. В ней, допустим, есть переменная @x и временная таблица, которая заполняется полями из запроса. Запрос возвращает две колонки значений: dir и amount. Нужно сделать следующее:
Если dir = 1 тогда @x = @x + amount
Если dir = 2 тогда @х = @х - amount
Как мне это реализовать в SQL Server? В PHP я бы сделал так:
$x = 0;
while ( $res = mssql_fetch_array(*результат моего запроса*) )
{
if ($res['dir'] == 1) $x += $res['amount'];
else $x -= $res['amount'];
}
A:
select @x = @x + case when dir = 1 then amount
when dir = 2 then -amount end
from ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel 5.5 - ReflectionException (-1) Class does not exist
I am trying to use ReflectionClass to get file name(from app directory) from a controller. For testing whether I can use the ReflectionClass or not i was trying in following way:
In my MyController.php
public function readContent()
{
$files = app_path() . DIRECTORY_SEPARATOR. "Drama.php";
// It returns "F:\xampp\htdocs\projectDirectory\app\Drama.php"
$class = new ReflectionClass($files);
echo "file name:: ". $class->getFileName();
}
I have a Drama.php file in this path. But when I am running the route for this method, I get following error
ReflectionException (-1)
Class F:\xampp\htdocs\projectDirectory\app\Drama.php does not exist
I have updated my composer.json file like following:
"autoload": {
"classmap": [
"app",
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
So that, i can read my app directory files.
I also ran the following commands
composer dump-autoload
composer update
php artisan config:clear
php artisan cache:clear
But i am still getting this error. Can anyone tell me how can i resolve this ?
A:
Your issue here is ReflectionClass takes the class path as the constructor argument, not file path. try new ReflectionClass('\App\Drama') instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
Azure File Share ListFilesAndDirectoriesSegmentedAsync() Fails Authentication
I am using the c#.net api to work with azure file storage but cannot successfully list all files in a fileshare. My code errors with:
Microsoft.WindowsAzure.Storage: Server failed to authenticate the
request. Make sure the value of Authorization header is formed
correctly including the signature.
The following code works perfectly, so my connection to the fileshare 'temp' is fine:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
CloudFileShare share = fileClient.GetShareReference("temp");
CloudFile f = share.GetRootDirectoryReference().GetFileReference("Report-461fab0e-068e-42f0-b480-c5744272e103-8-14-2018.pdf");
log.Info("size " + f.StreamMinimumReadSizeInBytes.ToString());
The code below results in the discussed authentication error:
FileContinuationToken continuationToken = null;
do
{
var response = await share.GetRootDirectoryReference().ListFilesAndDirectoriesSegmentedAsync(continuationToken);
continuationToken = response.ContinuationToken;
}
while (continuationToken != null);
Any help would be appreciated.
Thanks.
A:
Using key 1 instead of key resolved the issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find/choose a criminal lawyer in another state?
I am seeking an attorney, in a state other than my own (in the USA), to provide me with guidance in the area of criminal law. (I have some specific questions.) How might I go about finding such an attorney other than look at ads? What might indicate a really knowledgeable criminal attorney?
First update: 1. What type of work experience might indicate a really knolwedgeable criminal law attorney. For example, one attorney has 10 years experience as an Assistant United States Attorney. Is that a big plus or a Ho-hum? (Such information is available on https://www.justia.com/lawyers.)
2. Is there any value to such designations as "super lawyer": https://attorneys.superlawyers.com/
Second update:
3. Super doctor/lawyer websites seem to be a scam, per these reviews:
https://www.propublica.org/article/top-doctors-award-journalist
https://abcnews.go.com/Health/top-doctor-awards-deserved-abc-news-investigation/story?id=16771628
Third Update:
4. One comment said there was a legitimate ranking site for lawyers:
https://chambers.com
Unfortunately, it seems not to rate criminal law attorneys: https://chambers.com/research/practice-area-definitions-usa
5. These two sites say that "super lawyer" sites are a scam:
https://www.larrybodine.com/lawyers-cheering-the-uncloaking-of-bogus-accolades
http://www.abajournal.com/news/article
Fourth Update:
6. This site rates attorneys and seems legit:
https://www.avvo.com/
A:
It will be very difficult to find an attorney using the type of metrics that you seem most interested in.
We could say that the best attorneys are the ones who have won the most trials, but wouldn't you rather not go to trial in the first place? So is the best attorney the one who gets the best plea bargains? Maybe, but that's a lot harder to keep track of. And of course, it would be better still if the attorney were able to persuade prosecutors not to charge you to begin with. And that's going to be virtually impossible to track.
If I were looking for a defense attorney, I'd probably be glad to hire someone with significant experience as a prosecutor. That experience gives the lawyer first-hand knowledge of how the government will view the evidence, prioritize the case, and handle the prosecution. And of course, they're likely to have better relationships with prosecutors, which can go a long way in pretrial negotiations.
Lawyers know who among them are the best and worst, so you can probably just call a few firms and ask if they handle your type of case. If they don't, you can ask if they know anyone who does. If you make enough calls, you'll start to see some names start floating to the top.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is a bishop in Roman Catholic tradition equal in authority with the apostles?
According to an answer to this question When did Peter become the first Pope, according to Roman Catholic doctrine?, the Pope is the bishop of Rome.
So this made me wonder - since Peter was ordained an Apostle (not bishop of Rome) and he is considered the first Pope - are bishops equal in authority with apostles according to Roman Catholic tradition?
I understand what apostolic succession is, but it doesn't seem clear from this that it's the actual apostolic authority or just a part of it handed down to the bishops from the original apostles.
A:
Bishops (from the Greek, epi-scopus = overseers) are the successors of the Apostles. Their primary responsibility is shepherding the faith of the people in their diocese. They ordain priests, perform the sacrament of confirmation on the faithful, and serve to teach, provide guidance and support for the faithful. So in that sense, they indeed have the authority of the Apostles. However, a tenet of the Catholic Church is that public revelation ceased with the death of the last apostle.
The Christian dispensation, therefore, as the new and definitive covenant, will never pass away and we now await no further new public revelation before the glorious manifestation of our Lord Jesus Christ
Vatican II, Dei Verbum 4
Only apostles had firsthand knowledge of the teachings of Jesus. Therefore, no Bishop can add to public revelation. They may explain or further develop the implications of sacred revelation, whether by Scripture or the sacred Tradition of the Apostles.
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing OpenCV Image as function argument with ctypes
I have written some optimized C++ code for FLANN Matching with SIFT features (OpenCV) that returns the number of good matches (int) found on two images. My code works well when I pass the two image paths (query and train images) as char* via ctypes. I am writing a wrapper class in Python to handle these functions. However, I want to pass the two arguments as image instances and not as char* or std::string, namely the objects that are results of cv2.imread(apath) in Python OpenCV bindings.
My .cpp source code:
//detectors.cpp
#include <stdio.h>
#include <iostream>
#include "string.h"
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/nonfree/features2d.hpp"
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
///* (extern c) Get good matches using SIFT and FLANN Matcher * ///
extern "C" int get_matches_sift_flann(char* img1, char* img2)
{
Mat img_1 = imread(img1, CV_LOAD_IMAGE_GRAYSCALE );
Mat img_2 = imread(img2, CV_LOAD_IMAGE_GRAYSCALE );
//-- Step 1: Detect the keypoints using SIFT Detector
int minHessian = 400;
SiftFeatureDetector detector( minHessian );
std::vector<KeyPoint> keypoints_1, keypoints_2;
detector.detect( img_1, keypoints_1 );
detector.detect( img_2, keypoints_2 );
//-- Step 2: Calculate descriptors (feature vectors)
SiftDescriptorExtractor extractor;
Mat descriptors_1, descriptors_2;
extractor.compute( img_1, keypoints_1, descriptors_1 );
extractor.compute( img_2, keypoints_2, descriptors_2 );
//-- Step 3: Matching descriptor vectors using FLANN matcher
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match( descriptors_1, descriptors_2, matches );
double max_dist = 0; double min_dist = 100;
//-- Quick calculation of max and min distances between keypoints
for( int i = 0; i < descriptors_1.rows; i++ )
{ double dist = matches[i].distance;
if( dist < min_dist ) min_dist = dist;
if( dist > max_dist ) max_dist = dist;
}
//-- Draw only "good" matches (i.e. whose distance is less than 2*min_dist,
//-- or a small arbitary value ( 0.02 ) in the event that min_dist is very
//-- small)
//-- PS.- radiusMatch can also be used here.
vector< DMatch > good_matches;
for( int i = 0; i < descriptors_1.rows; i++ )
{ if( matches[i].distance <= max(2*min_dist, 0.02) )
{ good_matches.push_back( matches[i]); }
}
int n = (int) good_matches.size();
return n;
}
And my python wrapper.py module
#wrapper module for libdetectors.so
import os
import ctypes as c
libDETECTORS = c.cdll.LoadLibrary('./libdetectors.so')
class CExternalMatchesFunction:
def __init__(self, c_func):
self.c_func = c_func
self.c_func.argtypes = [c.c_char_p, c.c_char_p]
self.c_func.restype = c.c_int
def __call__(self, train_img_filename, query_img_filename):
r = self.c_func(c.c_char_p(train_img_filename), c.c_char_p(query_img_filename))
return r
#initialize wrapped functions
get_matches_sift_flann = CExternalMatchesFunction(libDETECTORS.get_matches_sift_flann)
All in all, I want to change CExternalMatchesFunction().c_func.argtypes to a list of image objects like these:
import cv2
img1 = cv2.imread('foo.jpg')
img2 = cv2.imread('boo.jpg')
Thanks in advance
A:
SOLUTION: Return void* and cast it again to cpp object when passed
| {
"pile_set_name": "StackExchange"
} |
Q:
Regressing a column against itself
Regressing a variable against itself should give a slope of 1.
I have a dataframe where I want to regress several columns (including a fixed column 'i') against the fixed column 'i'.
The slope coefficients from each regression are needed for a plot.
But the regression of col 'i' against itself gives no slope row in the summary.
a <- rnorm(100, 22,4) # some data
b <- rnorm(100, 30,7) # only to create a dataframe
df <- data.frame(cbind(a,b))
head(df)
summary(lm(data = df, a~a)) # regress a against itself
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 22.2602 0.3504 63.53 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Why is there no slope coefficient?
A:
Your code generates 2 warnings, the second arises because of the first:
Warning messages:
1: In model.matrix.default(mt, mf, contrasts) :
the response appeared on the right-hand side and was dropped
2: In model.matrix.default(mt, mf, contrasts) :
problem with term 1 in model.matrix: no columns are assigned
So your column of interest is dropped from the formula and hence is no slope coefficient, just intercept.
A:
This is because you are using the same name for both the dependent and the independent variable. If you just copy a to the b variable, it works:
df <- data.frame(cbind(a,b=a))
summary(lm(data = df, a~b))
Call:
lm(formula = a ~ b, data = df)
Coefficients:
(Intercept) b
-0.00000000000001137 1.00000000000000044
| {
"pile_set_name": "StackExchange"
} |
Q:
Listview in C# does not show any properties
I'm trying to use a simple ListView. I dragged one in my XAML file, name it, and trying to acces it in code. Yet all the properties like .Column are not available.
When I try to make a listview by code, it doesn't work either. What am I missing here? I added System.Windows.Forms
System.Windows.Forms.ListView testView = new System.Windows.Forms.ListView();
(System.Windows.Forms.ListView)lsView.Column // Can't find the property at all..
Other objects work just fine, like a ListBox for instance. I'm using the WPF .NET Framework
A:
You should use the System.Windows.Controls.ListView in WPF. It has a View property that you can set to a GridView which in turn has a Columns property:
System.Windows.Controls.ListView testView = new System.Windows.Controls.ListView();
System.Windows.Controls.GridView gridView = new System.Windows.Controls.GridView();
testView.View = gridView;
gridView.Columns.Add(new GridViewColumn() { Header = "...", DisplayMemberBinding = new Binding("Property") });
| {
"pile_set_name": "StackExchange"
} |
Q:
Efficiency of Stirling engine and Carnot's theorem
I want to calculate the efficiency of this Stirling cycle for an ideal gas $pV = nRT$
The mechanical work is
$$
\Delta W_{12} = - \int_{V_1}^{V_2} p(V) \mathrm{d}V = -nRT_2 \ln \frac{V_2}{V_1}\\
\Delta W_{23} = \Delta W_{41} = 0\\
\Delta W_{34} = -nRT_1 \ln \frac{V_1}{V_2}
$$
On the isothermal curves the change in inner energy $\Delta U = \Delta W + \Delta Q$ is zero.
$$
\Delta Q_{12} = - \Delta W_{12} > 0\\
\Delta Q_{34} = - \Delta W_{34} < 0
$$
On the isochoric (isovolumetric) curves the heat quantities are
$$
\Delta Q_{23} = C_V (T_1 - T_2) < 0\\
\Delta Q_{41} = C_V (T_2 - T_1) > 0
$$
The efficiency is then
$$
\eta = \frac{-\Delta W}{\Delta Q}
$$
$ \Delta Q$ is the input heat, i.e. sum of all the heat quantities $> 0$:
$$
\Delta Q = Q_{12}+Q_{41} = n R T_2 \ln \frac{V_2}{V_1} + C_V (T_2 + T_1)
$$
$\Delta W$ is the total mechanical work:
$$
\Delta W = W_{12}+\Delta W_{34} = - nR(T_2 - T_1) \ln \frac{V_2}{V_1}
$$
So finally the efficiency is
$$
\eta = \frac{T_2 - T_1}{T_2 + \frac{C_V (T_2 - T_1)}{nR \ln V_2 / V_1}} < \eta_\text{C}.
$$
It is smaller than the efficiency of the Carnot cycle. But it should be equal to it if all processes are done reversibly.
The calculations are taken from a textbook (Nolting: Grundkurs Theoretische Physik 4) which actually points out this problem as a question to the reader. My only explanation is that this process is not reversible but I don't know how to tell without actually seeing how the isothermal and isochoric processes are realized.
So my questions are:
Is this a contradiction to Carnot's theorem that the efficiency $\eta_\text{C} = 1 - T_1/T_2$ is the same for all reversible heat engines between two heat baths?
Is this cycle reversible?
Is there a way to say whether a process is reversible or irreversible only with a figure like the one above?
A:
Revamped Answer. 2017-07-01
There is no contradiction because your analysis only includes what happens to the gaseous working substance in the Stirling engine, and it neglects a crucial component of the engine called the regenerator. If the regenerator is not included as a component of the engine when we perform the efficiency analysis, then we don't have a device that qualifies as a heat engine operating between two temperatures, and we therefore shouldn't expect it to abide by Carnot's Theorem as I stated in the original version of this answer.
However, if we properly take account of the regenerator, then we find that the efficiency of the engine is the Carnot efficiency.
Of course the whole analysis here is an idealized one in which we assume, for example, that there are no energy losses due to friction in the engine's components.
Details.
A stirling engine is more complex than the $P$-$V$ diagram drawn in the question statement seems to indicate. If we conceptually reduce the engine to its simplest form, it contains two fundamental components:
A gaseous working substance. This is the part of the engine whose thermodynamic state travels along the curve in the $P$-$V$ diagram.
A regenerator. This part of the engine absorbs and stores the energy given up by the gaseous working substance by heat transfer during the process $2\to 3$ and then returns that same energy to the gaseous working substance during the process $4\to 1$.
The crucial point is that when the regenerator is included, there is no net heat transfer into or out of the engine during the processes $2\to 3$ and $4\to 1$. The energy that leaves the gaseous working substance during the process $2\to 3$ by heat transfer is stored in the regenerator, and that heat is then given back up to the working substance during process $4\to 1$. No heat is transferred between the engine and its surroundings during these legs of the cycle.
It follows that the only heat transferred to the engine as a whole is transferred during $1\to 2$. This qualifies the device as a heat engine (see old answer below) and the efficiency of the engine is then computed as the ratio of the net work output divided by the heat input in process $1\to 2$. This yields the Carnot efficiency as it should.
My original answer claimed that the cycle drawn does not represent the operation of a heat engine operating between two temperatures, but I was neglecting the regenerator, and I believe this is what you implicitly did in the computation you originally performed as well, and this yielded the incorrect efficiency.
Original, incomplete answer.
There is no contradiction. The Stirling cycle you drew above is reversible but does not operate between two reservoirs at fixed temperatures $T_1$ and $T_2$. The isovolumetric parts of the cycle operate at continuously changing temperatures (think ideal gas law).
Old Addendum. Note that in thermodynamics, a heat engine is said to operate (or work) between (two reservoirs at) temperatures $T_1$ and $T_2$ provided all of the heat it absorbs or gives up is done so at one of those two temperatures.
To give credence to this definition (which is essentially implicit in most discussions of heat engines I have seen), here is a quote from Fermi's thermodynamics text:
In the preceding section we described a reversible cyclic engine, the Carnot engine, which performs an amount of work $L$ during each of its cycles by absorbing a quantity of heat $Q_2$ from a source at temperature $t_2$ and surrendering a quantity of heat $Q_1$ to a source at the lower temperature $t_1$. We shall say that such an engine works between the temperatures $t_1$ and $t_2$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom Number Of Inputs
I need to enter UTM coordinates of certain polygons to a HTML form. I will handle the form values with php to insert into mysql db. But number of polygons and points of the polygons can be various. So text input boxes can be adjusted on the form.
+---------+------------+-----------+-------------+
| polygon | point | y | x |
+---------+------------+-----------+-------------+
| 1 | 1 | 0 | 0 |
+---------+------------+-----------+-------------+
| 1 | 2 | 0 | 50 |
+---------+------------+-----------+-------------+
| 1 | 3 | 50 | 50 |
+---------+------------+-----------+-------------+
| 1 | 4 | 50 | 0 |
+---------+------------+-----------+-------------+
| 2 | 1 | 50 | 75 |
+---------+------------+-----------+-------------+
| 2 | 2 | 50 | 100 |
+---------+------------+-----------+-------------+
| 2 | 3 | 75 | 75 |
+---------+------------+-----------+-------------+
Letting the user to enter number of points to create input boxes seems a good practice to me. However I'm not sure is the best practice to serialize values and handling the values with php ? Should I use JSON or just input names with indexes. Or something else?
Here is a simple example:
http://jsfiddle.net/UVZNq/
A:
You can try something like this:
+---------+------------+-----------+-------------+
| polygon | point | y | x |
+---------+------------+-----------+-------------+
***************
* Add Another *
***************
When the user presses 'Add Another` Submit the current point using Ajax and convert the existing (already submitted) point as simple text (rather than textbox) and add new set of text boxes.
This way the php script is handling a single point at a time and the UI is not cluttered either.
| {
"pile_set_name": "StackExchange"
} |
Q:
Animation of KML placemarks and description possible within KML only (Google Earth Tour)?
I'm dealing with animating a placemark and its description/label in a Google Earth Tour. So far I've accomplished animation of a placemark's tooltip ballon via
<gx:AnimatedUpdate>
<gx:duration>0.0</gx:duration>
<Update>
<targetHref/>
<Change>
<Placemark targetId="placemarkpin1">
<gx:balloonVisibility>1</gx:balloonVisibility>
</Placemark>
</Change>
</Update>
</gx:AnimatedUpdate>
But trying the same with a placemark and its description aka label (as in this tour it would make sense to show the placemark at the end) doesn't seem to work:
<gx:AnimatedUpdate>
<gx:duration>1.0</gx:duration>
<Update>
<targetHref></targetHref>
<Change>
<IconStyle targetId="pushpin-placemark_normalstate">
<scale>1.0</scale>
</IconStyle>
<LabelStyle targetId="pushpin-placemark_normalstate">
<scale>1.0</scale>
</LabelStyle>
</Change>
</Update>
</gx:AnimatedUpdate>
scale is per definition at beginning at 0.0
The both animations are in two separate gx:AnimatedUpdate siblings one after the other at the end of the tour.
I can only work in the KML file, there's no possibility to add JS in this project.
A:
Use unique ids for both the IconStyle and LabelStyle tags and refer to these in the targetHref for updates.
Note: Multiple changes can appear in a single <Change> element (as you have in your original example) or each can be wrapped in its own Change element as children of the <Update> element (as shown below).
<Style id="pushpin">
<IconStyle id="myiconstyle">
...
</IconStyle>
<LabelStyle id="mylabelstyle">
...
</LabelStyle>
</Style>
<gx:AnimatedUpdate>
<gx:duration>1.0</gx:duration>
<Update>
<targetHref></targetHref>
<Change>
<IconStyle targetId="myiconstyle">
<scale>1.0</scale>
</IconStyle>
</Change>
<Change>
<LabelStyle targetId="mylabelstyle">
<scale>1.0</scale>
</LabelStyle>
</Change>
</Update>
</gx:AnimatedUpdate>
You can find a complete example with a working tour doing exactly this here:
http://googlegeodevelopers.blogspot.com/2009/04/tours-in-kml-animating-camera-and.html
| {
"pile_set_name": "StackExchange"
} |
Q:
To get server date and time
i wrote the code to Fetch date and time from server not from client system. i write like this...
DateTime dt = new DateTime();
dt = DateTime.Now;
is this correct code?
A:
Invoking the DateTime constructor is not necessary. Use this instead:
var dt = DateTime.Now;
(This is equivalent, though slightly less verbose, than DateTime dt = DateTime.Now)
| {
"pile_set_name": "StackExchange"
} |
Q:
AngularJS dropdown select not working
I am using Angular to write a dropdown select menu with a few options that gets submitted to a database. In the front end html:
Role Type:
<select ng-model = "Role_Type">
<option ng-repeat="role in roles" value="{{role}}"> {{role}} </option>
</select>
In my controller, I have:
$scope.roles = ['Teacher', 'Student', 'Janitor', 'Principal'];
$scope.addNewEntry = function() {
entrys.addNewEntry({
Role_Type: $scope.role,
});
}
And in my backend (using Mongoose.js) schema, I have:
var EntrySchema = new mongoose.Schema({
Role_Type: String,
});
I am using the following code to display it back on the front end:
Role Type:
{{entry.Role_Type}}
But this does not work. Nothing is displayed back on the front end. Any ideas?
A:
Instead of using ng-repeat, try using ng-options which is meant for repeating values in a dropdown menu.
<select ng-model="Role_Type" ng-options="role for role in roles"></select>
| {
"pile_set_name": "StackExchange"
} |
Q:
To get the data attribute if a checkbox is checked
I have made a form to get value and data-cat from that form if checkbox is checked. Thanks to stackoverflow, I have achieve to get the values of form but cannot get a satisfying answer to achieve data attribute from jquery.
Html:
<div class="price-col-title-wrap">
<h4>Immer enthalten</h4>
<!-- <h3><span>CHF</span> <span id="immer-total">0</span>.-</h3> -->
<input type="checkbox" id="c1" class="immer" value="50" data-cat="Installation Wordpress" name="cc" onclick="return false" checked/>
<label for="c1"><span> </span> Installation Wordpress</label> <br/>
<input type="checkbox" id="c2" class="immer" value="50" data-cat="Basis SEO und Dynamic Sitemap" name="cc"/>
<label for="c2"><span> </span> Basis SEO und Dynamic Sitemap</label> <br/>
<input type="checkbox" id="c3" class="immer" value="50" data-cat="Adresse, Öffungszeiten, Telefon mit Call-Funktion für mobil" name="cc"/>
<label for="c3"><span> </span> Adresse, Öffungszeiten, Telefon mit Call-Funktion für mobil</label> <br/>
<input type="checkbox" id="c4" class="immer" value="50" data-cat="Seite für Datenschutz und Impressum" name="cc"/>
<label for="c4"><span> </span> Seite für Datenschutz und Impressum</label> <br/>
<input type="checkbox" id="c5" class="immer" value="50" data-cat="Social Media Follow (FB, G+, Twitter)" name="cc"/>
<label for="c5"><span> </span> Social Media Follow (FB, G+, Twitter)</label> <br/>
<input type="checkbox" id="c6" class="immer" value="50" data-cat="Kontaktformular + Google Map API" name="cc"/>
<label for="c6"><span> </span> Kontaktformular + Google Map API</label> <br/>
<h3><span>CHF</span> <span id="immer-total">0</span>.-</h3>
<input id="input" type="text" value="0"/>
<textarea id="t"></textarea>
</div>
I have a jquery to achieve the values from every checkbox but there's another attribute data-cat which contain a unique name for each checkbox.
My problem is to list the checked data-cat in the textarea whose id=t
upto now the js I am using is:
var inputs = document.getElementsByClassName('immer'),
total = document.getElementById('immer-total');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + add
var new_total = parseFloat(document.getElementById('input').value);
console.log(new_total);
document.getElementById('input').value=new_total + add
}
}
This is used to get the values from every checkbox
And after lots of query in stackoverflow I get a js to get the attribute
function updateTextArea() {
var cats = $('.immer').map(function(){
return this.dataset.cat
// or $(this).attr('data-cat')
}).get()
}
$(function() {
$('#price-col-title-wrap input').click(updateTextArea);
updateTextArea();
});
But it didn't help me. How can I get the data-cat in that textarea.
you can view it on my fiddle
A:
You can simply do:-
function updateTextArea() {
var cats = $('.immer').map(function() {
return $(this).data('cat');
}).get();
console.log(cats);
}
Returns in console:-
["Installation Wordpress", "Basis SEO und Dynamic Sitemap", "Adresse, Öffungszeiten, Telefon mit Call-Funktion für mobil", "Seite für Datenschutz und Impressum", "Social Media Follow (FB, G+, Twitter)", "Kontaktformular + Google Map API"]
To get the checked checbox data in textarea, you can do:
$('.immer').change(function() {
$('#t').val(this.checked ? $(this).data('cat') : '');
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How do we know that a string element in C is uninitialized?
Is there a way to know whether the element in a string in C has a value or not? I have tried using NULL, '', and ' ', but they don't seem to be working. I need to shift the characters down to index 0 without using stdlib functions.
#include <stdio.h>
int main()
{
char literal[100];
//literal[99] = '\0'
literal[98] = 'O';
literal[97] = 'L';
literal[96] = 'L';
literal[95] = 'E';
literal[94] = 'H';
int index = 0;
while(literal[index] != '\0')
{
if(literal[index] == NULL) // does not work
printf("Empty");
else
printf("%c", literal[index]);
++index;
}
getchar();
return 0;
}
A:
No. Since literal has automatic storage, its elements will not be initialized, the values in the array is undefined.
You could initialize every element to something special and check for that value.
e.g. you could change
char literal[100];
char literal[100] = {0};
to initialize every element to 0.
You'd have to change your while loop termination check to
while(index < 100) {
if(literal[index] == 0)
printf("Empty");
...
}
}
That might not be optimal if you need to perform more string manipulation on the array though, as 0 now means empty element and also 'end of string'.
A:
No, you can't do that. This is because it will have a value - there is just no way of knowing what that value is. This is why it is essential to initialise things to known values.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java. The same objects with different hashes
I have two objects from database (in database it is same object), but they have different hashes:
GroupType groupType = groupTypeDao.findById(3);
GroupType groupType1 = groupTypeDao.findById(3);
System.out.println(groupType);
System.out.println(groupType1);
I get this output:
GroupType@6040
GroupType@6041
Why is that? Technology stack: Spring, JavaFX, Hibernate.
I have another project with Spring and Hibernate. Configuration files are identical in the two projects. Hibernate version is identical also. But in another project this produce same hashcodes.
A:
What you've printed are object references. They are indeed different if you created each reference by calling new.
You need to override equals, hashCode, and toString according to "Effective Java" to get the behavior you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get locale in Spring WebFlux?
I want to get current locale but the context always return default locale. It works with MVC but not with WebFlux.
Thank for your help!
package co.example.demo.controller;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Locale;
@RestController
@RequestMapping("/hello")
public class HelloController {
private final MessageSource messageSource;
public HelloController(MessageSource messageSource) {
this.messageSource = messageSource;
}
@GetMapping
public String hello() {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("hello", null, locale);
}
}
A:
Do not use LocaleContextHolder in WebFlux environment but add Locale as a method parameter instead:
@RestController
public class LocaleController {
@GetMapping("/locale")
String getLocale(Locale locale) {
return locale.toLanguageTag();
}
}
Test:
$ curl localhost:8080/locale -H 'Accept-Language: en-US'
en-US
$ curl localhost:8080/locale -H 'Accept-Language: en-GB'
en-GB
For more info see:
Spring WebFlux. Annotated Controllers. Method Arguments
| {
"pile_set_name": "StackExchange"
} |
Q:
Pythonic way to increment keys and values in dictionary
I have a dictionary of keys and values, both of which are ints. Is there an easy and efficient way to increment all the keys and values in the dictionary?
A:
Given existing dictionary d:
d = {k+1: v+1 for k, v in d.items()}
This creates a new dictionary. You cannot change dictionary keys in place.
However, first consider whether you really need to create a new dictionary. For example, instead of accessing key k of your new dictionary, you could access key k-1 of your old dictionary, then add one to the value.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use Box 2 D on google colab
I am currently trying to optimize OpenAIGym's BipedalWalker with neat.
In order to use Bipedalwalker, it is necessary to install Box 2 D, but a problem arises.
In order to install Box 2 d on colab, we did the following first.
!apt-get install python-box2d > /dev/null
!pip install gym[Box_2D]
import gym
env = gym.make("BipedalWalker-v2")
However, this caused the following error
/usr/local/lib/python3.6/dist-packages/gym/envs/box2d/lunar_lander.py in <module>()
2 import numpy as np
3
----> 4 import Box2D
5 from Box2D.b2 import (edgeShape, circleShape, fixtureDef, polygonShape, revoluteJointDef, contactListener)
6
ModuleNotFoundError: No module named 'Box2D'
Since it did not work in the earlier method, next time I put Box 2 D, I tried the following.
!apt-get -qq -y install swig> /dev/null
!apt-get install build-essential python-dev swig python-pygame subversion > /dev/null
!git clone https://github.com/pybox2d/pybox2d
!python pybox2d/setup.py build
However, the following error also occurred with this method.
Traceback (most recent call last):File "pybox2d/setup.py", line 151, in <module>
write_init() File "pybox2d/setup.py", line 66, in write_init
license_header = open(os.path.join(source_dir, 'pybox2d_license_header.txt')).read()FileNotFoundError: [Errno 2] No such file or directory: 'Box2D/pybox2d_license_header.txt'
What is a good way to put Box 2d on colab?
A:
Following worked for me in colab:
!pip install box2d-py
!pip install gym[Box_2D]
import gym
env = gym.make("BipedalWalker-v2")
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I use a NAS for SQL Server?
Possible Duplicate:
SQL Server Files Local or NAS or SAN?
Hi,
I have just bought a NAS (NETGEAR Stora) for our home office - 2 Windows PCs.
I want to run a small database that both machines can access. I am building a c# winform app that is going to access it and I was hoping the entire database could reside on the NAS. Can you install SQL Server on a NAS? Is this possible or would one of the machines instead have to have SQL installed and then have the sql files on the NAS instead. The reason I was wanting to have the entire sql on the NAS was becuase then only the nas would need to be turned on and not have to rely on both the sql hosting pc and the NAS.
If it can be done how do i do it? Just point to the NAS during installation or...?
Any advice appreciated
thanks
A:
No. Your NAS is a 'dumb storage' device, not a server capable of hosting a piece of software like SQL.
As a storage device, it's also file-level rather than block-level (you cannot ask the device for only a small piece of a file, you have to take/put the whole file at once), which means you can't have concurrent access from multiple sources just by placing your data files onto the device. This is something you'd need a block-level file sharing system for (e.g. iSCSI/Fiber Channel SAN)
| {
"pile_set_name": "StackExchange"
} |
Q:
The usage of "in + past tense of a verb"
Then the wolf was very angry indeed, and declared he would eat up the
little pig, and that he would get down the chimney after him. When the
little pig saw what he was about, he hung on the pot full of water,
and made up a blazing fire, and, just as the wolf was coming down,
took off the cover, and in fell the wolf; so the little pig put on the
cover again in an instant, boiled him up, and ate him for supper, and
lived happy ever afterwards.
This is from "The story of The Three Little Pigs" in English fairy tales.
I think "in fell the wolf" means "the wolf fell in the pot" but I don't know the usage of "in + a past tense of a verb" like "in fell". The usage like this is commonly used?
A:
You are correct, this is just a different way to say "the wolf fell in [the pot]".
It is not a special structure with 'in' and verb past tenses, just a different arrangement of "fall in". It is informal/colloquial English.
You can do the same with other verbs indicating prepositions like 'go up' or 'run out':
"He let go of the balloon, and up it went."
"I open the front door, and out runs the cat."
A:
This is more of an old-fashioned way of saying "the wolf fell in the pot". It's less of a "in + past tense of a verb" and more of mixing around where the prepositional phrase is.
Take this:
The wolf fell in the pot.
"In the pot" is the prepositional phrase. If you move it around, you get:
In the pot fell the wolf.
(This form is not common, but it still is grammatically correct.) If you remove a few words (as English-speakers tend to do for convenience), it becomes:
In fell the wolf.
And this is the sentence in that story!
| {
"pile_set_name": "StackExchange"
} |
Q:
Accessing paramters from the request string in YII?
Let's say I have the following view:
http://localhost/site/www/index.php/products/view/1
Then
Yii::app()->request->getUrl() ==> /site/www/index.php/products/view/1
Yii::app()->getController()->id ==> products
Yii::app()->getController()->getAction()->id; ==> view
How do I access the "/1" part?
A:
There are two ways to get the id values.
Let's say you defined the following rule for the Url:
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
Then you can get the value of ID by using GET method in php:
$id = $_GET['id'];
Or u can define in your controller a param for the method, the param will automatically be the id u need:
public function viewAction($id) {
//here $id is equal to $_GET['id']
}
Be careful, the name of these parameters must be exactly the same as the ones we expect from $_GET
http://www.yiiframework.com/doc/guide/1.1/en/topics.url
http://www.yiiframework.com/doc/guide/1.1/en/basics.controller#action
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP PDO query not inserting - Error HY093
After a lot of searching the web, the times I see this error, it looks really scenario specific. So far, I haven't found one that matched my scenario. I think my issue is coming from a prepared statement with spatial data type params.
The way I'm executing my code is:
$sql = $conn->prepare("INSERT INTO states(`name`, `poly`) VALUES(':name',GeomFromText('GEOMETRYCOLLECTION(:coords)'));");
$res = $sql->execute(['name'=>$name, 'coords'=>$coords]);
if($res){
echo "... Successfully Inserted<br><br>";
}
else{
echo "... Failed<br><br>";
print_r($sql->errorInfo());
echo "<br><br>";
}
The above is failing. The connection to the database has been tested. Since these are rather large geometry sets, instead of pasting my code, I'll show how I verified my SQL:
Dumping a raw SQL file and copy/pasting the SQL into a phpMyAdmin window, everything inserted just fine.
$sqlStr = "INSERT INTO states(`name`, `poly`) VALUES('$name',GeomFromText('GEOMETRYCOLLECTION($coords)'));";
$check = file_put_contents('./states/'.$name.'2.sql', $sqlStr);
So it's because of this, that I believe my sql is correct, but it my problem is likely due to the prepare/execute portion somehow. I'm not sure if spatial data types can't be assigned like this?
Edit
I also want to note that I am on PHP version 5.5.9 and I've executed queries in the original method, with the params in the execute just fine.
A:
There's no way the code at the end could be working. Parameters in the query must not be put inside quotes.
Since GEOMETRYCOLLECTION(:coords) has to be in a string, you need to use CONCAT() to create this string.
$sql = $conn->prepare("
INSERT INTO states(`name`, `poly`)
VALUES(:name,GeomFromText(CONCAT('GEOMETRYCOLLECTION(', :coords, ')')));");
| {
"pile_set_name": "StackExchange"
} |
Q:
Join query in gremlin, group results in a one to many relationship
I have to type of vertices Country and Airports, and each country has an edge to multiple airports with label "hasAirport"
I'm trying a join query which will return Countries grouped with the Airports they have.
g.V().hasLabel("Country").as("country").out('hasAirport').as("airport").select("country", "airport").by(__.unfold().valueMap(true).fold()).toList()
The if I have only one Country say United States with two airports in my graph, the result of the query is something like below.
[ {
"country": [
{
"name": "United States",
"code": "USA", "label": "Country",
"id": 1565,
}
],
"airport": [
{
"id": 1234,
"label": "Airport",
"name": "San Francisco International Airport", "code": "SFO"
}
] }, {
"country": [
{
"name": "United States",
"code": "USA", "label": "Country",
"id": 1565,
}
],
"airport": [
{
"id": 2345,
"label": "Airport",
"name": "Austin Bergstrom International Airport", "code": "AUS"
}
] } ]
Is there a way to club multiple airports in a single array like below
[
{
"country": [
{
"name": "United States",
"code": "USA",
"label": "Country",
"id": 1565,
}
],
"airport": [
{
"id": 1234,
"label": "Airport",
"name": "San Francisco International Airport",
"code": "SFO"
},
{
"id": 2345,
"label": "Airport",
"name": "Austin Bergstrom International Airport",
"code": "AUS"
}
]
}
]
A:
You need to use project:
g.V().hasLabel("Country")
.project("country","airport")
.by(valueMap(true))
.by(out('hasAirport').valueMap(true).fold())
| {
"pile_set_name": "StackExchange"
} |
Q:
How to locate a land survey for my house?
A prospective buyer of my house has requested a survey. I thought I could obtain a copy from the county courthouse. My agent told me our courthouse does not keep surveys. Questions: Who is the official keeper of surveys? How does the surveyor know to '150 feet east from the power pole at corner of 'Wild and Crazy'?
A:
The deed is the official description of the land. The deed is generally filed with the county or city, and the surveyor can decipher it. The property taxing authority (county or city) maintains tax maps which should roughly correspond with your survey. If you're in a standard city lot, the tax map is probably very accurate. If you're in the country, a busy road that has been widened, an old suburb or old lot, it is more likely to be inaccurate.
As a seller of a house, be wary of buyers demanding surveys. A survey may reveal issues, such as fences on the wrong side of the line, which must be disclosed and addressed before you'll be able to sell the home. In New York, once you know of an issue, you must disclose that the issue exists. Your state may vary.
I would strongly recommend having the buyer pay for the survey. In my area, they cost about $1,500. This will save you money and potentially give you some deniability -- you don't need to disclose something that you do not know about.
A:
There is no universal "official keeper of surveys" because home surveys are not always mandatory. Some local agencies might conduct surveys on request, so it's useful to research and find out.
I'd suggest you speak with your buyer and explain that your area does not keep surveys. Ask if he has any specific documents in mind or any prior experience in the area, and work out a plan to get a survey done or some alternative arrangement.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot debug script tasks when running under the 64 bit version of the Integration Services runtime
I am trying to debug Script task and it is giving me following error.
"Cannot debug script tasks when running under the 64 bit version of the Integration Services runtime".
A:
I got the solution.
Need to change 'Run64bitRunTime' property to False.
1.Go to project menu in BIDS.
2.Go to properties.
3.In debugging category change the property 'Run64bitRunTime' to False.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to put JLabel behind JTextArea?
I have a JFrame, JLabel and JTextArea. How put layered JLabel and JTexrArea such that JTextArea is just above Jlabel (like layered) in the JFrame?
A:
JLayeredPane has ordering for Layers
| {
"pile_set_name": "StackExchange"
} |
Q:
"Out of bound from the array" error in C#
A beginner question here. I'm trying to run this code. I kinda want to alter the order of another array into this new array. However, I get error System.IndexOutOfRangeException: 'Index out of bound from array'
I don't really know what to do or what did I do wrong.
public partial class Form3 : Form
{
public string[] arrayJugadores = new string[3];
Form2 FormRegistro = new Form2();
public Form3()
{
InitializeComponent();
Random randomizador = new Random();
int valor = randomizador.Next(1, 15);
if (valor == 1)
{
arrayJugadores[0] = FormRegistro.listaJugadores[0];
arrayJugadores[1] = FormRegistro.listaJugadores[1];
arrayJugadores[2] = FormRegistro.listaJugadores[2];
arrayJugadores[3] = FormRegistro.listaJugadores[3];
}
else if (valor == 2)
{
arrayJugadores[0] = FormRegistro.listaJugadores[3];
arrayJugadores[1] = FormRegistro.listaJugadores[0];
arrayJugadores[2] = FormRegistro.listaJugadores[1];
arrayJugadores[3] = FormRegistro.listaJugadores[2];
}
A:
make your array bigger, it can currently only hold 3 elements:
public string[] arrayJugadores = new string[4];
also, check the error message and what line it appears in, then you should be able to figure it out.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does drupal connect to the database
I am really new to drupal and new to php.
I have some questions.
Suppose I have a drupal and a server running on my local machine, how does drupal interact with database? (database is mysql)
it doesn't matter which version of drupal it is, I just want to know how drupal interacts with database.
Thank you!
A:
Drupal uses a database abstraction layer to interact with databases. Currently only MySQL and PostgreSQL is supported as far as I know. You can read more about the available functions in the database abstaction layer here http://api.drupal.org/api/group/database/6.
Wikipedias explanation of database abstraction layer sums it up well:
Traditionally, all database vendors provide their own interface tailored to their products which leaves it to the application programmer to implement code for all database interfaces he would like to support. Database abstraction layers reduce the amount of work by providing a consistent API to the developer and hide the database specifics behind this interface as much as possible.
Source: http://en.wikipedia.org/wiki/Database_abstraction_layer
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails - forms fields for arrays
For my model containing array field arr
(in HAML)
= form_for @model do |f|
- @model.arr.try(:each) do |i|
= text_field_tag 'model[arr][]', i
How can I use f when I'm creating my text fields?
As you can see, I am ignoring f and manually specifying everything.
A:
I don't think you can. For serialized attributes, the approach you are taking is the only one I know of.
| {
"pile_set_name": "StackExchange"
} |
Q:
between_time not working on a pandas panel
The method between_time is defined in a pandas panel object, I would expect this method to be applied to all dataframes in the panel, but this is not working. So what is this method doing?
Example
rng = pd.date_range('1/1/2013',periods=100,freq='D')
data = np.random.randn(100, 4)
cols = ['A','B','C','D']
df1, df2, df3 = pd.DataFrame(data, rng, cols), pd.DataFrame(data, rng, cols), pd.DataFrame(data, rng, cols)
pf = pd.Panel({'df1':df1,'df2':df2,'df3':df3})
pf.between_time('08:00:00', '09:00:00')
The above code returns this error
Traceback (most recent call last): File "", line 1, in
File
"/usr/lib64/python2.7/site-packages/pandas-0.14.0-py2.7-linux-x86_64.egg/pandas/core/generic.py",
line 2796, in between_time
raise TypeError('Index must be DatetimeIndex') TypeError: Index must be DatetimeIndex
A:
You don't actually have any times that would be selected, so I changed your example a bit (you were using D frequency)
In [17]: rng = pd.date_range('1/1/2013',periods=100,freq='H')
In [18]: data = np.random.randn(100, 4)
In [19]: df1, df2, df3 = pd.DataFrame(data, rng, cols), pd.DataFrame(data, rng, cols), pd.DataFrame(data, rng, cols)
In [20]: pf = pd.Panel({'df1':df1,'df2':df2,'df3':df3})
In [21]: pf
Out[21]:
<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 100 (major_axis) x 4 (minor_axis)
Items axis: df1 to df3
Major_axis axis: 2013-01-01 00:00:00 to 2013-01-05 03:00:00
Minor_axis axis: A to D
The axis parameter is not implemented at the moment, so you can do this:
In [22]: indexer = pf.major_axis.indexer_between_time('08:00','09:00')
In [23]: pf.take(indexer,axis='major')
Out[23]:
<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 8 (major_axis) x 4 (minor_axis)
Items axis: df1 to df3
Major_axis axis: 2013-01-01 08:00:00 to 2013-01-04 09:00:00
Minor_axis axis: A to D
| {
"pile_set_name": "StackExchange"
} |
Q:
How to write correct sql with left join on some tables?
Good day.
STRUCTURE TABLES AND ERROR WHEN EXECUTE QUERY ON SQLFIDDLE
I have some sql queries:
First query:
SELECT
n.Type AS Type,
n.UserIdn AS UserIdn,
u.Username AS Username,
n.NewsIdn AS NewsIdn,
n.Header AS Header,
n.Text AS Text,
n.Tags AS Tags,
n.ImageLink AS ImageLink,
n.VideoLink AS VideoLink,
n.DateCreate AS DateCreate
FROM News n
LEFT JOIN Users u ON n.UserIdn = u.UserIdn
SECOND QUERY:
SELECT
IFNULL(SUM(Type = 'up'),0) AS Uplikes,
IFNULL(SUM(Type = 'down'),0) AS Downlikes,
(IFNULL(SUM(Type = 'up'),0) - IFNULL(SUM(Type = 'down'),0)) AS SumLikes
FROM JOIN Likes
WHERE NewsIdn=NewsIdn //only for example- in main sql NewsIdn = value NewsIdn from row table News
ORDER BY UpLikes DESC
AND TREE QUERY
SELECT
count(*) as Favorit
Form Favorites
WHERE NewsIdn=NewsIdn //only for example- in main sql NewsIdn = value NewsIdn from row table News
I would like to combine both queries, display all rows from the table News, as well as the number of Uplikes, DownLikes and number of Favorit for each value NewsIdn from the table of News (i.e. number of Uplikes, DownLikes and number of Favorit for each row of News) and make order by Uplikes Desc.
Tell me please how to make it?
P.S.: in result i would like next values
TYPE USERIDN USERNAME NEWSIDN HEADER TEXT TAGS IMAGELINK VIDEOLINK DATECREATE UPLIKES DOWNLIKES SUMLIKES FAVORIT
image 346412 test 260806 test 1388152519.jpg December, 27 2013 08:55:27+0000 2 0 2 2
image 108546 test2 905554 test2 1231231111111111111111111 123. 123 1388153493.jpg December, 27 2013 09:11:41+0000 1 0 1 0
text 108546 test2 270085 test3 123 .123 December, 27 2013 09:13:30+0000 1 0 1 0
image 108546 test2 764955 test4 1388192300.jpg December. 27 2013 19:58:22+0000 0 1 -1 0
A:
First, your table structures with all the "Idn" of varchar(30). It appears those would actually be ID keys to the other tables and should be integers for better indexing and joining performance.
Second, this type of process, especially web-based is a perfect example of DENORMALIZING the values for likes, dislikes, and favorites by actually having those columns as counters directly on the record (ex: News table). When a person likes, dislikes or makes as a favorite, stamp it right away and be done with it. If a first time through you do a bulk sql-update do so, but also have triggers on the table to automatically handle updating the counts appropriately. This way, you just query the table directly and order by that which you need and you are not required to query all likes +/- records joined to all news and see which is best. Having an index on the news table will be your best bet.
Now, that said, and with your existing table constructs, you can do via pre-aggregate queries and joining them as aliases in the sql FROM clause... something like
SELECT
N.Type,
N.UserIdn,
U.UserName,
N.NewsIdn,
N.Header,
N.Text,
N.Tags,
N.ImageLink,
N.VideoLink,
N.DateCreate,
COALESCE( SumL.UpLikes, 0 ) as Uplikes,
COALESCE( SumL.DownLikes, 0 ) as DownLikes,
COALESCE( SumL.NetLikes, 0 ) as NetLikes,
COALESCE( Fav.FavCount, 0 ) as FavCount
from
News N
JOIN Users U
ON N.UserIdn = U.UserIdn
LEFT JOIN ( select
L.NewsIdn,
SUM( L.Type = 'up' ) as UpLikes,
SUM( L.Type = 'down' ) as DownLikes,
SUM( ( L.Type = 'up' ) - ( L.Type = 'down' )) as NetLikes
from
Likes L
group by
L.NewsIdn ) SumL
ON N.NewsIdn = SumL.NewsIdn
LEFT JOIN ( select
F.NewsIdn,
COUNT(*) as FavCount
from
Favorites F
group by
F.NewsIdn ) Fav
ON N.NewsIdn = Fav.NewsIdn
order by
SumL.UpLikes DESC
Again, I do not understand why you would have an auto-increment numeric ID column for the news table, then ANOTHER value for it as NewsIdn as a varchar. I would just have this and your other tables reference the News.ID column directly... why have two columns representing the same component. And obviously, each table you are doing aggregates (likes, favorites), should have indexes on any such criteria you would join or aggregate on (hence NewsIdn) column, UserIdn, etc.
And final reminder, this type of query is ALWAYS running aggregates against your ENTIRE TABLE of likes, favorites EVERY TIME and suggest going with denormalized columns to hold the counts when someone so selects them. You can always go back to the raw tables if you ever want to show or update for a particular person to change their like/dislike/favorite status.
You'll have to look into reading on triggers as each database has its own syntax for handling.
As for table structures, this is a SIMPLIFIED version of what I would have (removed many other columns from you SQLFiddle sample)
CREATE TABLE IF NOT EXISTS `News` (
id int(11) NOT NULL AUTO_INCREMENT,
UserID integer NOT NULL,
... other fields
`DateCreate` datetime NOT NULL,
PRIMARY KEY ( id ),
KEY ( UserID )
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
extra key on the User ID in case you wanted all news activity created by a specific user.
CREATE TABLE IF NOT EXISTS `Users` (
id int(11) NOT NULL AUTO_INCREMENT,
other fields...
PRIMARY KEY ( id ),
KEY ( LastName, Name )
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
additional key in case you want to do a search by a user's name
CREATE TABLE IF NOT EXISTS `Likes` (
id int(11) NOT NULL AUTO_INCREMENT,
UserId integer NOT NULL,
NewsID integer NOT NULL,
`Type` enum('up','down') NOT NULL,
`IsFavorite` enum('yes','no') NOT NULL,
`DateCreate` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY ( UserID ),
KEY ( NewsID, IsFavorite )
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
additional keys here for joining and/or aggregates. I've also added a flag column for being a favorite too. This could prevent the need of a favorites table since they hold the same basic content of the LIKES. So someone could just LIKE/DISLIKE, against a given news item, but ALSO LIKE/DISLIKE it as a FAVORITE the end-user wants to quickly be able to reference.
Now, how do these table structures get simplified for querying? Each table has its own "id" column, but any OTHER table is uses the tableNameID (UserID, NewsID, LikesID or whatever) and that is the join.
select ...
from
News N
Join Users U
on N.UserID = U.ID
Join Likes L
on N.ID = L.NewsID
Integer columns are easier and more commonly identifiable by others when writing queries... Does this make a little more sense?
| {
"pile_set_name": "StackExchange"
} |
Q:
Fire function on loaded elements with particular class without events
I am using the combination of a data attribute and class name to fire a function to modify the content of the element with the particular class name.
Below function fires at $(document).ready
$('.accessControlled').each(function(){
var accessLevel = parseInt($(this).attr("data-accesslevel"));
if((user.role !== 0) && (accessLevel !== role)){
$(this).remove();
} else {
$(this).removeAttr('data-accesslevel');
$(this).removeClass('accessControlled');
}
});
Now I want to fire this function, on elements returned by ajax calls too.
I know I can bind the functions permanently by jquery on(), live(), delegate(), etc, but which event to use and how to go about it?
A:
There is a function ajaxSuccess in jQuery which can be used to do something after all ajax calls.
$(document).ajaxSuccess(function() {
accessControl.checkAccessControl();
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How to trigger ngClick programmatically
I want to trigger ng-click of an element at runtime like:
_ele.click();
OR
_ele.trigger('click', function());
How can this be done?
A:
The syntax is the following:
function clickOnUpload() {
$timeout(function() {
angular.element('#myselector').triggerHandler('click');
});
};
// Using Angular Extend
angular.extend($scope, {
clickOnUpload: clickOnUpload
});
// OR Using scope directly
$scope.clickOnUpload = clickOnUpload;
More info on Angular Extend way here.
If you are using old versions of angular, you should use trigger instead of triggerHandler.
If you need to apply stop propagation you can use this method as follows:
<a id="myselector" ng-click="clickOnUpload(); $event.stopPropagation();">
Something
</a>
A:
angular.element(domElement).triggerHandler('click');
EDIT:
It appears that you have to break out of the current $apply() cycle. One way to do this is using $timeout():
$timeout(function() {
angular.element(domElement).triggerHandler('click');
}, 0);
See fiddle: http://jsfiddle.net/t34z7/
A:
This following solution works for me :
angular.element(document.querySelector('#myselector')).click();
instead of :
angular.element('#myselector').triggerHandler('click');
| {
"pile_set_name": "StackExchange"
} |
Q:
Create column with group affiliations in R
Lets say I have a dataframe with column "a" and I want to add a column "b" that contains the group affiliation for a specified Interval.
I could use cut and classIntervals and solve this creating a function like this:
library(classInt)
df<-data.frame(a=c(1:120))
function.group.data<-
function(my.data,my.method,my.number){
cut(my.data,
breaks=data.frame(classIntervals(my.data,
method=my.method,
n=my.number)[2])[,1]
,include.lowest=T)
}
df$b<-function.group.data(df$a,"quantiles",10)
But this has some limitations. For example in column b the group names are kind of unpretty written down like this [1,12.9]. For plotting purposes I would rather prefer them to be 01-12.9 ore something like this.
Also I'm pretty convinced that there is some built-in function in R and I won't have to invent something new. Has anybody an idea?
A:
I don't think that you can format the labels of cut function. labels are constructed using "(a,b]" interval notation. But using gsub and some regular expression you can format your cut output. For example:
library(classInt)
x <- 1:120
b <- gsub('\\((.*)[,](.*)\\]','0\\1-\\2',
cut(x,classIntervals(x,10,'quantile',dataPrecision=2)$brks))
b <- as.factor(b) ## because gsub returns a character
droplevels(head(b)) ## to remove extra levels(just for display here)
[1] <NA> 01-12.9 01-12.9 01-12.9 01-12.9 01-12.9
Levels: 01-12.9
| {
"pile_set_name": "StackExchange"
} |
Q:
Hierarchic data with string paths - query for a node, get all parents and first level of their nodes
Say I got tree data:
- A A
- A0 A/A0
- A0.0 A/A0/A0.0
- A0.1 A/A0/A0.1
- A1 A/A1
- A1.0 A/A1/A1.0
- A1.1 A/A1/A1.1
- A2 A/A2
It is stored within a postgresql database "tree-data", with a column 'id' that is the path of the node like above and some helper columns like 'depth' (integer, representing the nodes depth in the tree), 'terminal' (boolean, is a leaf node and has no children).
What I'd like to achieve now is a query for 'A/A0/A0.0', that retrieves all parents and their first level of children.
Getting all parents is easy:
SELECT name, id, depth, terminal
FROM "tree-data"
WHERE 'A/A0/A0.0' LIKE id||'%'
ORDER BY id;
This will return the following nodes:
A
A/A0
A/A0/A0.0
But this is what I need:
A
A/A0
A/A0/A0.0
A/A0/A0.1
A/A1
A/A2
Can you think of an easy and efficient way of achieving this? Optimizing/modifying the schema is possible, though not preferred.
A:
You can get the parent using regexp_replace() and then use the same logic you are using:
SELECT name, id, depth, terminal
FROM "tree-data"
WHERE 'A/A0/A0.0' LIKE regexp_replace(id, '/[^/]+$', '') || '%'
ORDER BY id;
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating subplots, or combining figures while preserving original size
Assume that I have the following data:
simulations = [[27267.130859375, 27331.00668846435, 27597.986059411312, 27180.44375907077, 26829.412595057693, 27167.731093559323, 26556.90612812799, 26122.71038039928, 25543.220341812765, 25123.87968836483, 25277.911731421882, 25102.98106334218, 24805.693913480667], [27267.130859375, 27019.444250572345, 26529.912550263627, 26572.16868488334, 26592.542898027685, 25641.930009410316, 24663.55977841594, 24795.291521692317, 24908.994416967293, 24386.397363350403, 24063.386346808682, 23556.76793353066, 23715.030082008383], [27267.130859375, 28227.310627887142, 28909.446722910572, 28139.076655231747, 27548.374541261393, 28247.729058470348, 27830.124112015194, 27512.560217750248, 27565.08865622723, 27133.82296934645, 26678.617889033052, 26788.722609025077, 26893.136539404575], [27267.130859375, 26531.371663865724, 26717.69320226651, 26505.768003796456, 29335.17433063164, 27778.14503380179, 27187.514114438152, 27607.420455176907, 27943.06022406791, 28044.747407169572, 27341.21235387755, 28073.27564881572, 27695.188210124663], [27267.130859375, 27727.67055018843, 27636.288812957493, 27661.01614302658, 27986.698457965093, 28490.703984635184, 28476.077509161176, 28275.201605127215, 28031.107612767217, 27956.353927193675, 27392.95650829455, 27197.039461536096, 26963.66468936416], [27267.130859375, 27823.771790518123, 27442.706420466006, 26908.08863475161, 26523.819367242453, 25831.690942765847, 25750.957030655143, 25915.99538288321, 25969.517833005037, 25700.671829484592, 25929.46029292608, 26271.353832358396, 26220.673229349428], [27267.130859375, 27097.699256398635, 27202.122987356666, 27218.456973917666, 28241.520601451495, 28176.792213972087, 28183.565469533776, 28133.44471838637, 28737.95089455793, 28425.55883657568, 28580.68259268799, 27899.66932222768, 27795.92756453234], [27267.130859375, 26936.460418733706, 27860.74251952626, 27286.74877948139, 27692.183840993002, 27952.005733604867, 27863.3819082217, 27727.291908557738, 27852.83597365266, 27548.442227873576, 27798.046522269753, 28607.773820364207, 28374.91305279458], [27267.130859375, 27529.795976861045, 27101.50949669024, 27688.208528162228, 29037.36910025952, 28312.46322811291, 28152.236432688533, 27815.780083640635, 27691.330186328087, 27882.36888551168, 28328.48179151336, 27706.655305918193, 27863.41803326141], [27267.130859375, 27603.640385290073, 28096.86934899982, 28150.838898827406, 27669.363588455883, 28178.465803326388, 28577.641141279848, 28984.08621177433, 28998.37286432834, 29208.279312604634, 28254.61387972376, 28067.745036952027, 27441.691545496724], [27267.130859375, 27470.618797735722, 27233.17759710203, 26867.330106077818, 26463.579240126117, 26849.504479794527, 26524.231791075512, 25420.706326827014, 24439.613000109686, 25025.60529139645, 24740.068040547892, 24771.477670353106, 25021.752691350415], [27267.130859375, 26845.252686256492, 27228.63057230569, 27350.49313729412, 27936.045098500155, 27921.0610921457, 27867.450930513376, 28301.37542710208, 28262.928498355384, 28499.284306377886, 28742.15769898319, 28338.31288517325, 28472.695653872426], [27267.130859375, 27623.053107064497, 27814.34724086793, 27078.42902672029, 27668.457223842604, 28779.133677113437, 28258.05104515455, 28983.942493131075, 29122.976831830107, 29301.443061207585, 29597.955216457587, 29605.034822708, 29537.66755029881], [27267.130859375, 26959.455065204973, 26392.59161833839, 26578.82970698153, 26690.086450150462, 27100.112076632173, 27461.23607303833, 28174.645837339795, 27906.993178738125, 28267.609144010974, 28803.273460665652, 28923.142368998524, 29626.501857686653], [27267.130859375, 26759.957739598118, 27459.762163538955, 27762.52369318282, 27598.7309363265, 27254.132021827703, 25188.825938442806, 23793.833632986396, 23692.601648241627, 24428.647852182887, 24536.74628241662, 24975.86554644353, 23465.97278719595], [27267.130859375, 27579.158222534894, 26282.235842377417, 25873.80302012357, 25518.649759212723, 25690.483570018572, 24901.118116018377, 25139.73674890843, 25278.34778289732, 25455.229769210964, 24127.837774723626, 24645.128439482647, 23432.264794004026], [27267.130859375, 27098.000055238277, 26328.26189474818, 27782.21083927415, 27652.620342354265, 27706.047803703692, 27322.098751076872, 27835.53371846676, 28475.72451017814, 28598.66687443377, 29313.597474240767, 28920.54863647653, 28291.457477662447], [27267.130859375, 27235.492568195332, 26842.775481538316, 26689.954341652472, 29631.45593509602, 29322.006019769546, 29602.98202204091, 29805.691112142315, 30515.774884450067, 29925.81737813796, 30090.944021842068, 30373.65501973429, 29295.780929186178], [27267.130859375, 27121.76436254415, 27125.344806254634, 26757.58471130693, 27328.503338438582, 27636.868702796353, 27295.71108336172, 26309.14991663229, 26207.79904462052, 26346.253650894763, 26130.827570444053, 26131.23471077782, 25645.218082100924], [27267.130859375, 27626.076349430663, 27248.84497565231, 27490.28770947993, 28179.718934288405, 28528.742086430033, 28640.235706821008, 28005.502010306634, 28384.96923550602, 28053.662866796374, 28300.841740937092, 28157.33482351919, 28624.6433958065], [27267.130859375, 27094.46914236921, 26526.973768242442, 25841.354473700376, 26763.468460434546, 26901.16806657809, 27323.054362834624, 27179.792211066437, 27483.919444154624, 27819.38801473649, 27954.958744504944, 27768.11470107735, 28041.450624746856], [27267.130859375, 26658.796245017864, 26935.016281646138, 27608.455513068926, 28309.02053484581, 28460.53686715765, 27573.45787537816, 28271.92604739393, 27679.081389726372, 27547.17890044458, 27384.379362356107, 27914.821054915465, 28052.72196482801], [27267.130859375, 27175.711104316742, 26671.94753091903, 26798.422373314042, 26736.560113721793, 27288.784508171695, 27181.21533998257, 27261.234991698395, 27149.1719155268, 26956.04905800726, 26732.485035811285, 26619.14186206929, 26550.20966370784], [27267.130859375, 26808.169038458323, 26990.991303437902, 27062.871660697314, 27642.438741755, 26729.684224089367, 26302.412024191355, 26347.300084486975, 26642.422556183905, 26331.17333249717, 26097.450304503032, 26165.575471978183, 25797.13120233132], [27267.130859375, 27604.65211170589, 27822.59045919056, 28559.852571524832, 28929.359264451297, 28176.464111674304, 28094.535782256728, 27843.243273457385, 27710.319742438514, 27623.03881787898, 28395.931724234928, 28343.596623636895, 28630.888844920653], [27267.130859375, 26676.13452489905, 27204.622988549396, 27438.08812197452, 27644.34866616331, 27158.390550338845, 26950.675691287088, 26931.528511598914, 27354.22146883033, 27159.809925292757, 27061.16789576243, 26542.548448204478, 26270.598522407185], [27267.130859375, 27730.861841770806, 28753.836167390164, 28728.32422639492, 29758.01404312672, 29755.66634194187, 29601.021322921068, 29518.31721105122, 29715.934589612487, 28661.4465520372, 28518.38143436911, 28809.07333790931, 28041.947781362887], [27267.130859375, 26637.88761899429, 26020.61282795997, 26024.168248269663, 26086.29116445673, 27085.856919794256, 27534.980213997354, 26865.791461769677, 27318.70232033068, 26725.871012773838, 26712.25960585438, 26791.67403516035, 26582.7504609222], [27267.130859375, 27578.646606494487, 28288.02989736072, 29159.64320923237, 29109.506421205515, 28805.37613175051, 28517.34699745127, 28828.366312676568, 28907.002481140695, 28928.72155334556, 28499.54765945309, 28187.93934452906, 28148.690540197844], [27267.130859375, 27697.963928038866, 27501.45022328322, 28546.61379105984, 28456.002144629678, 29122.739492600213, 30276.20287580055, 30179.95445745492, 29397.448859840468, 29783.95467369244, 29667.285568104955, 30246.063219446285, 29918.485798703914], [27267.130859375, 27106.266000610656, 27501.445560612563, 27945.22764302737, 28267.20856903439, 27757.898273422747, 27601.63581488045, 27722.064142272207, 28044.64223763983, 28156.246752553638, 27947.299073796, 28098.752955060096, 28196.085238004605], [27267.130859375, 26610.14474268555, 26512.914191321335, 26082.45610077008, 26546.503903195866, 26114.264305829503, 26699.62496915473, 26327.081004229636, 26493.569004986584, 26413.056718272164, 26235.194271809047, 25656.49857182994, 25600.83623454324], [27267.130859375, 26829.00666379737, 26205.39957094446, 25971.85099449023, 25581.347909976004, 25566.10913497572, 24613.842296865416, 23261.51179791043, 23004.786399257722, 23108.447415166327, 24074.889824303253, 22801.083359988806, 23288.572856757044], [27267.130859375, 26493.954985998167, 25821.975897740398, 26138.058133030107, 25907.35031034589, 26327.067947848092, 25542.525449897195, 25355.275750585923, 25691.165127359473, 25684.528547797512, 25808.162755884518, 25905.556305511567, 26199.305203484157], [27267.130859375, 26806.851994838133, 27312.521627173737, 27234.042572522423, 28123.392394927363, 27093.113469498887, 26944.807596794344, 27542.263785413183, 26863.80173982801, 25879.536653771847, 25793.743445054723, 24791.965125749255, 24584.163228780406], [27267.130859375, 27209.602932848946, 26911.31986682307, 27111.982394004175, 27884.825938562077, 27946.03500190762, 27706.56380468143, 27701.858312753164, 27966.080876591437, 27323.02131037039, 27195.717223540345, 27674.55450844261, 27336.793855297412], [27267.130859375, 26894.356381566802, 28007.71685137701, 28501.85757036378, 29294.875268150696, 29771.08501165212, 29735.19665728221, 29304.264126519534, 29182.726929522545, 29246.21306597027, 29346.688979850816, 29188.665604862108, 29194.672001932802], [27267.130859375, 27240.7626878171, 27243.346103436947, 27239.567215171042, 26639.415375633947, 26590.454402128453, 27387.24371341738, 27597.545374250916, 27701.927146518083, 26993.717363033495, 27788.086698117626, 28379.19577599935, 27105.028970740113], [27267.130859375, 27348.99979962428, 27260.430874397873, 27766.94944001234, 27970.228296316396, 27013.368164678348, 27418.680898956787, 26925.38713247403, 27079.055061462306, 27167.546776883406, 26652.34401148123, 27053.61991432097, 27280.510380599124], [27267.130859375, 27242.836469953127, 27383.55653925608, 27238.777169111534, 28457.436460879202, 28245.62901129633, 28318.78914570046, 28346.335686810216, 28776.642015005837, 28928.099360553995, 28979.683614419882, 29098.517109226566, 28592.420624392278], [27267.130859375, 27482.28517197817, 26757.646273575552, 26771.71596816057, 26694.85950864844, 27365.599948640778, 26708.541662241678, 26489.726528940035, 26462.27301075272, 26471.419323785572, 26918.274090736882, 26432.02871389733, 26946.82425156129], [27267.130859375, 27510.32463412335, 28171.334776819815, 27774.572233185176, 28069.016906813053, 28483.139319314323, 29624.888451327748, 29973.249467630954, 29650.303854339236, 29317.930900253054, 29238.160339373047, 29429.68421740552, 29860.03600643044], [27267.130859375, 27907.108551749083, 27685.965959262234, 26806.161412612786, 26429.610039303006, 26790.781447092562, 26980.20507067256, 27085.989303517163, 26989.457224450816, 26536.357921662137, 26827.288478252118, 26327.791174304377, 26392.67134467677], [27267.130859375, 26750.768994778882, 25812.845601762176, 26054.90259621658, 26491.79983946998, 26642.01742866121, 25353.156590365106, 25692.427683373862, 25883.432137509237, 25117.958021125145, 24822.13963103479, 25436.4191087569, 26415.727231922767], [27267.130859375, 27025.953302725848, 26543.38178467313, 26183.131116259443, 26640.924366548516, 26176.45053458882, 25529.018626177723, 26177.17745227953, 25858.80623200601, 25801.705195238184, 25820.14888655071, 25744.14624451306, 25658.019752630265], [27267.130859375, 27613.910601976087, 27455.807524868782, 27239.820334647764, 27756.386442198607, 28049.68635382816, 28358.886096498365, 28290.336010450126, 28094.513179257425, 27703.24400498415, 27930.165860828645, 27611.301621463215, 27478.44430653395], [27267.130859375, 27298.761154516564, 27451.42571393972, 27788.754068144037, 26792.788127310723, 26743.69304771336, 27249.501950306854, 27191.181234865882, 26597.505881550067, 26523.33434130528, 26316.775539093607, 26167.125404325423, 26820.491588943845], [27267.130859375, 27562.553600154344, 26747.795858563226, 27056.523222407985, 26441.80260778559, 26523.627108322074, 26134.32073216405, 26307.477388176136, 26578.55391492888, 26838.55560100043, 27080.200672509905, 26454.395421345307, 26868.601775339783], [27267.130859375, 27036.12419022366, 27760.3320060603, 28685.511491719706, 28714.62003275436, 28488.714347188994, 28655.90102631908, 29052.99930099197, 29355.62877433884, 29170.472738906017, 30093.946736747526, 30493.875526804117, 30608.610795950826], [27267.130859375, 27628.500425682174, 28424.45641226704, 28790.97658171265, 29124.20247511447, 28435.21861816533, 28274.308918322036, 28267.913244106963, 28248.751307482653, 27508.984003818903, 27728.510434914708, 27591.71203430522, 27279.558190497144], [27267.130859375, 27119.885221890203, 27740.903587812696, 27885.682518238158, 26898.406259406343, 26737.20763374855, 27186.821180642215, 27743.742919476583, 27856.52192694423, 28560.645984742572, 28208.755709658148, 27813.31394603796, 28078.97262513587], [27267.130859375, 26728.329147828055, 26579.529092753022, 26252.393373893425, 26589.895259982943, 26884.995553348283, 27154.313412556305, 23652.7308789096, 24017.78604617143, 23717.175467502548, 23488.4917555555, 23256.276364345533, 23523.63179343334], [27267.130859375, 27169.4702010872, 27667.46104392589, 27747.203735234467, 27536.66311094841, 27956.70004479116, 27348.9070825626, 27592.88513101849, 27729.160002219283, 26542.26909405498, 26311.97973769372, 26354.54464814421, 26396.442706576752], [27267.130859375, 27255.392465851273, 26961.499126590894, 27054.054689419772, 27024.923597471534, 27360.45585637953, 26601.707706075398, 26821.393180089523, 27096.528494091228, 27010.6556770991, 26736.501531337744, 27177.41096301727, 27582.87261566596], [27267.130859375, 26658.445292957884, 26294.429126491712, 25088.00878043079, 25285.14422077942, 26620.760208843258, 26214.766739313254, 29059.128009872355, 29147.333664553724, 29071.729641253027, 29292.58175571688, 29482.962462213924, 29113.113724530744], [27267.130859375, 26879.539536900433, 26641.316202930393, 27385.7698874532, 27256.023570261557, 27714.523895020655, 27888.7257030455, 27881.254382109368, 27774.572980635017, 27531.843667507874, 27526.54192222514, 26878.345456415453, 26372.079593902967], [27267.130859375, 25811.133143111856, 26366.1788909208, 25688.216394210565, 25819.198676455002, 25079.325154487768, 24633.425621593473, 24834.259775877195, 25318.080401270607, 25713.873783592677, 25710.47232937887, 26084.819771758197, 26097.987795534023], [27267.130859375, 27420.06443628467, 27613.473923272584, 27793.90659284514, 27784.90216659009, 27149.09036862305, 26682.033810319135, 26561.558237099238, 26398.456558253114, 26176.6958750104, 26360.89783003479, 26574.72420643468, 26882.96923221906], [27267.130859375, 27333.645884983416, 27257.290982460323, 26826.84157610477, 26531.98642052505, 26358.967666694538, 27238.636725854372, 26973.963023818793, 27123.653308911147, 26122.044298655146, 25839.01110808385, 25740.414194408946, 25690.525837640733], [27267.130859375, 27685.596564995503, 27832.108255994543, 27998.13041598311, 27286.81172683546, 26472.62273185593, 26976.19136026744, 27928.25518728615, 27688.942460626946, 27673.172278729275, 27501.13587892087, 27971.314766945714, 29454.27561996876], [27267.130859375, 26467.790957873294, 26759.704184242364, 26106.90966101784, 25494.960866522553, 26240.41896832833, 27035.281568401504, 26974.975040321253, 27207.750718536423, 26680.883867946555, 26145.810875907006, 25804.830604687904, 26668.10351735926], [27267.130859375, 26980.57894844171, 27430.74830673905, 27335.06148813566, 27793.53929726743, 28283.24095557976, 28366.480610894738, 28031.44252222841, 27695.25858830163, 27708.031234225797, 27718.48865097257, 27094.4115012879, 26764.10705487519], [27267.130859375, 27649.195779776634, 26761.77599607052, 26114.367783543625, 25255.244428378002, 23576.0135338315, 23796.2700415901, 24856.069892020936, 25211.85382517624, 24894.41771168161, 24513.358534227627, 23995.692191357226, 23407.31012124949], [27267.130859375, 27905.250860454275, 28698.16892060309, 29458.848460975267, 28817.37933947186, 29259.762648296037, 29355.67344349033, 29833.08543360172, 29302.811297654083, 29553.92890442998, 30197.317299407732, 30626.551036856177, 30981.60576521389], [27267.130859375, 27944.25913534051, 28417.772938629223, 28976.086649365785, 27945.88817032404, 28232.25977297378, 29006.21660140772, 29242.827840480233, 29368.693242879846, 29582.123565858932, 29030.24249775212, 28843.813955819885, 29156.878411205278], [27267.130859375, 27703.49725693987, 27588.815684361914, 27249.57140603712, 26213.251431324647, 25996.693441682626, 25717.94640455972, 25985.50059556703, 25696.04189598756, 26099.58195015764, 25696.830282812483, 25992.008159676905, 25332.084327833152], [27267.130859375, 27424.509334129416, 27662.769643835294, 27852.595892347566, 27556.187767713283, 28852.756604020684, 28693.13534768218, 30077.87344698899, 30102.913063804397, 29851.052878857972, 30388.788496682668, 30962.183870605775, 30927.99294353436], [27267.130859375, 27206.714027372604, 27482.206330824043, 28236.046702627336, 28676.160279720072, 28728.870450558083, 28564.60966072108, 28249.82496847269, 28447.531450991093, 28705.42602789705, 28610.6976952552, 29028.03913695067, 28614.65873868892], [27267.130859375, 27495.475737870605, 27024.059781855714, 26524.500621450825, 27561.855925499283, 27385.66176280175, 27145.32993337999, 26165.90994940876, 26082.46874763505, 26038.30104179005, 25685.99472295401, 25276.992317458265, 25169.306679114958], [27267.130859375, 26888.55256152824, 26245.315380544427, 26631.295573669446, 29176.627868860603, 28123.24651188167, 27664.708065834006, 28171.33148274359, 27949.632537637866, 27865.311232666532, 28350.269681911606, 28432.995132309818, 28617.272371765135], [27267.130859375, 27630.27755738252, 27387.703315352, 28030.06795718627, 28166.420903607595, 27938.12090286012, 25487.34579134496, 26330.63960592992, 26164.63817390121, 25954.699241389037, 26323.912963596882, 26327.167309699587, 27502.969751854343], [27267.130859375, 26972.824635535657, 27905.42113774447, 26679.38589687777, 25901.128089647824, 25742.877323332967, 25888.851517311698, 25338.526930333646, 25356.77585766288, 25769.818889543116, 26012.524241961975, 26032.341966097712, 26758.60792457135], [27267.130859375, 27356.706458077388, 27290.78809829675, 31413.86098395701, 31866.904254271452, 32401.397552040344, 33370.55821863325, 33239.10887331018, 32269.49835680139, 31998.54635358946, 32628.093922768716, 32808.1477891488, 32889.8914680764], [27267.130859375, 27347.85313316035, 26011.439144563232, 26606.385032861406, 26438.922966528036, 26024.598782727284, 25608.887155042637, 26026.82198339158, 27113.737343410463, 27526.395458967858, 27527.611808152047, 27468.56168559715, 27655.35772197229], [27267.130859375, 27754.81065538187, 27109.868473118182, 27570.704769386284, 27857.750740199932, 28042.915754628873, 28265.95881381363, 28113.432801474723, 27601.378038205574, 27733.16953866419, 26921.119426180696, 26405.190251338805, 25822.34580036021], [27267.130859375, 26794.462643335803, 26802.105367026943, 27694.849230488206, 27307.396920625677, 27691.91269911242, 27172.62702683534, 27764.657358337874, 27844.708962630266, 27898.471224444063, 28086.957103822104, 27999.76132088686, 28396.670165462645], [27267.130859375, 26843.25856584464, 27280.5558707262, 27033.348790153836, 25568.82874939584, 25295.5955298737, 26007.371833879653, 25615.913145426017, 26020.1163528638, 25863.99575373376, 26047.599778471864, 26097.883668800026, 25701.513682798555], [27267.130859375, 27529.59119762463, 27039.992490367204, 27045.982162464825, 26943.611565902676, 25755.760675041376, 24663.56373974443, 25400.92798136101, 25657.415995837386, 25761.131813199747, 25614.027852459847, 25426.448990935034, 25828.45859549601], [27267.130859375, 27299.162619111637, 27209.581369828065, 27612.926578368475, 27779.12381252064, 27710.390266240505, 27048.08418128729, 26443.848669583913, 25995.06955055197, 26202.422722064453, 26451.506574866933, 25880.597388144026, 25312.2977181678], [27267.130859375, 27015.761730446888, 27464.628812977462, 27435.52171563358, 25980.196169676066, 25326.461772394596, 25357.849880851874, 25595.806589359236, 25822.552059560283, 25693.97402959115, 25993.550704786456, 25745.68691992582, 25876.35438065936], [27267.130859375, 27303.520965565403, 27912.40696288302, 27838.238735322288, 27440.48935425627, 27040.099558558977, 27442.947748585004, 27692.46502799187, 27671.02458926324, 27911.275877414733, 28146.110760409272, 28101.78584990382, 28503.465272802037], [27267.130859375, 26692.554458529605, 26751.405274299443, 28361.0410817989, 27977.809551222104, 28254.61590472317, 27418.613864799354, 27632.860070532024, 27853.47028615071, 27758.608879744577, 27841.77645250451, 27091.316408014736, 26293.988053367513], [27267.130859375, 26802.413403759016, 26161.97870952382, 26594.833674814003, 26369.77650426362, 25991.800962708596, 26887.13225514166, 27071.896589059095, 26440.95198202709, 26121.07603677044, 25594.134782550154, 25192.579244088905, 24526.97896876045], [27267.130859375, 27215.51040861127, 26503.9053555306, 26513.12521484297, 26524.06431082713, 27995.620657795404, 27670.088724204194, 27496.402954978537, 27718.529112466214, 27514.83027545648, 27485.495944166574, 27605.62133800692, 27813.828321517936], [27267.130859375, 27607.60388141927, 27888.517266195417, 27980.83520332806, 27222.428469108152, 25270.945378258522, 24352.592116204705, 25326.691102251287, 24759.3224928151, 24647.893229616388, 23431.397028694286, 23142.07996688148, 23054.23736025652], [27267.130859375, 27021.62957126276, 27114.40120114697, 27542.66846591281, 26981.562348795094, 27389.02325670764, 28419.5644043659, 29176.228934092505, 28921.460402292993, 29214.785944951567, 29135.877219970007, 29502.0127158178, 29983.294162601105], [27267.130859375, 26609.338742554537, 26971.184329022228, 27323.2017719181, 27956.672278889142, 26418.41215923013, 27392.09966512955, 26590.335690548553, 26703.06435356478, 26205.815560837145, 26742.93828479486, 26253.18057091659, 26369.36031006145], [27267.130859375, 27114.557243057487, 27542.734558988246, 28483.65686444672, 30165.1493080319, 30176.420935290065, 30374.01507576039, 29823.189750766087, 29990.61560598156, 30080.345355921872, 29742.250623668522, 30079.599691799165, 30155.431519729176], [27267.130859375, 26773.496731386265, 26240.594785733352, 26131.984431902885, 26014.354503198578, 26034.628399896075, 26450.673283072323, 26690.841572814585, 26924.867656143753, 26311.220955395893, 26827.25332385212, 26636.20870470606, 27033.227806770585], [27267.130859375, 27403.408207445864, 26898.756390965296, 26110.55218393077, 26172.165900541404, 27276.88028729244, 27332.626424353904, 27633.989245214918, 27261.969695131265, 27328.060121780523, 27730.841250141842, 28310.76795044502, 29270.948304505397], [27267.130859375, 26702.111223638156, 26558.668257947345, 25621.750057203815, 26128.66246281449, 25264.566902920353, 25839.85714587361, 25448.211741827014, 25509.06649270538, 25855.410568401203, 25717.67668658228, 25502.176087730477, 24929.102488514578], [27267.130859375, 27394.442961863628, 27403.29083847237, 25084.744560614294, 25224.054307554223, 25297.32361353963, 25936.31564179057, 25330.12169066776, 25667.871783443887, 25749.223758355747, 25499.06847836444, 25330.35765061298, 24953.3462032552], [27267.130859375, 27302.493409014758, 27220.731621806324, 26882.518792981587, 27967.043012437247, 28157.159748828893, 27291.285670759396, 27519.583482393384, 27477.342503425614, 28112.14855669922, 28314.420226343835, 28414.46240544191, 28157.255654370856], [27267.130859375, 27143.913587799583, 26983.710461954634, 26676.510468394546, 26699.991366267404, 26520.431739429634, 26741.37628011218, 27247.184605004193, 27175.89464779085, 27078.01856543501, 26979.07863521237, 26991.117663215246, 26698.072877565017], [27267.130859375, 27348.025412142386, 28250.332340419434, 27448.983192389373, 27067.411569982938, 26697.580105054098, 26216.43172535981, 27111.627841613496, 27353.141188528283, 28330.70656057089, 27600.014876385405, 28128.698406674714, 27763.81721399013], [27267.130859375, 27306.36466354744, 27260.446405466246, 25966.781476057233, 25030.136296382418, 24982.84117093597, 25230.819686262646, 27877.768606184636, 28035.876827995417, 28718.488536105237, 28556.4951713118, 28109.85933512346, 27985.558306397128], [27267.130859375, 27069.138991859174, 26796.45951185346, 25827.68214729034, 26095.977765684212, 25494.72768255823, 26105.75747623527, 25756.68959899161, 25297.57960296439, 25093.200164965943, 24440.094046389422, 24424.40825750931, 23373.6022781863], [27267.130859375, 26297.918702493225, 26608.499166290472, 25814.380757572417, 26201.916820465078, 26264.94858808162, 26559.26028897028, 27248.362940687784, 26764.090817048895, 27314.94471983351, 27495.330154439995, 27059.282120130578, 26581.933125065134], [27267.130859375, 27346.655638252727, 25989.727231476, 26292.788825695294, 25871.359908611208, 24683.617422481417, 24245.651922539702, 23423.737273051862, 23415.814878811423, 23396.52910169303, 23310.93603673958, 23926.627822650986, 24092.684895035894], [27267.130859375, 27348.15804948213, 27181.00302257683, 27041.426213245344, 26864.60411648043, 26317.76380441854, 26265.59160970587, 24645.57375371041, 24319.13312449091, 24391.777548370857, 24182.303398932923, 23896.897412400096, 24450.233812505525]]
And I plot this into subplots for each day by using this code:
for each_day in range(1, len(simulations[0])):
temp = []
for each_simulation in simulations:
temp.append(each_simulation[each_day])
plt.title('Day ' + str(each_day))
plt.subplot(np.ceil(len(simulations[0]) - 1 / 2),2,each_day)
plt.hist(temp, label='Day ' + str(each_day))
in which I intend to create a subplot with two columns that features all the figures that I want to plot. However, I end up with this:
I would like to preserve the size of each figure, instead of compressing them all into one plot. Unlike the graph I got. Is there a way in which I can just plot them all with their original size preserved (by original size I mean the size they would have if I had plotted them individually)
Many thanks
A:
You can create the figure and set its size according to the number of subplots:
fig,ax = plt.subplots(np.ceil((len(simulations[0]) - 1) / 2).astype(int),2,figsize=(4*2,4*np.ceil((len(simulations[0]) - 1) / 2))) #create figure and specify the size of it. figsize(width,height)
ax=ax.flatten() #flatten the axes to make them iterable
for each_day in range(1, len(simulations[0])):
temp = []
for each_simulation in simulations:
temp.append(each_simulation[each_day])
ax[each_day-1].hist(temp, label='Day ' + str(each_day)) #plot to the specific subplot
ax[each_day-1].title.set_text('Day ' + str(each_day)) #add title
| {
"pile_set_name": "StackExchange"
} |
Q:
Combining Select Statements
I have three select statements that provide the number of Members that attend particular events - Healthcare, Religious and Sport - in addition to the average "score" for each event and a count for each.
The count will differ for each event.
Individually each query works, but I want to combine them into one query.
How do I do that?
(select sum(case when Healthcare ='1' then 1 else 0 end) as [Healthcare_never],
sum(case when Healthcare ='2' then 1 else 0 end) as [Healthcare_not often],
sum(case when Healthcare ='3' then 1 else 0 end) as [Healthcare_average],
sum(case when Healthcare ='4' then 1 else 0 end) as [Healthcare_often],
sum(case when Healthcare ='5' then 1 else 0 end) as [Healthcare_very often]
,avg(Cast(Healthcare as float)) as Average
,count(Healthcare) as N_Healthcare
from Member
where Healthcare > '0' )
(select
sum(case when Religious ='1' then 1 else 0 end) as [Religious_never],
sum(case when Religious ='2' then 1 else 0 end) as [Religious_not often],
sum(case when Religious ='3' then 1 else 0 end) as [Religious_average],
sum(case when Religious ='4' then 1 else 0 end) as [Religious_often],
sum(case when Religious ='5' then 1 else 0 end) as [Religious_very often],
Avg(cast(Religious as float)) as Average
,count(Religious) as N_Religious
from Member
where Religious > '0' )
(select
sum(case when Sport ='1' then 1 else 0 end) as [Sport_never],
sum(case when Sport ='2' then 1 else 0 end) as [Sport_not often],
sum(case when Sport ='3' then 1 else 0 end) as [Sport_average],
sum(case when Sport ='4' then 1 else 0 end) as [Sport_often],
sum(case when Sport ='5' then 1 else 0 end) as [Sport_very often],
Avg(cast(Sport as float)) as Average
,count(Sport) as N_Sport
from Member
where Sport > '0' )
A:
try this
select
sum(case when Healthcare ='1' then 1 else 0 end) as [Healthcare_never],
sum(case when Healthcare ='2' then 1 else 0 end) as [Healthcare_not often],
sum(case when Healthcare ='3' then 1 else 0 end) as [Healthcare_average],
sum(case when Healthcare ='4' then 1 else 0 end) as [Healthcare_often],
sum(case when Healthcare ='5' then 1 else 0 end) as [Healthcare_very often],
avg(Cast((case when Healthcare > 0 Then Healthcare Else Null end) as float)) as Healthcare_Average,
count(case when Healthcare > 0 Then Healthcare Else Null end) as N_Healthcare,
sum(case when Religious ='1' then 1 else 0 end) as [Religious_never],
sum(case when Religious ='2' then 1 else 0 end) as [Religious_not often],
sum(case when Religious ='3' then 1 else 0 end) as [Religious_average],
sum(case when Religious ='4' then 1 else 0 end) as [Religious_often],
sum(case when Religious ='5' then 1 else 0 end) as [Religious_very often],
Avg(cast((case when Religious > 0 Then Religious Else Null end) as float)) as Religious_Average,
count(case when Religious > 0 Then Religious Else Null end) as N_Religious,
sum(case when Sport ='1' then 1 else 0 end) as [Sport_never],
sum(case when Sport ='2' then 1 else 0 end) as [Sport_not often],
sum(case when Sport ='3' then 1 else 0 end) as [Sport_average],
sum(case when Sport ='4' then 1 else 0 end) as [Sport_often],
sum(case when Sport ='5' then 1 else 0 end) as [Sport_very often],
Avg(cast((case when Sport > 0 Then Sport Else Null end) as float)) as Sport_Average,
count(case when Sport > 0 Then Sport Else Null end) as N_Sport
from Member
| {
"pile_set_name": "StackExchange"
} |
Q:
kSOAP2 and SOAPAction on Android
I am trying to access a Webservice with kSOAP2 on an Android Phone. I think the connection is being established, but the server won't answer my request since I'm not providing a SOAP Action Header which seems to be required in SOAP Version 1.1(please correct me if I'm wrong here) which I have to use since the server does not support Version 1.2 .
The concrete Faultcode which is returning in the request looks like this:
faultactor null
faultcode "S:Server" (id=830064966432)
faultstring "String index out of range: -11" (id=830064966736)
The errorcode which is generated on the server (I'm running it on a localhost) looks like this:
4.05.2010 20:20:29 com.sun.xml.internal.ws.transport.http.HttpAdapter fixQuotesAroundSoapAction
WARNUNG: Received WS-I BP non-conformant Unquoted SoapAction HTTP header: http://server.contextlayer.bscwi.de/createContext
24.05.2010 20:20:29 com.sun.xml.internal.ws.server.sei.EndpointMethodHandler invoke
SCHWERWIEGEND: String index out of range: -11
java.lang.StringIndexOutOfBoundsException: String index out of range: -11
at java.lang.String.substring(Unknown Source)
at de.bscwi.contextlayer.xml.XmlValidator.isValid(XmlValidator.java:41)
at de.bscwi.contextlayer.server.ContextWS.createContext(ContextWS.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.xml.internal.ws.api.server.InstanceResolver$1.invoke(Unknown Source)
at com.sun.xml.internal.ws.server.InvokerTube$2.invoke(Unknown Source)
at com.sun.xml.internal.ws.server.sei.EndpointMethodHandler.invoke(Unknown Source)
at com.sun.xml.internal.ws.server.sei.SEIInvokerTube.processRequest(Unknown Source)
at com.sun.xml.internal.ws.api.pipe.Fiber.__doRun(Unknown Source)
at com.sun.xml.internal.ws.api.pipe.Fiber._doRun(Unknown Source)
at com.sun.xml.internal.ws.api.pipe.Fiber.doRun(Unknown Source)
at com.sun.xml.internal.ws.api.pipe.Fiber.runSync(Unknown Source)
at com.sun.xml.internal.ws.server.WSEndpointImpl$2.process(Unknown Source)
at com.sun.xml.internal.ws.transport.http.HttpAdapter$HttpToolkit.handle(Unknown Source)
at com.sun.xml.internal.ws.transport.http.HttpAdapter.handle(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handleExchange(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handle(Unknown Source)
at com.sun.net.httpserver.Filter$Chain.doFilter(Unknown Source)
at sun.net.httpserver.AuthFilter.doFilter(Unknown Source)
at com.sun.net.httpserver.Filter$Chain.doFilter(Unknown Source)
at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(Unknown Source)
at com.sun.net.httpserver.Filter$Chain.doFilter(Unknown Source)
at sun.net.httpserver.ServerImpl$Exchange.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The relevant part of the WSDL (at least that's what I'm thinking) looks like this:
<operation name="createContext">
<soap:operation soapAction=""/>
−
<input>
<soap:body use="literal" namespace="http://server.contextlayer.bscwi.de/"/>
</input>
−
<output>
<soap:body use="literal" namespace="http://server.contextlayer.bscwi.de/"/>
</output>
</operation>
In my code I'm adding a Header, but it seems like I'm doing it wrong:
private static final String SOAP_ACTION = "";
//...
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope (SoapEnvelope.VER11);
soapEnvelope.setOutputSoapObject(Request);
AndroidHttpTransport aht = new AndroidHttpTransport (URL);
//...
aht.call(SOAP_ACTION, soapEnvelope);
SoapPrimitive resultString = (SoapPrimitive) soapEnvelope.getResponse();
Any advice would be great since I'm running out of ideas..
Thanks folks!
A:
The SOAP Action consists of the namespace and the actual method you want to call.
Furthermore, the SOAP Action needs to be encapsulated in " " to work. I had a similar error, until I used a helper method to generate my SOAP Action:
public String getSoapAction(String method) {
return "\"" + NAMESPACE + method + "\"";
}
I hope it helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
.NET Web API custom return value
I am having some issues with Web API, and standard documentation didn't help me much..
I have a ProductsController, with a default method GetAllProducts(), which accepts several GET parameters (it was easier to implement that way) for querying.
Now, in another part of the application, I use a jQuery autocomplete plugin, which has to query my webservice and filter the data. Problem is, it expects results in a custom format, which is different than that returned by Web API. I procedeed creating another method, GetProductsByQuery(string query), which should return the data in that format.
Is there any way I can enforce WebAPI to return the data as I want it, without making another Controller?
I am also having problems with the routing table, because all the GETs go straight to the first method, even if I routed the second one to url: "{controller}/query/{query}"
Here is some code:
public class ProductsController : ApiController
{
public IEnumerable<Product> GetAllProducts()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
// Querying EF with the parameters in the query string
return returnQuery;
}
[System.Web.Mvc.HttpGet]
public dynamic GetProductsByQuery(string query)
{
return SomeCustomObject;
}
And the routing:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Query",
url: "{controller}/query/{query}");
A:
You need to swap your routes around - any request that matches your second route will match your first route first.
Secondly, look into custom media formatters if you need specific return formats for your data:
http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters
| {
"pile_set_name": "StackExchange"
} |
Q:
Determine Oracle session client character set?
I know how the database characterset (NLS_CHARACTERSET in select * from v$nls_parameters;) and the client character set (the client environment setting NLS_LANG) interact.
What I can't find out however, is how or if I can determine, for an established session, what Oracle thinks the current client characterset is.
Is this possible at all?
Note: SELECT * FROM NLS_SESSION_PARAMETERS; does not include the character set (on 10g2).
To make absolutely clear what I'd like to accomplish:
NLS_LANG is set in client environment to an arbitrary value (for example GERMAN_GERMANY.WE8MSWIN1252)
Database application[*] starts and establishes a connection/session to the Oracle database.
Database application[*] wants to "ask" Oracle (not its OS environment) what the client character set is Oracle will assume.
[*]: If the db application is sqlplus, the example would look as follows:
...
sqlplus /nolog
connect user/pass@example
*magic command*;
CLIENT CHARACTERSET = ...
Jack's note in his answer raises two important points:
With Oracle, who does the characterset translation. Is it the client-library code or is it done on the server side?
As it appears it is the client, the client would need expose this setting -- what the client lib/tool assumes this setting is. Is there any of the Oracle client libs/tools (sqlplus, OCI/OCCI, Pro*C, ...) that can be queried for what it thinks this setting is?
A:
I am a little doubtful that this is exactly what you are looking for, but
host echo %nls_lang%;
ENGLISH_UNITED KINGDOM.WE8ISO8859P1
shows the client nls_lang environment variable on the client.
I don't think there will be a SQL query you can run to give the 'current' setting because AFAIK the server is not aware of what translation is done client-side, so any command to show the current setting will have to be native to the client - I used SQL Developer for the above command, but I assume it will work the same in SQL*Plus
--edit
from AskTom:
only the client knows their character set as well -- it is not available "in the
database"
and
the character set describes what is stored in database.
the client makes their desired translated to character know [sic] to the database via the NLS_LANG
settting.
If you were on 11.1+, you might have some joy with v$session_connect_info, because:
This information is pushed by OCI to the server ats login time.
But I discovered it would still depend on how you are connecting, eg from the JDBC Thin Driver you aren't using OCI and so the information isn't pushed
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting the Tasks in a Google App Engine TaskQueue
I know you can view the currently queued and running tasks in the Dashboard or development server console. However, is there any way to get that list programmatically? The docs only describe how to add tasks to the queue, but not how to list and/or cancel them.
In python please.
A:
It sure doesn't look that way. Instead of removing the task, how about altering the task handler, whatever it is that handles the task url invokes, to check to see if the work specified still needs to be done, and just return 200 OK immediately if the task would be deleted.
This issue on google-code appears to request the very same feature.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python; popen do not pass std*
I have a chain of three processes: Process A calls B to spawn C, then B dies. We can call B a "bridge" between two systems A and C.
I want to make sure that C DOES NOT inherit any file descriptors that A opens in order to prevent zombying, which I am currently observing (sometimes A calls B to kill C, and after this, I am seeing defunct C processes hanging around, but I don't know what the code in A looks like).
To make sure this issue isn't due to stdin/out/err being passed down,
I am currently doing the following in B
def _close_fds(): #workaround carstens bug
for fd in [0, 1, 2]:
try:
os.close(fd)
except Exception:
logger.info("File descriptor was not open")
...
_close_fds() #make sure there are no open file descriptors for the chile to enherit
pid = subprocess.Popen([_ROOT_PATH + "something.py"]).pid
...
Is there a better way to do this?
A:
When you are starting process C from B, and you don't want it to inherit any file handles, use the following arguments in subprocess.Popen;
close_fds=True
Set stdin, stdout and stderr to subprocess.PIPE or subprocess.DEVNULL.
The first closes all file handles except stdin, stdout and stderr. The arguments listed under (2) take care of those.
| {
"pile_set_name": "StackExchange"
} |
Q:
Redundant SAM-constructor can't be remove for Kotlin declared function, but works on Java declared function
I have a Java Class function as below
public void setPositiveButton(int resId, DialogInterface.OnClickListener listener)
I also have the same Kotlin Class function as below
fun setPositiveButton(resId: Int, listener: DialogInterface.OnClickListener)
When I call them from a Kotlin code
javaClassObj.setPositiveButton(R.string.some_string,
DialogInterface.OnClickListener { _, _ -> someFunc()})
kotlinClassObj.setPositiveButton(R.string.some_string,
DialogInterface.OnClickListener { _, _ -> someFunc()})
The Java Class function call could be reduced, but not the Kotlin Class function
javaClassObj.setPositiveButton(R.string.some_string,
{ _, _ -> someFunc()})
kotlinClassObj.setPositiveButton(R.string.some_string,
DialogInterface.OnClickListener { _, _ -> someFunc()})
Why can't the Kotlin function call reduce the redundant SAM-Constructor as per enabled for Java?
A:
Why would you use SAM in kotlin? while it has native support for functions.
The SAM convention is used in java8 as a workaround not having native function support.
from kotlin doc#sam-conversions:
Note that SAM conversions only work for interfaces, not for abstract
classes, even if those also have just a single abstract method.
Also, note that this feature works only for Java interop; since Kotlin
has proper function types, automatic conversion of functions into
implementations of Kotlin interfaces is unnecessary and therefore
unsupported.
you should then declare a function directly.
fun setPositiveButton(resId: Int, listener: (DialogInterface, Int) -> Unit) {
listener.invoke(
//DialogInterface, Int
)
}
and then it can be used
setPositiveButton(1, { _, _ -> doStuff() })
In kotlin 1.4 you can use SAM conversions for Kotlin classes.
fun interface Listener {
fun listen()
}
fun addListener(listener: Listener) = a.listen()
fun main() {
addListener {
println("Hello!")
}
}
A:
Extending @humazed answer as compiler complains that
lambda argument should be moved out of parenthesis
setPositiveButton("ok"){_,_ -> doSomething()}
| {
"pile_set_name": "StackExchange"
} |
Q:
Display NLog trace in RichTextBox
I whant to display NLog trace into RichTextBox at the same time when app executes
logger.Trace("This is a Trace message");
logger.Debug("This is a Debug message");
logger.Info("This is an Info message");
logger.Warn("This is a Warn message");
logger.Error("This is an Error message");
logger.Fatal("This is a Fatal error message");
Has NLog any global event so it is possible to use it and populate RichTextBox?
Thank you!
A:
We have to install https://www.nuget.org/packages/NLog.Windows.Forms
After this use NLog.Windows.Forms;
And finally add the code
private void FormMain_Load(object sender, EventArgs e)
{
NLog.Windows.Forms.RichTextBoxTarget target = new NLog.Windows.Forms.RichTextBoxTarget();
target.Name = "RichTextBox";
target.Layout = "${longdate} ${level:uppercase=true} ${logger} ${message}";
target.ControlName = "richTextBoxMainLog";
target.FormName = "FormMain";
target.AutoScroll = true;
target.MaxLines = 10000;
target.UseDefaultRowColoringRules = false;
target.RowColoringRules.Add(
new RichTextBoxRowColoringRule(
"level == LogLevel.Trace", // condition
"DarkGray", // font color
"Control", // background color
FontStyle.Regular
)
);
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Debug", "Gray", "Control"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Info", "ControlText", "Control"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Warn", "DarkRed", "Control"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Error", "White", "DarkRed", FontStyle.Bold));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Fatal", "Yellow", "DarkRed", FontStyle.Bold));
AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper();
asyncWrapper.Name = "AsyncRichTextBox";
asyncWrapper.WrappedTarget = target;
SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace);
}
Also you need to configure NLog target.
<target xsi:type="RichTextBox"
name="target2"
layout="${message} ${rtb-link:link text in config}"
formName="Form1"
ControlName="richTextBoxMainLog"
autoScroll="true"
maxLines="20"
allowAccessoryFormCreation="false"
messageRetention="OnlyMissed"
supportLinks="true"
useDefaultRowColoringRules="true" />
Download the sample project and test it https://github.com/NLog/NLog.Windows.Forms
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a CocoaPod
For 2 days I am trying to make a cocoapod in swift using Xcode 7.1.1
Problem is when I install pod using pod install, my pod files get integrated with the project but I can not use my pod files. The reference is missing. The project does not recognize my pod files.
Tutorials I have tried:
https://guides.cocoapods.org/making/using-pod-lib-create
http://code.tutsplus.com/tutorials/creating-your-first-cocoapod--cms-24332
http://useyourloaf.com/blog/creating-a-cocoapod.html
Both pod lib lint and pod spec lint passes validation. Also I was successful in pod trunk push
You can get the pod in your project using
pod 'WARDoorView', '~> 0.1.2'
You can try the pod using
pod try WARDoorView
If you download the repo, the example project has compiler error in ViewController.swift:
Use of undeclared type 'WARDoorView'
But I can see the WARDoorView.swift under pods
The repository is at
https://github.com/rishi420/WARDoorView
A:
God... after 3 days I'm able to find the issue.
I had to make my class public and any function I want to call from outside public.
public class WARDoorView: UIView { ...
public func doorOpen(angle: Double ...
public func doorClose(duration: NSTimeInterval ...
I thought public was the default. I was wrong.
New pod using
pod 'WARDoorView', '~> 1.0.2'
| {
"pile_set_name": "StackExchange"
} |
Q:
Sinatra unable to set cookies from helper file
I have a helper file in my sinatra app that has the following code:
todo_sinatra_app/helpers/sessions_helper.rb
class SessionsHelper
def self.sign_in(user)
cookies[:remember_token] = { value: user.remember_token, expires: 20.years.from_now.utc }
self.current_user = user
end
...
end
When I try to call on the sign_in method from my app.rb file, it throws an error that it doesn't know how to create cookies:
require 'sinatra'
require 'pg'
require 'sinatra/activerecord'
require 'sinatra/contrib'
require 'sinatra/cookies'
require './helpers/sessions_helper'
...
post '/sign_in' do
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
SessionsHelper.sign_in(user)
redirect '/'
else
...
end
Here is my gemfile.lock
GEM
remote: https://rubygems.org/
specs:
activemodel (5.2.0)
activesupport (= 5.2.0)
activerecord (5.2.0)
activemodel (= 5.2.0)
activesupport (= 5.2.0)
arel (>= 9.0)
activesupport (5.2.0)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 0.7, < 2)
minitest (~> 5.1)
tzinfo (~> 1.1)
arel (9.0.0)
backports (3.16.0)
bcrypt (3.1.13)
byebug (11.0.1)
coderay (1.1.2)
concurrent-ruby (1.1.5)
daemons (1.3.1)
diff-lcs (1.3)
eventmachine (1.2.7)
i18n (1.8.2)
concurrent-ruby (~> 1.0)
method_source (0.9.2)
minitest (5.14.0)
multi_json (1.14.1)
mustermann (1.1.1)
ruby2_keywords (~> 0.0.1)
pg (1.2.2)
pry (0.12.2)
coderay (~> 1.1.0)
method_source (~> 0.9.0)
pry-byebug (3.7.0)
byebug (~> 11.0)
pry (~> 0.10)
rack (2.1.2)
rack-protection (2.0.8.1)
rack
rack-test (1.1.0)
rack (>= 1.0, < 3)
rake (13.0.1)
rspec (3.9.0)
rspec-core (~> 3.9.0)
rspec-expectations (~> 3.9.0)
rspec-mocks (~> 3.9.0)
rspec-core (3.9.1)
rspec-support (~> 3.9.1)
rspec-expectations (3.9.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.9.0)
rspec-mocks (3.9.1)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.9.0)
rspec-support (3.9.2)
ruby2_keywords (0.0.2)
sinatra (2.0.8.1)
mustermann (~> 1.0)
rack (~> 2.0)
rack-protection (= 2.0.8.1)
tilt (~> 2.0)
sinatra-activerecord (2.0.14)
activerecord (>= 3.2)
sinatra (>= 1.0)
sinatra-contrib (2.0.8.1)
backports (>= 2.8.2)
multi_json
mustermann (~> 1.0)
rack-protection (= 2.0.8.1)
sinatra (= 2.0.8.1)
tilt (~> 2.0)
sinatra-flash (0.3.0)
sinatra (>= 1.0.0)
thin (1.7.2)
daemons (~> 1.0, >= 1.0.9)
eventmachine (~> 1.0, >= 1.0.4)
rack (>= 1, < 3)
thread_safe (0.3.6)
tilt (2.0.10)
tzinfo (1.2.6)
thread_safe (~> 0.1)
PLATFORMS
ruby
DEPENDENCIES
activerecord (= 5.2)
bcrypt
minitest (= 5.14.0)
pg
pry-byebug
rack-test
rake
rspec
sinatra
sinatra-activerecord
sinatra-contrib
sinatra-flash
thin
BUNDLED WITH
2.1.4
I've tried with putting the require 'sinatra/cookies' inside the helper file, and made sure that I have the gem 'sinatra-contrib' bundled. It works when I set a cookie directly in my app.rb file. Can anyone suggest anything else that I can check or what could be the issue?
A:
When you require 'sinatra' certain magic things happen that brings a bunch of stuff into scope and essentially turns your app.rb into an instance of Sinatra::Application. The cookies method is only defined on instances like this – it isn’t present on other classes automatically.
What you probably want to do is turn your helper into a real Sinatra style helper by making it a module and then loading it using the helpers keyword, which will just make these instance methods:
module SessionsHelper
def sign_in(user)
cookies[:remember_token] = { value: user.remember_token, expires: 20.years.from_now.utc }
self.current_user = user
end
...
end
And in your main file:
require './helpers/sessions_helper'
helpers SessionsHelper
...
post '/sign_in' do
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
sign_in user
redirect '/'
else
...
end
You might like to read more about this in the README.
| {
"pile_set_name": "StackExchange"
} |
Q:
Requiring more than just a programming language tag before an answer is accepted
Since Stack Overflow is centered around programming language-related questions we know that the programming language tags are by far the most effective and necessary tag to get an answer. This is very effective for new users and easy to understand.
Now for us more experienced users who do searches for previous questions before answering existing questions or posting new questions, it is far more efficient and faster to search based on tags than words because one may only need to search for one or two tags in addition to the programming language tag, and can check for other tags in the list or look at the tags of similar questions to see what tags the community are using. While if one searches for words in the Q&A one not only has to search many more words, but also hope to have covered all of the possible words and phrases that cover the question.
The way I commonly view tags is as a hierarchy of terms used to narrow down to a specific area, like the Dewey Decimal System for a library, but using tags instead of numbers.
If questions with only a programming language tag are required to have more than just the programming language tag it increases the chance of finding more relevant questions when searching with tags. With better results when searching for duplicate questions or similar questions leads to a better site.
It is not uncommon for me with f# to suspect a question is a duplicate, but being unable to find it with just a tag search. Then upon finding the duplicate see that an obvious tag was not included. This often happens, because new users don't know what tags to use and often ask the same question, but in a different guise.
As such I would like to recommend, that before a question can receive an accept vote, that if the only tag is a programming language tag that another tag must be added for further classification. The reason for placing the constraint on the accepted answer is because many new users do not know what tags to use, but the person answering typically does know what additional tags are relevant. Also since 2,000 reputation points is required to edit a question, additionally I recommend that anyone answering a question have the right to edit only the tags for the corresponding question.
TL;DR
In searching for duplicate or related questions I searched for
[tags] minimum
[tags] recommend
[site-recommendation] [tags]
[related-questions] [tags]
[tag-search]
[tag-tips]
[suggested-tags]
If this is a duplicate question, please let me know...
The other Meta Q or A of interest to this question:
Should some tags “warn” users before posting? - Answer
Compromise: It may be possible to require extra confirmation from
low-reputation or new users, and then stop requiring such as soon as
they reach some reputation line.
I find this of interest because in a related manner it suggests that new users can be required to add more tags and once they have enough reputation points avoid the extra step. IIRC, currently additional tags are only suggested.
Do we need to force any questions tagging assembly to tag the architecture also?
Many questions are incorrectly tagged simply because the person asking
doesn't know any better (either in the technology they're using or
they don't fully understand how the site works). Some of those people
will be first semester students at some random college/university and
will be crapping themselves about the subject they've got themselves
in to.
I find this of interest because it reaffirms that many question OP are not effective at tagging their own questions.
Help the helpless with how-to-ask tag tips
I find this interesting, because I don't recall seeing such a pop up dialog for a specific tag, but a dialog could be used as part of this recommendation. I tend to hang out on the fringes, e.g. f#, prolog, compiler-construction, where the ethos are more homegrown.
Search results incorrect for F#
When you search for just C# it gets converted in a tag search because
the SE search engine is programmed to treat the search string as a tag
when a search string is one of the top 60 tags of the SE site. C# is
in the top tag list whereas F# is not, so it is treated as a regular
search.
Learned something new about searching and tags.
Meta SO tags
I find this of interest because it shows that requirements can be placed on tags.
A:
The way I commonly view tags is as a hierarchy of terms used to narrow
down to a specific area, like the Dewey Decimal System for a library,
but using tags instead of numbers.
This is, to my eye, the major flaw with your idea here: the tag system isn't inherently hierarchical. In some cases the applicable tags may happen to work out that way, but it's not an assumption of the system, so you shouldn't be applying that expectation to all questions.
Further, the reason we allow (almost) anyone to edit (almost) any post is a recognition that a post doesn't have to be perfect to be posted. If you see a question that you think could benefit from additional tagging, you can and should edit to add the appropriate tags. That said, there's plenty of decent posts, this one included, that only start out with one tag - and many that only really need one.
| {
"pile_set_name": "StackExchange"
} |
Q:
При подключении API Telegram к node.js
Установил программу Node.js, потом создал папку, установил в нее сервер nvm (команда npm init), далее туда же установил библиотеку для взаимодействия с API Telegram (команда npm install --save node-telegram-bot-api), далее написал код:
const TelegramBot = require('node-telegram-bot-api');
// replace the value below with the Telegram token you receive from @BotFather
const token = '111111111:XXXXXXXXXXXXXXXXXXXXXXXXX';
// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, {polling: true});
// Matches "/echo [whatever]"
bot.onText(/\/echo (.+)/, (msg, match) => {
// 'msg' is the received Message from Telegram
// 'match' is the result of executing the regexp above on the text content
// of the message
const chatId = msg.chat.id;
const resp = match[1]; // the captured "whatever"
// send back the matched "whatever" to the chat
bot.sendMessage(chatId, resp);
});
// Listen for any kind of message. There are different kinds of
// messages.
bot.on('message', (msg) => {
const chatId = msg.chat.id;
// send a message to the chat acknowledging receipt of their message
bot.sendMessage(chatId, 'Received your message');
});
Потом выводит ошибку, но бот работает:
node-telegram-bot-api deprecated Automatic enabling of cancellation of promises
is deprecated.
In the future, you will have to enable it yourself.
See https://github.com/yagop/node-telegram-bot-api/issues/319. module.js:652:30
A:
Это не ошибка! Данная строка вываливается всегда при включении..
| {
"pile_set_name": "StackExchange"
} |
Q:
What is Wise to Study For a Successful Career Outside of Academia?
Next year I will be starting an MS program in the Computer Science department (I have come from a grad-prep program). I have "learned" C++, C, Java, assembly, CS math, and OS.
When I enter this program, I need to pick a track. My problem is I do not know what to choose yet.
I am sure this will remedy over time, but I wanted to get others' opinions.
I have heard databases and cyber-security make the most money. As far as job availability, I have heard that there are a lot of jobs in web development (using things such as Javascript, Node JS, etc).
What do you believe is a wise area to focus on during the next 1-3 years?
A:
I think this is an ongoing question for any stage of your career. Trends change a lot so you need to have a diverse set of tools available, while focusing on a few technologies so as not to spread yourself too thin.
First of all, it is probably not the best idea to choose according to what makes the most money. Highly paid jobs are more scarce and so the competition will be tougher. You cannot ensure you will have a high salary just by learning specific technologies.
On the other hand, you are more likely to become an expert in a field you enjoy working in and have an intuition for. So I would say try a few different things and see what you are best at. See what interests you. Obviously you can narrow this down by combining your current interests with the current trends, but try not to be limited by projected salaries; these are both highly changeable and misleading, and are used mainly in sales pitches for programming courses.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript condensing - defining many variables in one line
We generally have the understanding that functions in javascript are used to execute blocks of code with a single call. However, I'm currently working in a system that contains many functions which require many variables to be defined, so I'm seeing a lot of repeat code. I'd love to put the variable declarations in a function so they don't take a whole bunch of space, but is something similar to that even possible?
A:
I'd love to put the variable declarations in a function so they don't take a whole bunch of space, but is something similar to that even possible?
If you mean:
function one() {
var a, b, c, d, e, f;
// ...
}
function two() {
var a, b, c, d, e, f;
// ...
}
(E.g., each function has its own copy of the variables.)
...and you want
// Doesn't work
function declare() {
var a, b, c, d, e, f;
}
function one() {
declare();
// ...use a, b, etc. here
}
function two() {
declare();
// ...use a, b, etc. here
}
No, you cannot do that.
You might consider encapsulating the variables in an object, if the same set of variables is used in multiple places. In fact, the whole thing sounds like it might be refactored as an object.
But without too much refactoring:
function declare() {
return {
a: /*...*/,
b: /*...*/,
c: /*...*/,
d: /*...*/,
e: /*...*/,
f: /*...*/,
};
}
function one() {
var o = declare();
// ...use o.a, o.b, etc.
}
function two() {
var o = declare();
// ...use o.a, o.b, etc.
}
But again, that's the minimal-impact solution. It's like that if you look at your overall code with the idea that you could organize things a bit into objects, you'd find a less artificial way than the above.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create interface for object or for action / behavior?
When come to create an interface, do u create it based on behavior, follow the -able standard, e.g.
interface Comparable
interface Enumerable
interface Listable
interface Talkable
interface Thinkable
Or based on object, e.g.
interface Comparator
interface Enumerator
interface List
interface Human
And why?
UPDATE
This question is not about the naming convention (-able suffix or I- prefix). This is about the design intention of the interface, and the impact of it, in terms of:-
flexibility
complexity / simplicity
maintainability
For example, if I need to implement different features, by doing -able way, I can declare my class as
public class Man implements Talkable, Thinkable, Laughable
public class Woman implements Talkable, Thinkable, Laughable
On the other hand, if we create interface based on object, we can use it as
public class Man implements Human
public class Woman implements Human
And we can also use it for polymorphism purpose.
Human man = new Man();
A:
Interfaces are not about what a concrete class does. They are more about what the client needs, and what is substitutable in place of what the client needs. For example, instead of trying to extract an interface from a Man class, instead focus on one of the classes that use the Man class. What does it do? Perhaps it is a Conversation class that wants to make things talk to each other. If you gave it two Man classes, it could call talk() on them. But if you wanted it to be more flexible, you can abstract out the concept of what it does - makes things talk, and have it use a Talkable interface (for example). When you see a Talkable interface on this Conversation class, you shouldn't think "that is really a Man" but rather, "Where I see a Talkable, I can substitute anything that implements Talkable, whether it is a Man, Woman, Parrot, Robot, etc."
If I am unclear, there are good resources available on the subject. Check out Robert Martin's Dependency Inversion Principle, Interface Segregation Principle, and Liskov Substitution Principle articles for starters.
A:
An interface Comparable should be implemented by classes whose instances can be COMPARED; an interface Comparator (in languages that do any level of generic programming, probably Comparator<T>!-) should be implemented by classes whose instances can COMPARE OTHERS. Both usages have excellent use cases, essentially disjoint from each other; you seem to be missing this key semantic distinction.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to disable Auto Complete in Sublime Text (2&3)
I understand there are a few questions surrounding the auto_complete function in Sublime Text.
However, I have not been able to disable the auto_complete function in the Sublime Text settings (I've tried both Sublime Text 2&3). I just get the "Error trying to parse settings: Unexpected trailing characters in Packages/User/Preferences.sublime-settings:5:1" error when inputting the {"auto_complete": false,} command in user settings.
Would love to turn off the setting, but can't find a way to. Any help much appreciated!
A:
Put , after font-size:17 like:
{
"font_size":17, //note a comma here after 17
"auto_complete": false,
}
A:
There are two options
1: In Preference => User Check if TernJS plugin is Installed. If Yes Unistall it from your editor(Sublime Text).
2: In Preferences => User check for the auto_complete and change it to false
"auto_complete": false,
Restart Your Editor(Sublime Text)
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove textarea while preserving formatting
I have a textarea where users can edit some text. On click of an element I need to to remove textarea from around text, while preserving formatting, like line breaks etc. I need to do it with jQuery, because I cannot refresh the page.
$(document).on("click", ".close", function() {
var formattedText= $(this).prev("textarea").text();
$(this).prepend().text(formattedText);
});
<textarea>
Formatted text here.
And here...
</textarea>
<button class="close">Remove textarea</button>
A:
You are supposed to use val() for textarea to get the inputted text.
First you get the text value, then you replace the textarea with a div with the inputted text.
$(document).on("click", ".close", function() {
var formattedText= $("textarea").val();
$('textarea').replaceWith('<div>'+ formattedText +'</div>');
});
DEMO
EDIT
You can preserve line breaks by adding white-space:pre; to your CSS code.
Updated Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
How does one effectively increase intrigue?
I recently finished a game as ARC, who get a 25% boos to covert ops speed and intrigue increase. I deliberately researched directly to Computing, and subsequently produced the Spy Agency because of the bonus. My intent was to covert-ops my way to victory.
What I discovered is that the AIs (at least in this particular game) are exceedingly good at keeping the intrigue level relatively low in all of their cities. In my 320+ turn game, the highest-level covert operation I was able to perform was Recruit Defectors, at intrigue level 3. I never had the chance to Hack Satellites, much less a Coup D'etat. (Note: I never tried to start a new mission with a counter-agent in the city. If I noticed the AI had a defensive spy, I left that city and started elsewhere.)
That said, I know it is certainly possible to get the intrigue that high. I am watching Marbozir play on YouTube, and he was able to Coup a capital. He assigns the spy [1] when the city is at maximum intrigue, and successfully captures it [2] when the mission is completed 18 turns later.
How did he manage to get the intrigue that high in the AI capital? Any tips for boosting intrigue?
[1] Spy assignment
[2] City capture
A:
Before you understand the best ways to increase intrigue, you have to understand how intrigue works.
To gain intrigue, you must to preform a covert operation on the city specified to boost it. The harder and riskier the quest, the more intrigue you can earn (for that city).
A city has a minimum intrigue level of 0 and a maximum of 5. The higher level of intrigue the city has, the more difficult missions will be unlocked.
You have 10 possible missions:
1. Establish Network: Very Easy. Gathers various pieces of information about the target city and player, and displays the information in a window adjacent to the city while in covert operations view. The amount and detail of the information increases with the performing agent’s level.
2. Siphon Energy: Easy difficulty. Diverts energy resources from the target city to the player.
3. Steal Science: Easy difficulty. Diverts science resources from the target city to the player.
4. Steal Technology: Moderate difficulty. Steals a technology from the target player. This doesn’t necessarily match a tech that the target player has. One is automatically selected that is an appropriate reward.
5. Hack Satellites: Moderate difficulty. Deorbits a random satellite.
6. Call Worm Strike: Hard difficulty. Draws hostile aliens to the target city. This operation is allowed only by the Harmony Affinity level.
7. Dirty Bomb: Hard difficulty. Decreases the target city’s population substantially. This operation is allowed only by Purity Affinity level.
8. Sabotage: Hard difficulty. Pillages nearby improvements. This operation is allowed only by Supremacy Affinity level.
9. Recruit Defectors: Moderate difficulty. Gives the player a set of random military units at their capital.
10. Coup D’etat: Moderate difficulty. Transfers control of the target city to the performing player.
And now for the tips on boosting a city's intrigue:
Agent Rank. These two words will change how you play covert ops in the game.
So you have your agents, gaining a cities intrique from doing these missons to boost the intrigue of the enemy city, but your agent's are getting a special reputation while doing it. They are boosting their rank, which gives them more of a chance to succeed in the later missons. This is a key advantage, you can basically grind low level missons on city's all over to boost your Agent's rank and it will greatly help your chance of succeeding in a mission.
The higher your Agent's rank, the more likely his covert ops misson will be successful.
Be aware that even with the lower ranked missons, your agent will always have a chance of being killed during the misson. Try playing strategically, and you will be able to do a Coup D'etat in no time.
Source 1
| {
"pile_set_name": "StackExchange"
} |
Q:
Criar Vhosts Apache no Windows: Não passa do htdocs
Estou seguindo um tutorial na net ensinando a criar VirtualHosts no Apache em ambiente Windows
Meu http-vhosts.conf
<VirtualHost _default_:80>
DocumentRoot "${SRVROOT}/htdocs"
#ServerName www.example.com:80
</VirtualHost>
<VirtualHost *:80>
ServerName fielcard.net.br
DocumentRoot "D:\Trabalhos\host\htdocs\fielcard.net.br"
ErrorLog "logs/projeto-error.log"
CustomLog "logs/projeto-access.log" common
<Directory "D:\Trabalhos\host\htdocs\fielcard.net.br" >
DirectoryIndex index.php index.html index.htm
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Tem mais coisas. Porém com linhas comentadas.
Meu hosts do windows
127.0.0.1 fielcard.net.br
Novamente: Tem mais coisas. Porém com linhas comentadas.
Apache 2.4
PHP 7.3
Tentativas:
ServerName fielcard.net.br.local
127.0.0.1 fielcard.net.br.local
Reiniciei o Apache.
Reiniciei o Windows.
Meu Apache tem a pasta htdocs com um arquivo index.php com apenas a palava localhost. E dentro dela para cada site que desenvolvo existe uma pasta com o nome do site.
Então, desejo criar um vhosts para cada site.
O resultado que estou obtendo,sempre é o mesmo:
Aparece
Localhost
no Browser!
Isto é, nunca entra na pasta do projeto!
O que está errado?
COMPLEMENTO:
Descobri o seguinte:
Na pasta conf do Apache tem a pasta extra
Dentro dessa pasta tem 2 arquivos de configuração a saber:
httpd-ahssl.conf => Configuração de Virtuais Hosts com SSL
e
httpd-vhosts.conf => Configuração de Virtuais Hosts sem SSL
De fato, ao configurar o Virtual Host para um site, estava toda hora redirecionando para a página na raiz do htdocs e não para dentro do site.
Isso se deve pelo fato de que na pasta do fielcard.net.br, tem um .htaccess redirecionando toda entrada http para https e, como as entradas https estavam setadas seu DocumentRoot para a raiz do localhost logo toda tentativa de VirtualHost caia na raiz e por conseguinte no index.php que contem apenas a palavra Localhost como já informado anteriormente aqui na pergunta.
Sem SSL, a porta e sempre a 80, logo, estava funcionando a virtualização mas o redirecionamento ás pastas de cada novo host não!
A dúvida agora passa a ser outra.
Eis o novo arquivo httpd-ahssl.conf
##
## SSL Virtual Host Context
##
<VirtualHost _default_:443>
SSLEngine on
ServerName localhost:443
SSLCertificateFile "${SRVROOT}/conf/ssl/server.crt"
SSLCertificateKeyFile "${SRVROOT}/conf/ssl/server.key"
DocumentRoot "D:/Trabalhos/host/htdocs/fielcard.net.br"
# DocumentRoot "${SRVROOT}/htdocs"
# DocumentRoot access handled globally in httpd.conf
CustomLog "${SRVROOT}/logs/ssl_request.log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
<Directory "${SRVROOT}/htdocs">
Options Indexes Includes FollowSymLinks
AllowOverride AuthConfig Limit FileInfo
Require all granted
</Directory>
</virtualhost>
<VirtualHost *:443>
SSLEngine on
ServerName serverone.tld:443
SSLCertificateFile "${SRVROOT}/conf/ssl/serverone.crt"
SSLCertificateKeyFile "${SRVROOT}/conf/ssl/serverone.key"
DocumentRoot "D:/Trabalhos/host/htdocs/fielcard.net.br"
CustomLog "${SRVROOT}/logs/ssl_request.log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
<Directory "${SRVROOT}/htdocs">
Options Indexes Includes FollowSymLinks
AllowOverride AuthConfig Limit FileInfo
Require all granted
</Directory>
</virtualhost>
<VirtualHost *:443>
SSLEngine on
ServerName servertwo.tld:443
SSLCertificateFile "${SRVROOT}/conf/ssl/servertwo.crt"
SSLCertificateKeyFile "${SRVROOT}/conf/ssl/servertwo.key"
DocumentRoot "D:/Trabalhos/host/htdocs/fielcard.net.br"
CustomLog "${SRVROOT}/logs/ssl_request.log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
<Directory "${SRVROOT}/htdocs">
Options Indexes Includes FollowSymLinks
AllowOverride AuthConfig Limit FileInfo
Require all granted
</Directory>
</virtualhost>
<VirtualHost _default_:443>
SSLEngine on
ServerName localhost:443
SSLCertificateFile "${SRVROOT}/conf/ssl/server.crt"
SSLCertificateKeyFile "${SRVROOT}/conf/ssl/server.key"
DocumentRoot "D:/Trabalhos/host/htdocs/mvc_crud_pdo"
CustomLog "${SRVROOT}/logs/ssl_request.log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
<Directory "${SRVROOT}/htdocs">
Options Indexes Includes FollowSymLinks
AllowOverride AuthConfig Limit FileInfo
Require all granted
</Directory>
</virtualhost>
<VirtualHost *:443>
SSLEngine on
ServerName serverone.tld:443
SSLCertificateFile "${SRVROOT}/conf/ssl/serverone.crt"
SSLCertificateKeyFile "${SRVROOT}/conf/ssl/serverone.key"
DocumentRoot "D:/Trabalhos/host/htdocs/mvc_crud_pdo"
CustomLog "${SRVROOT}/logs/ssl_request.log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
<Directory "${SRVROOT}/htdocs">
Options Indexes Includes FollowSymLinks
AllowOverride AuthConfig Limit FileInfo
Require all granted
</Directory>
</virtualhost>
<VirtualHost *:443>
SSLEngine on
ServerName servertwo.tld:443
SSLCertificateFile "${SRVROOT}/conf/ssl/servertwo.crt"
SSLCertificateKeyFile "${SRVROOT}/conf/ssl/servertwo.key"
DocumentRoot "D:/Trabalhos/host/htdocs/mvc_crud_pdo"
CustomLog "${SRVROOT}/logs/ssl_request.log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
<Directory "${SRVROOT}/htdocs">
Options Indexes Includes FollowSymLinks
AllowOverride AuthConfig Limit FileInfo
Require all granted
</Directory>
</virtualhost>
# End SNI Demonstration Config
Não sei se estou fazendo corretamente. Mas quando digito no browser:
https://fielcard.net.br
Vai de boa.
Mas quando digito
https://mvc_crud_pdo
está abrindo
https://fielcard.net.br
ao invés de
https://mvc_crud_pdo
O que está errado agora?
Outra dúvida: se esse é mesmo caminho certo, então quer dizer que para cada virtual host terei que configurar 3 blocos de código iguais esse? Se sim, daqui um tempo esse arquivo vai estar gigante!
É assim mesmo?
A:
<VirtualHost *:80>
DocumentRoot "${SRVROOT}/htdocs"
ServerName localhost
ServerAlias localhost
</VirtualHost>
<VirtualHost *:80>
ServerName fielcard.net.br
ServerAlias fielcard.net.br
DocumentRoot "D:\Trabalhos\host\htdocs\fielcard.net.br"
ErrorLog "logs/projeto-error.log"
CustomLog "logs/projeto-access.log" common
<Directory "D:\Trabalhos\host\htdocs\fielcard.net.br" >
DirectoryIndex index.php index.html index.htm
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
| {
"pile_set_name": "StackExchange"
} |
Q:
Limits of the function given by the following graph
Let $$
f(x)=\left\{
\begin{array}{c}
3-x, \ \ \ x<2 \\
(x/2) +1, \ \ \ x>2 \\
\end{array}
\right.
$$
(a) Find $\lim_{x\to 4^+}f(x)$ and $\lim_{x\to 4^-} f(x)$
(b) Does $\lim_{x\to 4}f(x)$ exist? If so, what is it?
Here's what I got:
(a) $\lim_{x\to 4^+}f(x)=3$ and $\lim_{x\to 4^-}f(x)=3$
(b) Yes, 3
Is that right?
The circles in the graph mean that the point there is "open", as in open\closed intervals.
A:
Now, when the limit tends to $4$ (since $4>2$),you take the equation $f(x)=\frac{x}{2}+1$, then:
$$\lim_{x\to4^+}\frac{x}{2}+1=\lim_{x\to4^-}\frac{x}{2}+1=3$$
like the lateral limits are equal, the limit in that point exist.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are the lightsaber battles in the original trilogy slower and less acrobatic than those in the prequel trilogy?
Obviously as filmed the lightsaber battles in the original trilogy are slower and less acrobatic than those in the prequel trilogy. Is this canon? There's a popular question that basically asks why this is and most of the answers are out of universe explanations about lightsabers originally being meant to be heavy, improvements in CG, and that the choreographer in the original trilogy was an Olympic fencer while the choreographers in the prequel trilogy were stuntmen. This implies that the lightsaber battles as shown are not meant to be taken literally.
Why do the lightsaber moves of Luke Skywalker look so uncoordinated and crude compared to the prequels?
On the other hand, the lightsaber battles tend to be taken more literally in questions comparing the lightsaber skills of Anakin and Darth Vader and various explanations are given for why Darth Vader doesn't do flips.
I've always figured that when a lightsaber battle happens it should just be understood that <epic battle takes place> and the exact movements are unimportant. If that weren't the case, it would be sensible to ask silly questions like "Why are Qui Gon Jinn and Obi-Wan playing around in the battle with Darth Maul at the end of Episode I? Why are they flipping around instead of trying to kill each other? Who are they trying to impress?"
A:
Seriously though:
For Episode 4:
All of the fighting moves in the duel were two-handed strokes, in keeping with Lucas' initial concept that lightsabers were incredibly heavy and difficult to handle.
As we progress through Empire and Jedi:
Lucas rethought the fighting styles. He decided to make them "faster and more intense," symbolizing Luke Skywalker's increasing mastery of the weapon.
Upon planning and filming the prequels:
Peter Diamond was replaced by Nick Gillard, who completely rethought the Jedi fighting styles. George Lucas envisioned that during this time period, the Jedi had reached their peak in terms of martial arts development, so the choreography had to be a great deal faster and more sophisticated. Gillard wanted to convey the sense that the Jedi had studied every single style of swordplay available, his idea being that since they had chosen such a short-range weapon, they would have to be so good if they're up against ray guns and lasers. Gillard choreographed the duels as what he described as "a chessgame played at a thousand miles an hour," with every move being analogous to a check.
So yes, the OT (especially Luke) is more crude because Luke had nobody to train him
http://starwars.wikia.com/wiki/Lightsaber_combat/Legends
| {
"pile_set_name": "StackExchange"
} |
Q:
How to monitor and automatically restart mysql?
I'm running mysql on Debian.
Is there a way to monitor mysql and restart it automatically if it locks up? For example sometimes the server starts to take 100% of cpu and starts running very slowly. If I restart mysql, things clear up and the server starts working fine, but I'm not always present to restart it manually.
Is there a way to monitor MySQL and if the CPU is above 95% for more than 10 minutes straight then MySQL will automatically be restarted
A:
You can do this with monit. For example, to alert & restart mysql, assuming you run monit on a 60 second cycle:
check process mysqld
with pidfile /var/run/mysqld.pid
if cpu usage > 99% for 10 cycles then alert
if cpu usage > 99% for 10 cycles then restart
monit is very flexible and can do pretty much any sort of monitoring of processes, memory, etc. you can think of.
This could probably be done with ps-watcher too, but it's hard to make ps-watcher remember this sort of state and act on it. monit is the right tool to use.
| {
"pile_set_name": "StackExchange"
} |
Q:
Build software on Linux using cross toolchain
Motorola provides a cross compiling toolchain for building Software for their Set Top Box VIP1710. You have to extract it to /usr/local/kreatel and there you have a tree of build tools:
./bin
./bin/mipsel-kreatel-linux-gnu-addr2line
./bin/mipsel-kreatel-linux-gnu-ar
./bin/mipsel-kreatel-linux-gnu-as
./bin/mipsel-kreatel-linux-gnu-c++
./bin/mipsel-kreatel-linux-gnu-c++filt
./bin/mipsel-kreatel-linux-gnu-cpp
./bin/mipsel-kreatel-linux-gnu-g++
./bin/mipsel-kreatel-linux-gnu-gcc
...
./include
./lib
Now how do I make those configure scripts using my cross-compiling tools instead of my systems' gcc?
A:
the --host parameter to configure, like this
./configure --host=arm-9tdmi-linux-gnu
where arm-9tdmi-linux-gnu is the identfication of the target system in my case - you can have multiple targets in one crosstool installation btw.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to edit chart data using office.js within Microsoft Word
I'm creating a word add-in using the word javascript api that pulls data from database, allowing users to create tables/text with the data. I would now like to add the functionality to change charts based on the data
I can see information about editing charts in the documentation for excel, however I can't see anything for word.
Is it possible to edit chart data within word?
If so, would someone be able to provide me an example or link to the appropriate location to look?
I've tried doing it in excel and have made progress but can't see anything on the word side
A:
I'm afraid that there are no chart editing APIs in the Word JavaScript yet. It's a good idea, and you can suggest it at Office Developer Suggestion Box.
In the meantime, a chart in Word is a element in the file's OOXML. You could try the following workaround: Your add-in could get the XML using the Office.Document.getFileAsync, edit the OOXML, then use the Word createDocument API to create a new document that is just like the original, but with your chart edits.
| {
"pile_set_name": "StackExchange"
} |
Q:
Vertically Center Icon with CSS
I am building a web site. My web site will have blocks of content. Each block will have a title, some text, and an icon. My challenge is, I'm trying to vertically center each icon in the block. Currently, I have the following HTML or you can look at the jsfiddle.
<blockquote>
<div class="row">
<div class="small-10 columns">
<h4>The Block Title</h4>
<em>Some small blurb</em>
<p>Here is a paragraph relating to this block. It may include a couple of sentences. These sentences will wrap. Ultimately, the heart needs to be vertically centered.</p>
</div>
<div class="small-2 columns">
<span class="fi-heart" style="font-size:4rem;"> </span>
</div>
</div>
</blockquote>
In this code block, I'm using Zurb Foundation to help with layout. However, I can't seem to get the heart icon to center vertically in my right column. Does anyone know how I can do this with CSS?
Thank you
A:
Add a line-height property to your inline style for <span class="fi-heart"> with a value equal to the font-size:
font-size:4em; line-height: 4em
| {
"pile_set_name": "StackExchange"
} |
Q:
javascript welcoming msgbox problem
i'm doing my html and javascript class project
and i want to have a msgbox welcoming the visitor asking for his name and then a welcoming msgbox shows up saying "hello (the name added)"
i know how to do that but my only problem is that if i pressed back and went to the homepage of my website again, the msg will show up again asking for my name
is there anyway to prevent this from happening? seriously don't want the visitor to wite his name each time he goes to the home page
please help
this is the code i'm using:
<script>
response = window.prompt("Welcome!","Please enter your name");
window.alert("hello " + response);
</script>
please help
A:
The example given on W3Schools for using cookies is exactly what you need.
http://www.w3schools.com/js/js_cookies.asp
A:
The script will aways execute the same way. When you tell it to show a message box every time the page is loaded, regardless of how often it has been done in the past, it WILL happen again and again and again and again.
You could save the name in a cookie, and before prompting anything just check if there's already a cookie with the name. If there is, use that one. If there isn't, ask for one, use it and save it in a cookie. How to do this is covered basically everywhere, try googling.
The worse problem I see here is the whole prompting and message boxing. Don't ever do that. If you ever had any visitor on that site, they will never be coming back. Don't do such things with Javascript. It's like you are running through the city, grabbing every person you see, hold them, ask them for their name, YELL it in their FACE and go do the same with the next person. It's all fun and games until someone looses an eye.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set DisableHWAcceleration key if HKEY_CURRENT_USER\SOFTWARE\Microsoft\Avalon.Graphics\ does not exist?
I checked few articles in internet and they all seems to assume that one can navigate to
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Avalon.Graphics\
with Registry Editor.
I don't have in my Win7 Enterprise machine Avalon.Graphics at all in Registry Editor. So how do I set DisableHWAcceleration = 1?
A:
If the registry key does not exist, then create it. I don't believe the Avalon.Graphics key is expected to exist by default. It hasn't existed any time I needed to set a WPF-related registry override, but they always got picked up after I added the key manually.
I don't know why so many articles are unclear on that point.
| {
"pile_set_name": "StackExchange"
} |
Q:
StackExchange vs. Stack Exchange
Which spacing is correct? I've seen both being used. Plus, there isn't really anything saying which is correct.
A:
Stack Exchange is correct.
Stack Exchange Inc. is the official name of the company.
(http://stackexchange.com/legal/trademark-guidance)
A complete extract:
Proper Use of the Stack Exchange Name
Stack Exchange Inc. is the official name of the company.
Stack Overflow is a programmer Q&A site on the Stack Exchange Network. As a name, Stack Overflow, is always written "Stack Overflow"
(two words, capital letters). The website domain name is always
written stackoverflow.com (no CamelCase, single word capitalization
rules apply). Currently, all Stack Exchange Network sites follow this
convention: Server Fault (serverfault.com), Super User
(superuser.com), etc.
A Stack Exchange site is a Q&A website built on the technology of Stack Exchange Inc. The phrase "Stack Exchange" is generally used as
an adjective, not a noun. One would say "Propose a Stack Exchange site
on Area 51" (correct), not "Propose a Stack Exchange on Area 51"
(wrong).
The Stack Exchange Network refers to the collection of Stack Exchange sites and services.
Area 51 (two words) is the site used to propose new Stack Exchange sites for the Stack Exchange Network.
The Stack Exchange API allows users to write applications based on the Stack Exchange engine. The API is always referred to as "Stack
Exchange API", even if the application is written for a specific site
(i.e. never Stack Overflow API, Server Fault API, etc.).
The Stack Exchange Blog is the company blog which talks about everything we're doing on all our sites and what the company itself is
doing.
| {
"pile_set_name": "StackExchange"
} |
Q:
Having troubles color coding items in a listbox/listview/multiline textbox
I have an application that works similar to a chat, except beside the location where they submit their message they also have a dropdown that selects the type of message it is.
When someone sends a message the message appears in a listbox (can also be a listview or a multiline textbox if that would work easier for what I want to do). What I need to happen is that the message they submit needs to be color coded based on what message type they chose in the dropdown.
Does anyone know how to make list items be different colors?
Thanks,
Matt
A:
If you don't want to draw the items yourself then use a ListView.
You'll need to set it into either a List or Details mode (in Details mode you'll need to add a column). Then you can add items to the list and set the background or foreground colors. See ListViewItem
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.