text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
How can I redirect after POST in Pyramid?
I'm trying to have my form submit to a route which will validate the data then redirect back to the original route.
For example:
User loads the page website.com/post
Form POSTs the data to website.com/post-save
User gets redirected back to website.com/post
Pyramid is giving me some troubles doing this.
Here's my slimmed down views.py
def _get_link_form(post_data):
""" Returns the initialised form object """
return LinkForm(post_data)
def home_page(request):
form = _get_link_form(request.POST)
return {'form' : form}
def save_post(request):
""" form data is submitted here """"
form = _get_link_form(request.POST)
if not form.validate():
return home_page(request, form)
This is the code I've been playing around with. Not only does it not work, it also feels messy and hacked up. Surely there's a simpler way to 'redirect after-POST' in Pyramid?
A:
Your problem is most easily solved by simply POSTing to the same URL that your form is shown at, and simply redirecting the user away from the page when the POST is successful. That way until the form is successfully submitted you do not change URLs.
If you're just dying to POST to a different URL, then you need to save the data using sessions, since you're obviously handling the form data between requests.
Typically if you want to be able to handle errors in your forms you would use a session and flash messages. To do this you simply add a location for flash messages to appear in your base template and setup session support using something like pyramid_beaker.
Assuming your home page is setup at the 'home' named-route:
from pyramid.httpexceptions import HTTPFound
def myview(request):
user = '<default user field value>'
if 'submit' in request.POST:
user = request.POST.get('user')
# validate your form data
if <form validates successfully>:
request.session.flash('Form was submitted successfully.')
url = request.route_url('home')
return HTTPFound(location=url)
return {
# globals for rendering your form
'user': user,
}
Notice how if the form fails to validate you use the same code you did to render the form originally, and only if it is successful do you redirect. This format can also handle populating the form with the values used in the submission, and default values.
You can loop through the flash messages in your template of choice using request.session.peek_flash() and request.session.pop_flash().
route_url supports mutating the query string on the generated url as well, if you want to flag your home page view to check the session data.
You can obviously just pass everything in the query string back to the home page, but that's a pretty big security vulnerability that sessions can help protect against.
A:
The Pyramid documentation has a particularly on-point section with the following example:
from pyramid.httpexceptions import HTTPFound
def myview(request):
return HTTPFound(location='http://example.com')
| {
"pile_set_name": "StackExchange"
} |
Q:
Can somebody update the search section of the FAQ?
Under the Stackoverflow FAQ the section entitled "Are there any search options?" could use an update. I have to search on how to search on stackoverflow because the search options are hidden so well. The natural place for this kind of thing is in the FAQ. Basically it just needs to have a summary of https://stackoverflow.com/search. Also, a link to the above linked search page on the home page would be nice. Here is my suggestion:
Are there any search options?
Indeed there are. To search, type in the box at the top right of every page
and press Enter. For example, 'apples oranges' will return any questions or
answers containing "apples" or "oranges". If that's not specific enough,
you can narrow your search even further. You can narrow your search to specific
tags like this: '[tag] apples oranges' or this: '[tag] [another-tag] apples
oranges' or to a phrase like this: '"apples oranges"' or to ensure that the
words appear in the results '+apples +oranges'. Advanced Super Ninja Search
Options are available at https://stackoverflow.com/search. … but you must
first snatch this pebble from my hand, grasshopper.
I am not sure what that last part means but it must be important to somebody or it wouldn't be there.
A:
The FAQ now links to the advanced search options at the bottom.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP-Warning: array_map(): Argument #2 should be an array
I have this Code for fetch data from MySql database:
$sql = 'SELECT id,title,seotitle FROM ' . PROPERTIES_TABLE . ' WHERE featured = "A" AND approved = 1 AND id = "' . safe($_GET['id']) . '" LIMIT 1';
$r = $db->query ( $sql ) or error ('Critical Error' , mysql_error());
$f = $db->fetcharray( $r );
// Make all values in the array 'n/a' if empty
$f = array_map ( 'if_empty', $f);
if_empty is:
function if_empty ( $value )
{
if ($value == '' || $value == '0')
return '';
else
return $value;
}
Now, I see this error:
Warning: array_map(): Argument #2 should be an array in C:\xampp\htdocs\cms\qrcode.php on line 26
how can i fix this ?
A:
Try:
if ($f) {
$f = array_map ( 'if_empty', $f);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set Angular Material Fields to width:100%?
How should I set form fields to max width with a screen size under 840px?
I'm using: Angular, Angular Materials & Flex-Layout.
Specifically, why doesn't this work & what should I use instead?
Styles.css:
@media (max-width: 840px) {
md-form-field{
width: 100%;
}
}
A:
Probably you set rules in wrong css file, like in styles.css. If need to set styles there, turn off ViewEncapsulation:
import { ViewEncapsulation } from '@angular/core';
@Component({
encapsulation: ViewEncapsulation.None,
})
| {
"pile_set_name": "StackExchange"
} |
Q:
Mutliple threads accessing synchronised and unsynchronised methods on same object
Suppose there is a class Test which has one synchronized method m1, and one non synchronized method m2, and an instance of Test, say obj.Two threads T1 and T2, try to access methods related to instance obj.
What happens when T1 invokes obj.m1(synchronized method), and before it completes m1 execution, T2 invoked obj.m2(non-synchronized).
Will T2 have to wait?
I was asked this question in an interview.
My Answer: T2 will continue to execute without any wait. T2 is accessing non-synchronized method, hence it does not need any lock.
The interviewer did not seem to agree with my answer, though when I asked him back about the correctness of my answer, he did not provide any input.
Please help me understand if I am missing something.
P.S. I have tried a test program already, and I see that my understanding is right. I am just wondering if there is any special scenario where this would not work as I explained to the interviewer.
A:
Well, You answer sure was correct, but i guess the small reply didn't made the interviewer happy or maybe he had higher expectations and wanted a very clear explanation for his question.
I wont be writing any code to answer your question, but i will state two points highlighting the basics of multi-threading in java.
1) Each object has only one lock.
2) If two threads say T1 and T2 are trying to execute synchronized instance methods on the same object, then the thread which obtains the lock first will be able to execute the synchronized method and the other thread T2 will have to wait until T1 completes its execution or enters into blocking/waiting state for some handful number of reasons. In other words, No Thread T2 can not enter ANY (I repeat ANY) synchronized method for an object "obj" if Thread T1 already has a lock for the same object obj.
3) If a Class has both synchronized and non-synchronized methods, then any number of Threads can access the non-synchronized methods in any way they wish without having to wait for someone or something.
The Bottom line here is, Thread T2 doesn't need to wait for Thread T1 to complete its execution as it is trying to execute a non synchronized method. Hope This answer meets your expectations.
I see You have edited your question
P.S. I have tried a test program already, and I see that my understanding is right. I am just wondering if there is any special scenario where this would not work as I explained to the interviewer.
There is no such scenario. The above points should meet your question.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to disable textbox and assign default value on it?
this is my textbox with id of brgy_name:
<select name="brgy_name" class="" style="width:240px" id="brgy_name" required >
<option value="">Select Barangay</option>
<option value="ALL">ALL</option>
<?php $result = pg_query("SELECT * FROM tbl_barangay order by cbrgyname");
while($row = pg_fetch_array($result)){ ?>
<option value="<?php echo $row['cbrgyname']; ?>"><font style="margin-top:-20px"><?php echo $row['cbrgyname'];?></font></option>
<?php } ?>
</select>
<input type="hidden" id="asgn_brgy" value="<?php echo $_POST['brgy_name']; ?>">
<input type="hidden" id="frm" value="<?php echo $_POST['fromyear']; ?>">
<input type="hidden" id="to" value="<?php echo $_POST['toyear']; ?>">
<input type="hidden" id="usertype" value="<?php echo $_SESSION['admin_usertype'] ?>"> <!--ADMIN-->
<input type="hidden" id="userbrgy" value="<?php echo $_SESSION['admin_brgycode'] ?>"> <!--TAGUIBO-->
This is my script:
<script text="text/javascript">
var holderu = document.getElementById('usertype').value;
var holderb = document.getElementById('userbrgy').value;
if(holderu=='ADMIN'){
}else{
}
</script>
if holderu == 'ADMIN' is true.. i want the value of holderb to be put into the textbox..
A:
i hope this will help..
<script text="text/javascript">
var holderu = document.getElementById('usertype').value;
var holderb = document.getElementById('userbrgy').value;
if(holderu=='ADMIN'){
$("#brgy_name").empty();
var select = '<option>'+holderb+'</option>';
$("#brgy_name").append(select);
$("#brgy_name").prop('disabled',true);
}else{
//your code
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Shorten a string in JTabel when cell is too small
When a cell is too small to display the whole string, it shortens the end by adding '...'. For instance: "This is a string" becomes "This is..."
Is there a way to shorten it at the beginning? "...a string".
Thx!
A:
JTable by default uses a JLabel as its rendering component, so basically you need to tell that label how to shorten your string. You can do that by implementing a custom TableCellRenderer. Perhaps you can use the Left Dot Renderer as a starting point and extend it, if it does not exactly suits your needs.
| {
"pile_set_name": "StackExchange"
} |
Q:
node js script to act upon a constellation response
H Apologies,
This is going to be an incredibly beginner question - I have been trying to figure this out on my own this afternoon. I am only beginning coding in js for the first time today.
I am trying to create a script that will monitor Mixer's constellation server, receive a response when a stream goes live. (I have this bit working fine and when the streamer goes online it send a true message, when the streamer goes offline i get false).
const Carina = require('carina').Carina;
const ws = require('ws');
Carina.WebSocket = ws;
const channelId = xxxxxx;
const ca = new Carina({ isBot: true }).open();
ca.subscribe(`channel:${channelId}:update`, data => {
console.log(data.online);
});
I then would like it to trigger a POST query to using the maker script part of IFTTT to trigger an event there (such as flash my lights when my favourite streamer goes online) - I also have this script working fine!
var request = require("request");
request({
uri:
"https://maker.ifttt.com/trigger/streaming/with/key/xxxxxxxxxxxxxxxxxx",
method: "POST",
}, function(error, response, body) {
console.log(body);
});
Problem I have, is I have zero knowledge of js, as to have to merge the 2 together, so that when I receive a 'true' response from the Mixer constellation server, it runs the second part of the script.
I hope that you go easy on my lack of knowledge and I look thank you for your assistance.
A:
i think you have to simply use a function in callback of another function like this:
const Carina = require('carina').Carina;
const ws = require('ws');
Carina.WebSocket = ws;
const channelId = xxxxxx;
const ca = new Carina({ isBot: true }).open();
var request = require("request");
ca.subscribe(`channel:${channelId}:update`, data => {
if(data.online){
request({
uri:
"https://maker.ifttt.com/trigger/streaming/with/key/xxxxxxxxxxxxxxxxxx",
method: "POST",
}, function(error, response, body) {
console.log(body);
});
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Arrange ggsurv plots with one shared legend
I am trying to plot several Kaplan Meijer curves in a grid with a shared legend in R. Here (common legend in arrange_ggsurvplots) ggsurvplot_facet is advised. However, in my case, every plot is based on a different fit using different variables, so ggsurvplot_facet is (at least in my understanding) not applicable here. Please see my data and script below. Is there a way to have these plots arranged while sharing one legend? I've tried working with ggarrange and grid_arrange_shared_legend, but I couldn't get it to work with ggsurvplot objects.
library(survival)
library(survminer)
data_km <- data.frame(DaysToFirstDetectByBird = c(16.88, 50.17, 1.14, 22.46, 9.95, 4.64, 1.08, 7.06, 1.86, 0.00, 1.11, 2.87, 3.63, 29.15, 0.31, 13.89, 2.16, 2.24, 5.93, 0.12, 0.92, 0.06, 0.08, 0.32, 1.23, 19.06, 8.09, 0.17, 16.04, 4.86, 4.11, 2.94, 0.06, 5.69, 4.87),
FirstDetectByBirdEvent = c(1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1),
DaysToFirstDetectByMammal = c(1.63, 6.47, 1.44, 1.62, 1.22, 1.13, 2.22, 3.43, 10.66, 2.37, 20.83, 0.64, 1.09, 1.46, 0.49, 0.72, 0.90, 0.59, 6.05, 10.43, 3.04, 0.68, 0.53, 27.47, 0.93, 2.57, 0.46, 0.68, 2.61, 5.32, 0.69, 0.22, 0.42, 0.51, 0.50),
FirstDetectByMammalEvent = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
OcGroup = c("Open", "Open", "Open", "Open", "Open", "Open", "Open", "Open", "Open", "Open", "Open", "Open", "Open", "Open", "Open", "Open", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest", "Forest"))
# plotA
SurvFit_DetectionBird <- survfit(Surv(DaysToFirstDetectByBird, FirstDetectByBirdEvent) ~ OcGroup, data = data_km)
plot_DetectionBird <- ggsurvplot(SurvFit_DetectionBird)
plot_DetectionBird$plot <- plot_DetectionBird$plot + labs(title = "A")
# plotB
SurvFit_DetectionMammal <- survfit(Surv(DaysToFirstDetectByMammal, FirstDetectByMammalEvent) ~ OcGroup, data = data_km)
plot_DetectionMammal <- ggsurvplot(SurvFit_DetectionMammal)
plot_DetectionMammal$plot <- plot_DetectionMammal$plot + labs(title = "B")
# arrange plots
plots <- list(plot_DetectionBird, plot_DetectionMammal)
res <- arrange_ggsurvplots(plots, print = FALSE,
ncol = 1, nrow = 2)
ggsave("~/Desktop/survplots_test.pdf", res)
A:
You can use patchwork package, but first you need to extract the ggplot object from the "ggsurvplot" object
library(patchwork)
(plot_DetectionBird$plot + plot_DetectionMammal$plot) / guide_area() +
plot_layout( guides = 'collect')
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP count from database WHERE
I am trying to show a count of all applications stored in a database with the status of 1.
Here is my UPDATED code:
$result=mysql_query("SELECT * FROM member ")or die('You need to add an administrator ' );
$counter = mysql_query("SELECT COUNT(*) as personID FROM member where state='1' ");
$row = mysql_fetch_array($result);
$personID = $row['personID'];
$num = mysql_fetch_array($counter);
$countadmin = $num["personID"];
However this isn't showing anything when I echo `$countadmin'
Can anyone help
A:
You may try this
$query = mysql_query("select count(*) from member where state='1'");
if ($query) {
$count = mysql_result($query, 0, 0);
echo $count;
}
Check mysql_result and also notice the Warning at top. Also make sure that, the field is state not status, it's confusing, you mentioned status in your question but used state in the query.
Also, following line is not required to get the count of your second query
$result=mysql_query("SELECT * FROM member ")or die('You need to add an administrator ' );
Also, make sure that, you have connected to a database and selected it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Relationships and constraints across databases
HI There,
what are the possible ways in which i can maintain relationships across instances of databases . i know relationships across DB's is bad approach , but i have to do this way.
i am using SQL SERVER 2005.
Thanks
DEE
A:
As far as I know it is impossible to do.
Your options are:
Set up replication between the datases so that the tables you want to define a relationship with are available in your local database. But that could get messy.
Create a UDF that does the checking and use that as a contraint.
Triggers.
However, this is such a bad idea that you really should re-evaluate whatever reasoning drove you to create multiple databases in the first place.
| {
"pile_set_name": "StackExchange"
} |
Q:
Clarification about this proof about Dilworth's Theorem
Theorem 6.1. Let P be a partially ordered finite set. The minimum
number m of disjoint chains which together contain all elements
of P is equal to the maximum number M of elements in an
antichain of P.
Proof: (i) It is trivial that m ≥ M.
(ii) We use induction on |P|. If |P| = 0, there is nothing to
prove. Let C be a maximal chain in P. If every antichain in P\C
contains at most M − 1 elements, we are done. So assume that
{a1, . . . , aM} is an antichain in P\C. Now define S− := {x ∈ P :
∃i[x ≤ ai]}, and define S+ analogously. Since C is a maximal chain,
the largest element in C is not in S− and hence by the induction
hypothesis, the theorem holds for S−. Hence S− is the union of M
disjoint chains S
−
1 , . . . , S
−
M, where ai ∈ S
−
i . Suppose x ∈ S
−
i and
x > ai. Since there is aj with x ≤ aj , we would have ai < aj ,
a contradiction. This shows that ai is the maximal element of the
chain S
−
i , i = 1, . . . , m. We do the same for S+. By combining the
chains the theorem follows.
Could someone explain the proof in a simpler manner and
what is exactly meant by the term maximal chain in P ?
A:
A maximal chain is one that cannot be extended any more. That means any other element you add to a maximal chain will never result in a longer chain.
The above proof is by induction on the size of the poset $P$. The idea is to remove a maximal chain $C$ from $P$ to have a smaller poset. Then use the induction hypothesis.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does a closure REALLY refer to?
I know how to use "closures"... but what does the word closure actually refer to?
On MDN the definition is that it is a function. Here is the page about closures. The first sentence is, "Closures are functions that refer to independent (free) variables." and in the first code example there is a comment highlighting the closure function. However, the second sentence seems to suggest that the closure is really the persistent scope that the inner function resides in. That's what this other stack overflow answer suggest, too (search word "persistent").
So, what is it? The function or the persistent scope?
A:
Technically, a closure is the mechanism behind how persistent scope works in functions - in other words, it's the implementation. That's what it originally meant in terms of Lisp. And in some cases that's still what it means - just look at the explanations of what closures are in various Lisp dialects and they almost all try to explain it in terms of how the compiler/interpreter implements closures. Because that was how people used to explain scope.
The first time I came across a much simpler explanation of closures (that is, explaining the behavior instead of the mechanics) was in javascript. Now that more people are used to the idea of closures, the word itself has grown to mean:
the captured scope of an inner function allowing the function to refer to the variables of the outer function (this is the closest to the original meaning)
the inner function itself (typically in languages that call first-class functions or lambdas "closure")
the free variable captured by the closure
I personally prefer the last meaning because it captures the essence of what closures are: a form of variable sharing, kind of like globals. However, if you want to be pedantic, only the first meaning is actually the technical meaning: "closure" refers to the captured scope.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why JavaScript onClick doesn't trigger jQuery submit function?
I am submitting a form like this:
<input id="submitBtn" style="margin-top:20px;" type="button" onclick="document.getElementById('form94').submit();" value="Opdater">
That for some reason doesn't trigger my jQuery .submit() function.
$("#form94").submit(function() {
var form = $(this);
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(), // data to be submitted
success: function(response){
$("#showFancyBoxThankYouLink").click();
}
});
return false;
});
A:
Because you use different selectors
document.getElementById('form94'); //returns a HTML DOM Object
$('#form94'); //returns a jQuery Object
You can try next code, it works fine
<form id="form94">
<input id="submitBtn" style="margin-top:20px;" type="button" onclick="$('#form94').submit();" value="Opdater">
</form>
<script type="text/javascript">
$("#form94").submit(function(e) {
e.preventDefault();
alert('test');
});
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the questions one should ask of oneself in trying to understand definitions and lemmas?
Definition (Finite series). Let $m,n$ be integers, and let $(a_i)_{i=m}^{n}$ be a finite sequence of real numbers, assigning a real nmber $a_i$ to each integer $i$ between $m$ and $n$ inclusive. Then we define the finite sum $\sum_{i=m}^{n} a_i$ by the recursive formula $\sum_{i=m}^{n} a_i = 0 $ whenever $n < m$ and $\sum_{i=m}^{n+1} a_i = \sum_{i=m}^{n} a_i + a_{n+1}$ whenever $ n \geq m-1$ .
Lemma Let $m \leq n < p$ be integers, and let $a_i$ be a real number assigned to each integer $m \leq i \leq p$. Then we have $\sum_{i=m}^{n} a_i + \sum_{i=n+1}^{p} a_i =\sum_{i=m}^{p} a_i$.
MY QUESTIONS
What are the typical questions one would ask of himself in trying to understand such a typical sequence of definition and lemma?
Why did the author write $m \leq i \leq p$ and not $(n+1) \leq i \leq p$? Is the author trying to generalize $i$? If yes what is the benefit of this generalization?
A:
Questions to ask yourself: "Can I create a concrete example myself? Why are the hypothesis sufficient? Are they necessary? Can I find a counter-example if I change them?"
The index of summation ($i$) must be between the bounds of summation ($m$ and $p$). The integer $n$ is just where the summation is being split, so it will be an upper-bound for $i$ in the first summation, and a lower-bound for $i$ in the second summation.
A:
Mathematics, in contrast to the wasy it is presented in many textbooks, is not a collection of sacred rules of conduct, nor a sacred dictionary of meaning-of-words, but a certain form of an account of what mathematics is about, and what mathematicians do.
It is true that there has been "optimization" of these accounts over the last 200 years, ... but that in itself is a problem, in some cases! That is, the back-story is tricky enough so that without knowing it (which would be daunting already) the "calm" sequel is incomprehensible.
And then there's the stylistic conceit about definitions/lemmas/proofs. This can easily degenerate into a sort of acolyte-seeking-to-propitiate-whimsical-gods scenario.
While we're here, although "the Moore method" has its fans, I am not among them. In fact, I would claim that the implicit hypothesis in this is that mathematics is (conceptually) "shallow", in the specific technical sense (not necessarily insulting, though it sounds like it!) that not much prior experience or prior knowledge (the big two "priors") are relevant. (Another discussion: necessity versus relevance.)
The most-most-immediate answer to such questions, I'd claim, is to ask what "real question" this "stylized/formal" question is hiding.
Usually, the answer is that there's no real issue. More like whether you're sitting down... much less having fastened the seat-belt... before driving.
It is certainly true that other philosophical approaches to mathematics dictate or suggest other views, but, I'd recommend not thinking in terms of those things, but in terms of the "what are we trying to do?" criterion. I know, yes, these are not the usual things in "school", ...
| {
"pile_set_name": "StackExchange"
} |
Q:
JuMP querying solution doesn't work in for loop
I'm using JuMP v0.20.0 with the Ipopt optimizer, and I'm trying to solve a system of nonlinear equations in a loop, where the problem statement varies based on what I'm looping over.
Suppose I have this really simple problem of trying to pick $$t_1,\dots, t_n$$ to minimize the non-linear equation $$\sum_{i=1 to N} t_i^2$$. When I run this without looping, I have the following code
using JuMP, Optim, Ipopt, NLsolve
m = Model(Ipopt.Optimizer)
@variable(m, t[1:N] >= 0.00000001)
function solve_Aik(tlist...)
t = collect(tlist)
return sum([t[i]^2 for i in 1:N])
end
register(m, :solve_Aik, N, solve_Aik, autodiff=true)
@NLobjective(m, Min, solve_Aik(t...))
optimize!(m)
solution = [value.(t[i]) for i=1:N]
the last line of which provides me my solution just fine.
However, as soon as I put this in a loop (without even providing the number I'm looping over to the problem), I can no longer recover my solution, with an error of "MethodError: no method matching value(::ForwardDiff.Dual{ForwardDiff.Tag{JuMP.var"#107#109"{var"#solve_Aik#378"},Float64},Float64,8})". See the code below:
nums = [1,2,3]
for num in nums
m = Model(Ipopt.Optimizer)
@variable(m, t[1:N] >= 0.00000001)
function solve_Aik(tlist...)
t = collect(tlist)
return sum([t[i]^2 for i in 1:N])
end
register(m, :solve_Aik, N, solve_Aik, autodiff=true)
@NLobjective(m, Min, solve_Aik(t...))
optimize!(m)
solution = [value.(t[i]) for i=1:N]
end
The last line providing the solution is what Julia gets hung up on. Has anyone else encountered a similar issue? TIA!
A:
My guess based on the error message is that by some quirk of Julia's scoping rules, t = collect(tlist) overwrites the JuMP variable t defined in the body of the for loop. Try using a different name for the variable inside solve_Aik.
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing the Increment Value in Data Frame at Certain Row
I have this data frame:
Power
15
15
10
30
15
90
100
22
15
I wanted to create another column called 'Seconds' that increments by 10 every row so I wrote this code:
df.index += 1
df['Seconds'] = 10 * df.index.values
This produces the data frame:
Seconds Power
10 15
20 15
30 10
40 30
50 15
60 90
70 100
80 22
90 15
I now want to make the Seconds column increment by 10 until the 5th row. At the 5th row, I want to change the increment to 0.1 until the 7th row. At the 7th row, I want to change the increment back to 10.
So, I want the data frame to look like this:
Seconds Power
10 15
20 15
30 10
40 30
50 15
50.1 90
50.2 100
60.2 22
70.2 15
How would I go about doing this? Should I change the index and multiply the index.values by a different value when I get to the row where the increment needs to change?
Thanks in advance for your help.
A:
You can use numpy.repeat + cumsum
np.repeat([10, 0.1, 10], [5, 2, 2]).cumsum()
# ^ ^ ^
# 5th ^ ^
# 7th ^
# Until end -> df.shape - increments[:-1].sum() more generally
array([10. , 20. , 30. , 40. , 50. , 50.1, 50.2, 60.2, 70.2])
In a more general sense, it is probably more intuitive to not have to calculate out the repeats by hand, and it would be easier to define them not by their difference with the previous value, but by absolute location in the array.
Using some arithmetic, we can create a function that does all of the grunt-work for you.
def cumsum_custom_increment(increments, points, n):
points[1:] = np.diff(points)
d = np.r_[points, n - np.sum(points)]
return np.repeat(increments, d).cumsum()
>>> cumsum_custom_increment([10, 0.1, 10], [5, 7], df.shape[0])
array([10. , 20. , 30. , 40. , 50. , 50.1, 50.2, 60.2, 70.2])
| {
"pile_set_name": "StackExchange"
} |
Q:
Get usage status from AWS API key
I have an AWS serverless API configured with a usage plan. I want users to be able to know how many more requests they can make, so they are don't get stuck with:
HTTP/2 429
content-type: application/json
content-length: 28
date: Mon, 16 Apr 2018 03:41:12 GMT
x-amzn-requestid: 02436b06-4128-11e8-aa37-8f617035a300
x-amzn-errortype: LimitExceededException
x-cache: Error from cloudfront
via: 1.1 de2aa82ec56d0a6d749df4bf0a88b28f.cloudfront.net (CloudFront)
x-amz-cf-id: afyULHDbLwJYAJO07zLeFG1Q0tZA-VhB3kezRgE1UBldQdfaGRQaZQ==
{"message":"Limit Exceeded"}
I've been looking over AWS documentation https://docs.aws.amazon.com/cli/latest/reference/apigateway/index.html#cli-aws-apigateway & https://docs.aws.amazon.com/sdk-for-go/api/service/apigateway/
And I can't seem to figure out how to tell how many requests an API key is allowed to make! My goal is to see present user's something like Twitter's:
x-rate-limit-limit: 1500
x-rate-limit-remaining: 1499
x-rate-limit-reset: 1523850782
What am I missing ?
A:
You can get the usage data of a usage plan in a specified time interval for an "optional" specific API key via usage:get:
GET /usageplans/<usageplanId>/usage{?keyId,startDate,endDate,limit}
The returned usage data represents daily logs of used and remaining quotas, over the specified time interval indexed over the API keys in the usage plan.
(Similar implementations are available in AWS SDKs)
Source: Amazon API Gateway REST API Reference.
| {
"pile_set_name": "StackExchange"
} |
Q:
Best practice for modal window in Web Forms application
On a list page, clicking on one of the items brings up the details in a modal popup window which will have its own functionality (like validation, updating etc). What's the best practice to implement this (not looking for a hack). I see two options here:
Hide the details markup until a list item is clicked at which time, do a ajax request to get the details and populate and show the details section.
Have the details section as a separate page by itself. On a list item click, show this page in a modal window (is this even possible?) This is similar to the IFrame approach and sounds like an old school approach.
What are the pros of cons of these approaches or are there other ways of doing this? There should not be a postback on list item click.
Edit: Any more opinions are appreciated.
A:
I'm doing option 1 currently, it's very lightweight and all you need is an ajax post (jQuery or UpdatePanel) and some modal (I'm using jQery UI). It's easier than a full page post, plus you have the added benefit of being able to manipulate the page you're in as part of the result.
For example I have grids in the page, the editor is modal, usually with more detail, when you hit save, the grid is updated. I've put this in a generic template solution and it's very easy to work with, and is as light as webforms can be in that situation, so I'm all in favor of option 1.
Here's an example approach, having your modal control inherit from UpdatePanel (code condensed for brevity):
public class Modal : UpdatePanel
{
private bool? _show;
public string Title
{
get { return ViewState.Get("Title", string.Empty); }
set { ViewState.Set("Title", value); }
}
public string SaveButtonText
{
get { return ViewState.Get("SaveButtonText", "Save"); }
set { ViewState.Set("SaveButtonText", value); }
}
protected override void OnPreRender(EventArgs e)
{
if (_show.HasValue) RegScript(_show.Value);
base.OnPreRender(e);
}
public new Modal Update() { base.Update();return this;}
public Modal Show() { _show = true; return this; }
public Modal Hide() { _show = false; return this; }
private void RegScript(bool show)
{
const string scriptShow = "$(function() {{ modal('{0}','{1}','{2}'); }});";
ScriptManager.RegisterStartupScript(this, typeof (Modal),
ClientID + (show ? "s" : "h"),
string.Format(scriptShow, ClientID, Title, SaveButtonText), true);
}
}
In javascript:
function modal(id, mTitle, saveText) {
var btns = {};
btns[saveText || "Save"] = function() {
$(this).find("input[id$=MySaveButton]").click();
};
btns.Close = function() {
$(this).dialog("close");
};
return $("#" + id).dialog('destroy').dialog({
title: mTitle,
modal: true,
width: (width || '650') + 'px',
resizable: false,
buttons: btns
}).parent().appendTo($("form:first"));
}
Then in your markup (Can't think of a better name than MyControls right now, sorry!):
<MyControls:Modal ID="MyPanel" runat="server" UpdateMode="Conditional" Title="Details">
//Any Controls here, ListView, whatever
<asp:Button ID="MySaveButton" runat="server" OnClick="DoSomething" />
</MyControls:Modal>
In you pages codebehind you can do:
MyPanel.Update().Show();
Fr your approach, I'd have a jQuery action that sets an input field and clicks a button in the modal, triggering the update panel to postback, and in that code that loads the details into whatever control is in the modal, just call MyPanel.Update.Show(); and it'll be on the screen when the update panel ajax request comes back.
The example above, using jQuery UI will have 2 buttons on the modal, one to close and do nothing, one to save, clicking that MySaveButton inside the modal, and you can do whatever you want on then server, calling MyPanel.Hide() if successful, or put an error message in the panel if validation fails, just don't call MyModal.Hide() and it'll stay up for the user after the postback.
| {
"pile_set_name": "StackExchange"
} |
Q:
Become first responder app delegate not working
My situation goes as follows: I have an app which has a PIN screen implemented. Its nothing high-tech just basic 4 UITextFields and implemented logic via UITextFieldDelegate - it works.
I'm showing this screen in app delegate on -(void)applicationWillEnterForeground:(UIApplication *)application event. I am using MMDrawerController from github (link: https://github.com/mutualmobile/MMDrawerController) as the main view controller. If the current view presented when the application enters background and foreground again is this MMDrawerController then the becomeFirstResponder is not working - it doesn't show the keyboard. If there is another view controller presented on top of drawer controller the when entering foreground (let's say settings view) then keyboard appears normally.
I have tried NSLoging the canBecomeFirstResponder property and its set to YES. What is going on? How to fix this?
I can paste code if needed but its nothing ambiguous. Just plain call becomeFirstResponder.
EDIT:
To explain things a bit more clearly. rootViewController is a view controller caleed LoginViewController and it alloc-inits the sidebar and the center view controllers, alloc-inits the drawer controller and hooks everything up so it works. The app delegate view is actually a PIN screen which pops up when the app enters foreground. Now the keyboard appears like it should for the first time the drawer is visible.
When the user pops up SettingsViewController (yes, this is another view controller accessible from the sidebar view controller) it works as well. But when the user dismisses the settings view controller keyboard doesn't appear anymore. It has to do something with the drawer cause I tried without it and it worked (but I only had sidebar or center view controller visible).
A:
Ideally you would want to access the textField within the MMDrawerControllers currentView. I have achieved something similar with this implementation:
In your app delegate store a reference to the DrawerController like so:
In AppDels interface:
@property(nonatomic, strong) MMDrawerController *appDrawController;
Then after you create the local drawer controller in didFinishLaunching (if you followed the setup instructions for this library):
self.appDrawController = drawerController;
In your applicationWillEnterForeground:
THECLASSTHATCONTAINSTHEPINVIEW *yourClass = self.appDrawController.centerViewController.childViewControllers[0];
Now you can access the public methods/properties, so:
[[yourClass pinEntryField] becomeFirstResponder];
Does this help at all ?
| {
"pile_set_name": "StackExchange"
} |
Q:
Vector Space confusion
For each of the following, I need to decide if it is a vector space over $\mathbb{R}$. (You may assume that the set of all real valued functions on the interval $[-1, 1]$ is a vector space with the operations $(f+g)(x)=f(x)+g(x)$ and $(\lambda f)(x)=\lambda f(x).$
A=$\{f:[-1,1] \to \mathbb{R}:$ f is an even function $\}$
B= $\{f:[-1,1] \to \mathbb{R}:$ f is differentiable and $f(0)+f'(0)=1 $}
C=$\{f:[-1,1] \to \mathbb{R}: f(0) + \int_{-1}^1sin(x)f(x)dx=0$ $\}$
My question is (forgive my lack of experience): Do I really need to prove all axioms of a vector space hold? Or only show that closure properties hold? I'm clueless as to how to prove these are vector spaces. If anyone can help me with at least one of them, I can try the rest. Thank you.
A:
Linearity isn't sufficient in general to prove the sets are vector spaces, but it is necessary. Since you are given the parent set is a vector space, you simply have to check closure under addition, closure under scalar multiplication, and containment of the zero-vector. This is called the subspace test. I would try and find where things break and go from there.
For a vector space, we have closure over addition. So let's look at $B$. What happens if $f(0) = 1$ and $f^{\prime}(0) = 0$. Now take $g(0) = 0$ and $g^{\prime}(0) = 1$. Clearly, $f, g \in B$. So if $B$ is a vector space, then $f + g \in B$. However, $(f + g)(0) = 2$. So closure under addition fails.
For $A$, let's look at addition. An even function is a function such that $f(x) = f(-x)$. So if I take two even functions and add them, will the result be even? Are the functions commutative over addition? What about associative? You may find properties of addition over $\mathbb{R}$ to be helpful here. By this, I mean that since the functions map to values in $\mathbb{R}$, it suffices to consider commutativity, associativity, and distributivity over $\mathbb{R}$.
Now is there an identity in $A$? Is there a function such that for all $f \in A$, there exists a $g \in A$ such that $f + g = f$? Again, think about the additive identity on $\mathbb{R}$.
Hopefully this will help you get started. I've included more steps than necessary, but I did so in the hopes of clarifying general vector space proofs as well, rather than restricting to the case of subspaces (which you should do here). Please let me know if I can clarify some.
| {
"pile_set_name": "StackExchange"
} |
Q:
Missing DLLs cross-compile wxWidgets shared library on ubuntu
I try to cross-compile under Linux to Windows using the shared library.
I followed the instructions on wxWidgets wiki but while executing main out.exe I got a lot of missing DLL Errors.
Here's how I builded the library :
../configure --disable-debug_flag --host=x86_64-w64-mingw32 --build=x86_64-linux-gnu -with-msw
Here's how I compile and Link :
First : x86_64-w64-mingw32-g++ -c *.cpp *.h $(/wxWidgets/build_win/wx-config --cxxflags)
Second : x86_64-w64-mingw32-g++ -o out.exe *.o $(/wxWidgets/build_win/wx-config --libs) -static-libgcc -static-libstdc++
When I use wine out.exe I got these errors :
002a:err:module:import_dll Library wxbase313u_gcc_custom.dll (which is needed by L"Z:\\home\\ubuntu\\test.exe") not found
002a:err:module:import_dll Library wxmsw313u_core_gcc_custom.dll (which is needed by L"Z:\\home\\ubuntu\\test.exe") not found
002a:err:module:attach_dlls Importing dlls for L"Z:\\home\\ubuntu\\test.exe" failed, status c0000135
I've added the missing DLLs in the same folder as out.exe (They were located in /wxWidgets/build_win/lib/ ) and doing this added lot of more errors :
wine out.exe
0028:err:module:import_dll Library libgcc_s_seh-1.dll (which is needed by L"Z:\\home\\ubuntu\\Bureau\\test\\wxbase313u_gcc_custom.dll") not found
0028:err:module:import_dll Library libstdc++-6.dll (which is needed by L"Z:\\home\\ubuntu\\Bureau\\test\\wxbase313u_gcc_custom.dll") not found
0028:err:module:import_dll Library wxbase313u_gcc_custom.dll (which is needed by L"Z:\\home\\ubuntu\\Bureau\\test\\out.exe") not found
0028:err:module:import_dll Library libgcc_s_seh-1.dll (which is needed by L"Z:\\home\\ubuntu\\Bureau\\test\\wxbase313u_gcc_custom.dll") not found
0028:err:module:import_dll Library libstdc++-6.dll (which is needed by L"Z:\\home\\ubuntu\\Bureau\\test\\wxbase313u_gcc_custom.dll") not found
0028:err:module:import_dll Library wxbase313u_gcc_custom.dll (which is needed by L"Z:\\home\\ubuntu\\Bureau\\test\\wxmsw313u_core_gcc_custom.dll") not found
0028:err:module:import_dll Library libgcc_s_seh-1.dll (which is needed by L"Z:\\home\\ubuntu\\Bureau\\test\\wxmsw313u_core_gcc_custom.dll") not found
0028:err:module:import_dll Library libstdc++-6.dll (which is needed by L"Z:\\home\\ubuntu\\Bureau\\test\\wxmsw313u_core_gcc_custom.dll") not found
0028:err:module:import_dll Library wxmsw313u_core_gcc_custom.dll (which is needed by L"Z:\\home\\ubuntu\\Bureau\\test\\out.exe") not found
0028:err:module:attach_dlls Importing dlls for L"Z:\\home\\ubuntu\\Bureau\\test\\out.exe" failed, status c0000135
Here's my folder content :
ChildPanels.o wxmsw313u_gl_gcc_custom.dll
main.o wxmsw313u_html_gcc_custom.dll
MainPanel.o wxmsw313u_media_gcc_custom.dll
out.exe wxmsw313u_propgrid_gcc_custom.dll
wxbase313u_gcc_custom.dll wxmsw313u_qa_gcc_custom.dll
wxbase313u_net_gcc_custom.dll wxmsw313u_ribbon_gcc_custom.dll
wxbase313u_xml_gcc_custom.dll wxmsw313u_richtext_gcc_custom.dll
wxmsw313u_adv_gcc_custom.dll wxmsw313u_stc_gcc_custom.dll
wxmsw313u_aui_gcc_custom.dll wxmsw313u_webview_gcc_custom.dll
wxmsw313u_core_gcc_custom.dll wxmsw313u_xrc_gcc_custom.dll
Can anyone help me with this ?
EDIT :
It work copying all of these DLLs to my folder :
libgcc_s_seh-1.dll libstdc++-6.dll libwinpthread-1.dll wxmsw313u_core_gcc_custom.dll wxbase313u_gcc_custom.dll
I don't understand why I need to copy the libgcc and libstdc++ to my folder because I linked them staticly. Is it not possible to link static libgcc and libstdc++ and shared wxWidgets ?
Also, how can I tell the compiler I want my DLLs to be loaded from a folder named /lib for example inside my app folder ?
A:
This is not really wxWidgets-specific, but just the way that DLLs work: they need to be found during the program execution and this means either being in the same directory as the program itself, or in one of the directories in the PATH environment variable.
You can't "tell the compiler" anything about the path where the DLLs are found because this path must be used at run time, not compile time.
The simplest workaround if you really, really want to have the DLLs in another directory is to use a wrapper (it could be a script or another compiled program) that would add this directory to the PATH before launching the real application. Alternatively, just link statically and don't bother with the DLLs at all.
| {
"pile_set_name": "StackExchange"
} |
Q:
What prevents a cover to be Galois?
Let $f:X\rightarrow Y$ be a ramified cover of Riemann surfaces or algebraic curves over $\mathbb{C}$. My question is can one in terms of the ramification data of $f$, determine whether the cover is Galois or not. I am Specially interested in the following question: if $f:X\rightarrow Y$ and $g:Y\rightarrow Z$ are both ramified Galois covers of curves, when $g\circ f:X\rightarrow Z$ is (or isn't) a Galois cover?
A:
I assume that the surfaces are connected. Composition of two regular covering maps need not be regular even if the coverings are unbranched: A (usual) covering map is regular iff it is defined by a normal subgroup of the fundamental group. If you have a composition
$$
X \stackrel{f}{\to} Y \stackrel{g}{\to} Z
$$
of regular covers then $\pi_1(X)\triangleleft \pi_1(Y)$ and
$\pi_1(Y)\triangleleft \pi_1(Z)$. Hence, $\pi_1(X)$ is a subnormal subgroup of
$\pi_1(Z)$. Subnormal subgroups need not be normal. However, if, say,
$\pi_1(X)< \pi_1(Y)$ is a characteristic subgroup then it will be normal in $\pi_1(Z)$. This is the simplest condition I know to ensure that composition of regular covering maps is again regular. The same applies to ramified covers once you remove branch points and their preimages.
A:
The ramification data doesn't generally suffice to determine whether the cover is Galois. If $f:X\to Y$ and $g:Y\to Z$ are ramified Galois covers, then usually $g\circ f$ won't be Galois, for instance because there will usually be a point $z$ of $Z$ which has two preimages under $g\circ f$ having different ramification indices.
A:
There are many automorphisms of $Y$ over $Z$. One can pull back the cover $X$ along any of these automorphisms of $Y$, producing a new cover of $Y$. If the composition is Galois, then these new covers are in fact isomorphic to the original cover - this is because the map $Gal(X|Z) \to Gal(Y|Z)$ is surjective. Taking a lift of an element of $Gal(Y|Z)$ produces an isomorphism between the original cover and the pullback.
The converse is also true. If such an isomorphism exist, they give us enough elements of the automorphism group of $X$ over $Z$ that, combined with the automorphisms of $X$ over $Y$, the cover is Galois!
So this explains why the two preimages with different ramification data will prevent the cover from being Galois. Because then the pullback of the cover along an automorphism which permutes those two preimages will not be isomorphic to the original - it will have different ramification data.
| {
"pile_set_name": "StackExchange"
} |
Q:
jqGrid userData to show a value in View (asp.net mvc3)
I'm new to jqGrid. My task is now to show TotalDiabetes in View (asp.net MVC3) which has jqGrid, so I have chosen userData. My Controller code for jqGrid as follows,
extraPersons = ExtraPersonService.GetAllExtraPersons();
int TotalDiabetesCount = extraPersons.First().TotalDiabetes;
int pageIndex = gridSettings.pageIndex;
int pageSize = gridSettings.pageSize;
int totalRecords = extraPersons.Count;
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
int startRow = (pageIndex - 1) * pageSize;
int endRow = startRow + pageSize;
var jsonData = new
{
total = totalPages,
page = pageIndex,
records = totalRecords,
userdata = new { TotalDiabetesCount = "totalDiabetes" },
rows =
(
extraPersons.Select(e => new
{
Id = e.ExtraPersonId,
Name = e.FirstName + " " + e.LastName,
Diabetes = e.Diabetes ,
BP = e.BP,
Arrived = e.Arrived,
TreatmentApplied = e.TreatmentApplied,
})
).ToArray()
};
return Json(jsonData);
My JavaScript code for jqGrid as follows,
jQuery("#allextraperson").jqGrid({
url: '/ExtraPerson/GetAllExtraPersons/',
datatype: 'json',
mtype: 'POST',
colNames: gridInfoJSON.GridModel.ColumnDisplayArray,
colModel: [
{ name: 'Id', index: 'Id', hidden: true },
{ name: 'Name', index: 'Name', width: 200, formatter: generateNameLink },
{ name: 'Diabetes', index: 'Diabetes', width: 55, align: 'center', formatter: generateDiabetesLabel },
{ name: 'BP', index: 'BP', width: 50, align: 'center', formatter: generateBPLabel },
{ name: 'Arrived', index: 'Arrived', width: 70, align: 'center', formatter: generateArrivedLabel },
{ name: 'Delete', index: 'Delete', width: 75, align: 'center', formatter: deleteformatter }
],
jsonReader: {
id: 'Id',
repeatitems: false
},
height: "100%",
width: 970,
pager: '#allextraperson-pager',
rowNum: 10,
rowList: [10, 20, 30, 50],
sortname: 'Id',
sortorder: 'asc',
viewrecords: true,
loadComplete: function (data) {
var table = this;
setTimeout(function () {
updatePagerIcons(table);
}, 0);
var totaldiabetes = jQuery("#allextraperson").getGridParam('totalDiabetes');
alert("Total diabetes:" + totaldiabetes);
}
});
}
My View Code to show TotalDiabetes as follows
<span class="user_info muted" style="position: inherit;">Total Diabetes
:  <strong class="orange"> totalDiabetes </strong></span>
The alert shows Total diabetes:null
I don't know what I did wrong, please anyone suggest me a solution.
A:
Myself found what I did wrong, In the Controller code, I have replaced the line
userdata = new { TotalDiabetesCount = "totalDiabetes" },
with this line
userdata = new { totalDiabetes = TotalDiabetesCount }
In my javascript code, I have replaced the line
var totaldiabetes = jQuery("#allextraperson").getGridParam('totalDiabetes');
with these lines,
var userData = jQuery("#allextraperson").getGridParam('userData');
if (userData.totalDiabetes) {
$('#total-diabetes').text(userData.totalDiabetes);
}
And in my View I have added an id = "total-diabetes" to strong tag in html. Thus I got the output.
| {
"pile_set_name": "StackExchange"
} |
Q:
confparse says IP address is not found as file or directory
This is the what I'm trying to accomplish with my code:
properties( IPADDR='192.168.0.1', NETMASK='255.255.255.0' ).apply_to( '/path/to/ifcfg-eth0' )
However, it's stating that the IP address is not found as file or directory. But from the docs we can see that is the proper format.
SEE: http://code.google.com/p/confparse/
CODE BELOW:
def writestaticConf(nic, ipa, netm):
""" Write conf file """
whichnic = '/etc/sysconfig/network-scripts/ifcfg-' + nic
print whichnic
ip = "IPADDR=" + ipa
mask = "NETMASK=" + netm
print ip + " " + mask
properties(ip, mask).apply_to(whichnic)
TRACEBACK BELOW
In [45]: writestaticConf('eth0','192.168.0.1', '255.255.255.0')
/etc/sysconfig/network-scripts/ifcfg-eth0
IPADDR=192.168.0.1 NETMASK=255.255.255.0
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-45-00917222fac3> in <module>()
----> 1 writestaticConf('eth0','192.168.0.1', '255.255.255.0')
<ipython-input-44-7af6f7537082> in writestaticConf(nic, ipa, netm)
6 mask = "NETMASK=" + netm
7 print ip + " " + mask
----> 8 properties(ip, mask).apply_to(whichnic)
9 #w.apply_to(whichnic)
/root/.virtualenvs/teknasportal/lib/python2.7/site-packages/confparse-1.0a1-py2.7.egg/confparse.py in __init__(self, _fileordict, _order, **kwargs)
123 if isinstance( _fileordict, str ) or isinstance( _fileordict, list):
124 self.template=_fileordict
--> 125 self.read( _fileordict )
126
127 elif hasattr( _fileordict, '__setitem__' ):
/root/.virtualenvs/teknasportal/lib/python2.7/site-packages/confparse-1.0a1-py2.7.egg/confparse.py in read(self, filenames)
309
310 if isinstance(filenames, basestring):
--> 311 self._read( file(filenames), filenames)
312 self.template=filenames
313
IOError: [Errno 2] No such file or directory: 'IPADDR=192.168.0.1'
A:
properties('IPADDR=192.168.0.1', 'NETMASK=255.255.255.0')
is not the same as
properties(IPADDR='192.168.0.1', NETMASK='255.255.255.0')
If you want to use a keyword argument, use a keyword argument! Don't prepend 'IPADDR=' to the string itself.
properties(IPADDR=ip, NETMASK=mask)
| {
"pile_set_name": "StackExchange"
} |
Q:
INSERT Error - IF file EMPTY function not working
I have this code and for some reason I am getting this error
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's','Used','A Book','1','http://media1.' at line 2
CODE:
if(empty($_POST['image'])) {
$file = 'http://media1.site.org/products/images/no-photo.jpg';
} else {
define('UPLOAD_DIR', '/products/images/');
define('UPLOAD_HOST', 'http://media1.sabinalcanyon.org/products/images/');
move_uploaded_file($_FILES['image']['tmp_name'],UPLOAD_DIR.$_FILES['image']['name']);
$file = UPLOAD_HOST.$_FILES['image']['name'];
}
$descedit = "<p>".$_POST['description']."</p>";
mysql_query("INSERT INTO products (`title`,`barcode`,`ISBN`,`catagory`,`set_price_start`,`brand`,`condition`,`description`,`amount_stock`,`picurl`)
VALUES('$_POST[title]','$_POST[barcode]','$_POST[ISBN]','$_POST[catagory]','$_POST[set_price_start]','$_POST[brand]','$_POST[condition]','$descedit','$_POST[amount_stock]','$file')") or die(mysql_error());
Line 2 is just the start of this block of code.
A:
i just give you an example and you continue with the other variables.
VALUES('".mysql_real_escape_string($_POST['title'])."',.......
and about your error
right syntax to use near 's' ,
this is due to $_POST[brand] variable.
i guess you have some values in your brand variable which includes apostrof 's
then better to escape it like that
'".mysql_real_escape_string($_POST['brand'])."'
Please turn to PDO or MYSQLI as mysql is already deprecated.
| {
"pile_set_name": "StackExchange"
} |
Q:
May a low DRAM router be a bottleneck for a LAN?
I need to install a LAN that is a hybrid between a star LAN and a cascade LAN. There are two levels (I mean that the maximum number of link to go from the central switch to the most external switch is 2 cables), and the "central" switch (connected to all other first level switches) is a NetGear ProSafe 8800 Series 6-Slot Chassis. It is connected to first level switches with 10 Gbps cables, and they have a bandwidth greater than 10 Gb.
The central switch should be connected to the external network with a router, and I've seen this router, but my big doubt is about DRAM, which is only 1/2 GB. So if the switch linked to it has a bandwidth a lot greater than 2 GB, will the router be a bottleneck?
A:
It's going to depend on what features you're intending to use and your exact configuration, but generally RAM in a router is primarily going to be used for routing tables, route cache, security policy etc. and if you've got it enabled, connection tracking.
If the network is working properly, packets spend almost zero time in the router, so the DRAM capacity is pretty much irrelevant for packet forwarding rate, as long as there's enough for a few 10s of ms of packet buffer. However you can definitely create configurations that depend a lot more on RAM and may fail entirely or slow down drastically if you don't have enough.
As far as basic PPS (packets per second) rate is concerned though it's basically not a factor.
| {
"pile_set_name": "StackExchange"
} |
Q:
React js - Calling a method from another method
const ACCESS_TOKEN = 'auth_token';
var api = {
async removeToken(){
try {
await AsyncStorage.removeItem(ACCESS_TOKEN);
this.getToken(ACCESS_TOKEN);
} catch (error) {
console.log("something went wrong remove token")
}
},
async storeToken(accessToken){
try {
await AsyncStorage.setItem(ACCESS_TOKEN, accessToken);
this.getToken(ACCESS_TOKEN);
} catch (error) {
console.log("something went wrong store token")
}
},
async getToken(){
try {
let token = await AsyncStorage.getItem(ACCESS_TOKEN);
var parsedToken = JSON.parse(token).auth_token;
console.log("getToken: " + parsedToken);
return parsedToken;
} catch (error) {
console.log("something went wrong gettoken")
return null;
}
},
getTasks(){
var url = "http://doit.unicrow.com/api/v1/tasks/";
return fetch(url, {
method: 'GET',
headers: {
'Authorization': "Token" + this.getToken()
}
}).then(response => response.json())
}
}
module.exports = api;
Hi everyone, i am doing a project with react js and i am having a problem with it. In the above code snippet in getTasks method, I want to call the token value that returns from getToken method . I couldn't do it with using "this". How can I do it? Thanks in advance.
A:
you can do it by using state
maintain a local state as
{
token:""
}
set the token in state as
async getToken(){
try {
let token = await AsyncStorage.getItem(ACCESS_TOKEN);
var parsedToken = JSON.parse(token).auth_token;
console.log("getToken: " + parsedToken);
// return parsedToken;
this.setState({
token:parsedToken
})
} catch (error) {
console.log("something went wrong gettoken")
return null;
}
},
and in your getTasks method access it from state as
getTasks(){
var url = "http://doit.unicrow.com/api/v1/tasks/";
return fetch(url, {
method: 'GET',
headers: {
'Authorization': "Token" + this.state.token
}
}).then(response => response.json())
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Dwarf Fortress - Haven't Been Attacked
Okay right, so I'm fairly new to DF but have managed to get a semi-sizeable base up and running with some fortifications and a (I hope) half-decent military. Anyways, we're nearly at the third year and haven't been attacked, raided or besieged and I'm starting to wonder why nothing has come along when I've read that everything is out to kill you! Is there a way to force people to attack you just for the hell of it?
Edit: I just got besieged by goblins, guess they had a bit of a treck and I slaughtered an elven caravan, so lets see what the consequences of that are...
A:
There is a few reasons why you've not had anyone attack...
Normally attacks occur after your fortress has exceeded a certain value, and if you haven't yet passed this then you won't get many/any attackers. You can try engraving to raise the value of the fort, to cause some attackers to come.
Also, it's possible that the attackers are far far away, this means they'll take longer to get to you, sometimes a number of years can pass without incident, only to suddenly get attacked when you were starting to think there was nothing out there, and you'd recycled those walls to build more bedrooms...
And finally it's possible there isn't anything out there. Sometimes other civilizations will be wiped out, or simply never spawn due to the spawning mechanics (which in turn effects the world generation.)
To see if you've maybe been involved in wars/attacks/other things and not realised (maybe a dog scared off a sneaky goblin you didn't notice?) hit C and it'll show ANY civ's you've interacted with, be that by wars, or trade (and it'll show the dwarven civ you've come from).
If you're looking for a fight, dig deeper brave dwarf...
A:
Here's a couple simple things to check:
It is entirely possible that during world gen all other civilizations have died off. If this is the case, you will never get invaded, etc., though you should still come under fire from Mega and Forgotten Beasts. A subset of this case is embarking on an isolated island or continent -- there might be elves or goblins in the world, they just can't reach you. You can check this by viewing the neighbors tab on the embark screen. (Press Tab to change modes)
(If the neighbors tab only has Dwarves, you will never be invaded / receive traders)
You have not met the Wealth Threshold for invasions and/or megabeasts. Just make more stuff, and they will come!
Invaders are turned off in the config. Check "d_init.txt" inside /installation_folder/data/init to see what the settings are. There are also "d_init.txt" files within each save directory, so you can tweak these on a game-by-game basis. Depending on where you downloaded the game from, this might have been set to "OFF".
| {
"pile_set_name": "StackExchange"
} |
Q:
Author firstname, Initials and Lastname values find and store in LaTeX3
I would like to store each authors firstname, initials and lastname values in newcommands. My MWE is:
\documentclass{article}
\usepackage{xparse}
\makeatletter
\def\author#1{\gdef\@author{#1}
\getfirstpart\firstname{#1}
%\getinitial\initials{#1}
\getlastpart\lastname{#1}}
\makeatother
\ExplSyntaxOn
\NewDocumentCommand{\getfirstpart}{mm}
{
\seq_set_split:Nnn \l_tmpa_seq { ~ } { #1 }
\seq_pop_left:NN \l_tmpa_seq #1
}
\NewDocumentCommand{\getlastpart}{mm}
{
\seq_set_split:Nnn \l_tmpa_seq { ~ } { #2 }
\seq_pop_right:NN \l_tmpa_seq #1
}
\ExplSyntaxOff
\begin{document}
\author[[email protected], web="http://www.tex.stackexchange.com", address=Department of Mathematics, UK]{John Smith} %% mail value should store \mail{[email protected]}, web value should store in \web{http://www.tex.stackexchange.com} and address value should store \address{Department of Mathematics, UK}
\firstname and \lastname
\author{John X. Smith}
\firstname and \lastname %%how do store initial value?
\author{Smith}
\author{Brian H.-K. Lly}
\end{document}
A:
For standard American names “Firstname I. Surname” automation is possible. Here's some code that uses this, but can be helped for different cases:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\keys_define:nn { balaji/author }
{
mail .tl_set:N = \l_balaji_mail_tl,
mail .initial:n = {},
web .tl_set:N = \l_balaji_web_tl,
web .initial:n = {},
address .tl_set:N = \l_balaji_address_tl,
address .initial:n = {},
firstname .tl_set:N = \l_balaji_firstname_tl,
firstname .initial:n = {},
initials .tl_set:N = \l_balaji_initials_tl,
initials .initial:n = {},
lastname .tl_set:N = \l_balaji_lastname_tl,
lastname .initial:n = {},
fullname .tl_set:N = \l_balaji_fullname_tl,
key .tl_set:N = \l_balaji_key_tl,
key .initial:n = {},
}
\NewDocumentCommand\xauthor{ O{} m }
{
\group_begin:
\keys_set:nn { balaji/author } { #1 }
\keys_set:nn { balaji/author } { fullname = #2 }
\balaji_define_author:n { #2 }
\group_end:
}
\cs_new_protected:Npn \balaji_define_author:n #1
{
\tl_if_empty:NT \l_balaji_lastname_tl
{
\seq_set_split:Nnn \l_balaji_author_seq { ~ } { #1 }
\seq_pop_right:NN \l_balaji_author_seq \l_balaji_lastname_tl
\seq_pop_left:NN \l_balaji_author_seq \l_balaji_firstname_tl
\tl_set:Nx \l_balaji_initials_tl { \seq_use:Nn \l_balaji_author_seq { ~ } }
}
\tl_if_empty:NT \l_balaji_key_tl
{ \tl_set_eq:NN \l_balaji_key_tl \l_balaji_lastname_tl }
\seq_gput_right:NV \g_balaji_author_list_seq \l_balaji_key_tl
\prop_new:c { g_balaji_author_ \l_balaji_key_tl _prop }
\balaji_populate:n { mail, web, address, firstname, initials, lastname, fullname }
}
\cs_new_protected:Npn \balaji_populate:n #1
{
\clist_map_inline:nn { #1 }
{
\prop_gput:cnv { g_balaji_author_ \l_balaji_key_tl _prop }
{ ##1 }
{ l_balaji_##1_tl }
}
%\prop_show:c { g_balaji_author_ \l_balaji_key_tl _prop } % for debugging
}
\cs_generate_variant:Nn \prop_gput:Nnn { cnv }
\seq_new:N \l_balaji_author_seq
\seq_new:N \g_balaji_author_list_seq
\NewDocumentCommand{\getauthorfield} { m m }
{
\prop_item:cn { g_balaji_author_#1_prop } { #2 }
}
\ExplSyntaxOff
\begin{document}
\xauthor{John X. Smith}
\xauthor[
key=HK,
web=http://x.y.z,
firstname=Brian,
lastname=Hamilton Kelly
]{Brian Hamilton Kelly}
\xauthor[
key=VP,
firstname=Charles,
initials={L. X. J.},
lastname={de la Vall\'ee Poussin},
]{Charles Louis Xavier Joseph de la Vall\'ee Poussin}
\getauthorfield{Smith}{firstname} \getauthorfield{Smith}{lastname}
\getauthorfield{HK}{web}
\end{document}
If the name is “complex”, you can and should add a key; the same if the same last name appears more than once. For a simple name, the key is set to the last name.
I set a global sequence containing the keys, so it can be mapped for retrieving the information. Of course much more should be done.
The information about the author whose key is KEY is contained in the property list \g_balaji_author_KEY_prop. Single fields can be retrieved by \getauthorfield{KEY}{<field name>}. It's easy to extend the set of fields.
| {
"pile_set_name": "StackExchange"
} |
Q:
Quicksort Counter Example
Firstly (as the question title implies) I'm not looking for why the bellow partitioning method doesn't work, rather a modification to it so that it will work for the following input:
int[] a = {1,2,8,4,5,7};
Here's the partition method along with some other stuff:
static int[] swap (int[] a,int i,int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
return a;
}
static int partition (int[] a,int l,int r){
int i = l;
int j = r;
int v = a[l];
while (true) {
while (a[i] < v) {
if (i == r) break;
i++;
}
while (a[j] > v) {
if (j == l) break;
j--;
}
if (i >= j) break;
a = swap(a,i,j);
}
a = swap(a, l, j);
return j;
}
void sort(int[] a,int l,int r){
int j = partition(a, l, r);
sort(a, l, j-1);
sort(a, j+1, r);
}
public static void main(String[] args) {
int[] a = {1,2,8,4,5,7};
System.out.println(partition(a,0,5));
}
Output:
0
The output is the index of the pivot returned from the partition method. 0, as the index of the pivot, makes sense in terms of the definition, i.e. everything left of the pivot is smaller and everything right of the pivot is larger, but clearly runs into a problem in sort namely:
sort(a, l, j-1);
where you have the right pointer being negative (j-1 = 0-1 = -1). My question again being is there a modification to the above method(s) that will maintain the definition (everything left of the pivot is smaller and everything right of the pivot is larger) and not run into the problem in sort.
A:
The missing part is the line
if ( l >= r ) return;
in the beginning of the sort method. This is actually the recursion stop step so it is necessary to have it anyway to prevent endless recursion. But besides that, it also solves your problem, because if you call sort(0,-1) then -1 is less than 0, so it prevents further processing of that index.
| {
"pile_set_name": "StackExchange"
} |
Q:
Modify default text in subject+body in "Send e-mail" section of the "Add users" screen
I would like to modify the default text in Subject and Personal message, on the page:
http://(sharepoint)/_layouts/aclinv.aspx
Where do I change the text?
Thanks :-)
A:
About three ways I can see this being done:
Make a copy of the aclinv.aspx page, name it something like aclinv_custom.aspx. In the aspx you copied modify the text properties of the txtEmailSubject and txtEmailBody controls : 1 Problem though, you would need to modify the Javascript in the page itself as this sets the subject value.
Make a copy of the page as above, except this time create a custom page class that inherits from Microsoft.SharePoint.ApplicationPages.AclInv. Override the Page load event and set the properties programtically. Change the inherits tag in the copied page to point to the newly created class. You would still need to change the page javascript though.
Make a copy of the page as above, in the head of the aspx modify the javascript in the UpdateEmailSubject() javascript function to set the subject text field, you could also set the body text in the same way.
All these approaches would require that you update any setting page links that take the user to the original aclinv.aspx. You could do this using feature actions to remove the existing link and add in your custom link. This way you avoid modifying any of the OOTB files, and you can deploy the new page via a solution avoiding any issues with service pack updates etc that may modify the original page.
Hope this helps
Stuart
| {
"pile_set_name": "StackExchange"
} |
Q:
Color Normalization
Im doing a normalization for my image and i've already gotten done the RGB values for the image. can anyone help me with the RGB normalization for the c# codes like maybe some starters on how to write out the normalization code. thanks!
private void normalization_Click(object sender, EventArgs e)
{
// for (int x = 0; x < pictureBox1.Width; x++)
{
// for (int y = 0; y < pictureBox1.Height; y++)
{
try
{
Bitmap img = new Bitmap(pictureBox1.Image);
Color c;
for (int i = 0; i < img.Width; i++)
{
for (int j = 0; j < img.Height; j++)
{
c = img.GetPixel(i, j);
int r = Convert.ToInt16(c.R);
int g = Convert.ToInt16(c.G);
int b = Convert.ToInt16(c.B);
d = r / (r + g + b);
h = g / (r + g + b);
f = b / (r + g + b);
img.SetPixel(i, j, Color.FromArgb(d, h, f));
Color pixelColor = img.GetPixel(i, j);
float normalizedPixel = (d + h + f);
Color normalizedPixelColor = System.Drawing.ColorConverter.(normalizedPixel);
img.SetPixel(x, y, normalizedPixelColor);
}
}
}
catch (Exception ex) { }
Hi. I've done the formulaes and all for normalization. The problem that I am facing now is that I'm having trouble getting the values of the RGB pixels out of the listbox and normalizing it with the formulae and then putting the pixels back into picturebox/image. Above is the code that i've tried to do to put the normalized RGB pixels back into the picturebox. Can I ask for some help with this because it still doesn't normalize my image. Thanks.
A:
Have a look at AForge.NET if you do not mind having a dependency in your project. As a bonus you'll have plenty of other algorithms at your availability without the need for you to re-invent the for loop...
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it good, if I insert my problem on public chat to get more attention?
I've doubt on some questions. I've worked with these with my best, when I'm not satisfied with my solution or if there were any ambiguity.
I've tried to edit, set bounty etc., then I've got some beautiful solution.
My question is :
Is it OK, if I insert my problem on public chat to get more attention?
A:
You can ask a question on chat, but let people know that the question is also on the main site, and try to follow the chat suggested rules, especially 2, 3, and 4.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reference request (famous mathematicians for High School)
Some students of an High School asked me some books from famous mathematicians that they can read (so advanced high school level focused mainly on real-analysis). They were asking things like Cauchy, Fermat... but I think the language would be technical in an akward ancient way for them so that probably will not be suitable. I thought that maybe Riemann dissertation could do but maybe it's too advanced. I then thought Galois, but again the original papers are quite difficult to understand if you don't already have the right picture in your mind.
I'm not sure there's effectively a book from an historically famous mathematician that could fit the request. They didn't specifically requested that the argument should be mathematical even if I think they implied this, otherwise I could suggest something of Poincaré which rather philosophical but at least readable.
They didin't specify the period (even if I think they might want to already know the name of the writer). In modern period maybe I would suggest Mumford the Indra's Pearls. But I'm quite sure they don't know Mumford...
I'm now thinking that maybe some kind of physicist would be better. But they were asking mathematicians.
I really don't have a clue of what to suggest. Please help me!
Edit. Someone correctly asked me why I'm "limiting to Mathematicians they've heard of". I totally agree with who's asking. Old mathematics would be kind of akward I think. The problem is not that "I'm limiting", the problem is that "this is what they asked". It's something like "We have seen their theorems, heard a lot about them, we would like to read something written by them". As pointed out is that probably this request cannot be fulfilled entirely or is not a good idea to fulfill their request. So any suggestion will be take into account. If it was physics Schroedinger "What is Life" and some Heisenberg essays would be in order... in mathematics I've no clue if exists something similar... I think maybe Poincaré is the only one...
A:
It's quite difficult to find maths books written by famous mathematicians of the past that even contemporary mathematicians would find worth reading from a mathematical point of view, since mathematicians write for their peers, who have both different knowledge and different interests from people of today. On the other hand, presumably mathematicians writing about stuff that isn't mathematics is not quite what you have in mind.
Hardy, A Course in Pure Mathematics. Yes, it's an analysis textbook, but it's written by one of the English mathematicians of the twentieth century.
Littlewood, A Mathematician's Miscellany. This is one of those books that you either really enjoy, or don't connect with, but a lot of mathematicians praise it highly.
Hilbert and Cohn-Vossen, Geometry and the Imagination. I wish more mathematicians wrote books like this: it's a nice classical bridge from Euclidean to advanced geometry, with plenty of illustrations.
A:
An introduction to the theory of numbers by G.H. Hardy and E.M. Wright
Number theory. An approach through history and Number theory for beginners by André Weil
Solving mathematical problems. A personal perspective, Terence Tao
Calcul des probabilités by Henri Poincaré (in french)
A:
I recommend a classic from one of our greatest, published in 1748, with accessible content and wonderful to read
Introduction to the Analysis of the Infinite
by Leonhard Euler.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does angular lazy loading compile everything, or when it is loaded
Apologies if this documented somewhere, but I couldn't find an answer.
We are trying to improve the loading time for our Angular application. Currently it takes 8seconds to load. About 3 to download all the resources and 5 to compile the app.
We can't use AOT right now due to some server side generation of html, but this is in scope for the future.
So, if we use lazy loading to only load modules when their routes are loaded, will we see a speed up in our compilation? IE does it compile the bare minimum, then compiles the modules being routed to just before navigation?
A:
Lazy loading won't improve your compilation time for the app, but will speed up the loading of client side pages.
With lazy loading only module required items are downloaded, so lightweight modules will be loaded faster, but if you have "heavy" modules they will take some time to be loaded.
Lazy loading is a good solution if it's a common case that your user only navigate few modules of your site, without the need to load all the resources the site require.
| {
"pile_set_name": "StackExchange"
} |
Q:
Possible to have a on_delete=PROTECT on PageChooserBlock?
Let's say that I have an awesome Wagtail project.
In this project I would like a Page where I can add unlimited Pages as links, the code would look like this:
pages = StreamField([
('link_page', blocks.PageChooserBlock(help_text='Link page')),
])
As you can see I have this StreamField with PageChooserBlock's that I can add.
My template would look like this:
{% for block in page.pages %}
<a href='{% pageurl block.value %}'>{{ block.value.specific.title }}</a>
{% endfor %}
But what happens now if someone would delete one of the "linked" pages.
They would be deleted from the pages streamfield, or at least. The streamfield would be shown, but empty.
Is there some way of adding a on_delete=PROTECT on the PageChooserBlock? like so:
pages = StreamField([
('link_page', blocks.PageChooserBlock(help_text='Link page', on_delete=blocks.PROTECT)),
])
If someone tries to delete the page now, they would get a violation error.
e.g. Works perfect on ForeignKey:
page = models.ForeignKey(
'wagtailcore.Page',
null=True,
blank=True,
on_delete=models.PROTECT,
related_name='',
help_text= 'Page',
)
A:
It's not possible in current versions of Wagtail - StreamField data is stored as a JSON string, which makes it difficult to identify places where a page ID is referenced within that data, and certainly not something that can be enforced at the database level.
However, there's a pull request currently in the works which will identify these cases and warn about them at the point that the page is deleted: https://github.com/wagtail/wagtail/pull/4702
| {
"pile_set_name": "StackExchange"
} |
Q:
R combining ggplot with dlply
I have the following data frame
structure(list(G1 = c(68, 68.6, 66.6, 73.1, 51.6, 50.1, 64.1,
73, 63.7, 43.2, 62.3, 59.2, 67.5, 68.2, 54.6, 67.9, 56.5, 54.2,
67.3, 68, 68.4, 67.9, 73.3, 51.7, 50.3, 63.9, 73.9, 64, 42.9,
62.5, 59.3, 66.7, 68.4, 54, 68.2, 56.8, 54.5, 67, 53.2, 41.4,
53, 52.3, 41, 37.4, 56.9, 65.3, 36.2, 35.3, 36.1, 32.5, 56.5,
47.7, 39.4, 59.6, 38.1, 24.2, 30.2, 68.5, 68.9, 70.7, 74.9, 53.4,
51.6, 65.9, 75.7, 64.7, 42.8, 61.4, 60.8, 69.5, 68.7, 55.9, 70.7,
59.5, 51.1, 69.5), G2 = c(79.8, 72.2, 73.5, 74.4, 50.4, 54.8,
63.1, 70.4, 63.6, 45.1, 65.3, 49.4, 65.3, 76.2, 51, 63.9, 58.7,
57.8, 67, 79.6, 72.1, 73.9, 74.7, 50.5, 55.1, 62.8, 70.5, 63.3,
44.6, 65.5, 48.9, 64.9, 76.3, 50.6, 64.8, 58.6, 58.3, 67.4, 51.2,
37.7, 49.1, 53.7, 44.6, 37.3, 54.9, 64.1, 33.8, 31.9, 34.2, 30.3,
56.2, 44.6, 38.2, 63.2, 35.8, 26.5, 27.6, 80.6, 71.6, 75.4, 77.1,
52.4, 56.3, 66, 72.3, 64.5, 38.2, 64.3, 49.2, 66.9, 77.1, 52.4,
67.5, 59.6, 55.6, 69.9), S1 = c(75.1, 65.9, 72.7, 68.8, 49, 57.5,
66.5, 74.1, 60.9, 51.8, 58, 64.3, 71.1, 71.4, 58.9, 62.2, 58,
57.7, 58.6, 75.2, 66, 73.2, 69.7, 48.9, 57.7, 66.5, 74.7, 60.8,
51.4, 58.9, 65.5, 70.5, 71.4, 58.9, 65.1, 60.8, 57.7, 58.4, 54.3,
40.2, 52.6, 60.5, 42.6, 34.1, 55, 64.7, 36.3, 32.5, 39, 38.8,
58.1, 48, 40.5, 61, 40, 26.4, 28.8, 76.4, 66.5, 73.9, 72, 50.7,
59.2, 69.9, 76.3, 62.4, 50, 58.5, 66.6, 73.7, 72.3, 62.6, 69.6,
62.7, 57.9, 61.1), S2 = c(76.6, 71.6, 71.2, 72.7, 51.6, 56.7,
65.9, 73.5, 63.6, 55.2, 62.6, 62.2, 69.1, 71.1, 56.8, 61, 61.7,
60, 55.7, 76.9, 71.6, 72.3, 73.2, 51.7, 56.8, 64.5, 74.9, 63.6,
51.3, 63, 62.8, 68.7, 71.3, 56.8, 64.2, 62.8, 60.4, 55.8, 53.6,
42.5, 50, 54.4, 42.2, 36.4, 57.7, 64.1, 35.1, 30.8, 39.1, 37.4,
58.7, 47.8, 42, 58.8, 39.4, 24.2, 28.2, 78.2, 73.3, 72.3, 75.6,
53.4, 57.8, 68.3, 76.6, 63.7, 51.7, 63.4, 63.3, 71.5, 72.3, 60.2,
67.1, 65.5, 58.2, 59.1), Method = structure(c(4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Simple_2_ROI", "Single_ROI",
"WIG_drawn_bg", "WIG_Method"), class = "factor")), .Names = c("G1",
"G2", "S1", "S2", "Method"), class = "data.frame", row.names = c(NA,
-76L))
What I would like to do is produce a correlation heatmap (lower triangle only) for this data set based on the variable Method.
I can get the required plot for all data using the following code
library(reshape2)
library(ggplot2)
c = cor(df[sapply(df,is.numeric)])
cordf.m = melt(cor(df[sapply(df,is.numeric)]))
df.lower = subset(cordf.m[lower.tri(c),],Var1 != Var2)
df.ids <- subset(cordf.m, Var1 == Var2)
ggplot(data=df.lower, aes(x=Var1,y=Var2,fill=value)) + geom_tile() + theme_bw() + geom_text(aes(label = sprintf("%1.2f",value)), vjust = 1) + geom_text(data=df.ids,aes(label=Var1)) + scale_fill_gradient2(midpoint=0.8,low='white',high='steelblue') + xlab(NULL) + ylab(NULL) + theme(axis.text.x=element_blank(),axis.text.y=element_blank(), axis.ticks=element_blank(),panel.border=element_blank(),legend.position='none')+ggtitle("All Data")
which gives the following graph
I can get a basic correlation heatmap per method using dlply
dlply(df, .(Method), function (x1) {
ggplot(melt(cor(x1[sapply(x1,is.numeric)])),
aes(x=Var1,y=Var2,fill=value)) + geom_tile(aes(fill = value),colour = "white") + geom_text(aes(label = sprintf("%1.2f",value)), vjust = 1) + theme_bw() +
scale_fill_gradient2(midpoint=0.8,low = "white", high = "steelblue")})
However, I am stuck with a few issues
(i) How do I show the equivalent plot to that above for each method - i.e lower triangle only
(ii) How can I make the ggtitle equal to the method name e.g Simple_2_ROI,.. for each graph
(iii) Also I would like to use stars to highlight the significance of each correlation as done here. How can I do this with my data set (I tried p <- cor.pval(iris.. but get an error message cor.pval is not found
The following gets me closer to what I want
plots <- dlply(df, .(Method), function (x1) {
ggplot(subset(melt(cor(x1[sapply(x1,is.numeric)]))[lower.tri(c),],Var1 != Var2),
aes(x=Var1,y=Var2,fill=value)) + geom_tile(aes(fill = value),colour = "white") +
geom_text(aes(label = sprintf("%1.2f",value)), vjust = 1) +
theme_bw() +
scale_fill_gradient2(midpoint=0.7,low = "white", high = "steelblue") + xlab(NULL)+ylab(NULL) + theme(axis.text.x=element_blank(),axis.text.y=element_blank(), axis.ticks=element_blank(),panel.border=element_blank(),legend.position='none') + ggtitle(x1$Method) + theme(plot.title = element_text(lineheight=1,face="bold")) + geom_text(data = subset(melt(cor(x1[sapply(x1,is.numeric)])),Var1==Var2),aes(label=Var1) ) })
However, I cannot get the correlation stars on the plot
Any pointers?
A:
I have achieved the following solution (though I was unable to achieve the significance stars)
plots <- dlply(df, .(Method), function (x1) {
ggplot(subset(melt(cor(x1[sapply(x1,is.numeric)]))[lower.tri(c),],Var1 != Var2),
aes(x=Var1,y=Var2,fill=value)) + geom_tile(aes(fill = value),colour = "white") +
geom_text(aes(label = sprintf("%1.2f",value)), vjust = 1) +
theme_bw() +
scale_fill_gradient2(name="R^2",midpoint=0.7,low = "white", high = "red") + xlab(NULL)+ylab(NULL) + theme(axis.text.x=element_blank(),axis.text.y=element_blank(), axis.ticks=element_blank(),panel.border=element_blank()) + ggtitle(x1$Method) + theme(plot.title = element_text(lineheight=1,face="bold")) + geom_text(data = subset(melt(cor(x1[sapply(x1,is.numeric)])),Var1==Var2),aes(label=Var1),vjust=3 ) })
#Function to grab legend
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
legend
}
legend <- g_legend(plots$WIG_Method)
grid.arrange(legend,plots$Single_ROI+theme(legend.position='none'), plots$Simple_2_ROI+theme(legend.position='none'),plots$WIG_Method+theme(legend.position='none'), plots$WIG_drawn_bg+theme(legend.position='none'), ncol=5, nrow=1, widths=c(1/17,4/17,4/17,4/17,4/17))
This achieves the following plot
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I manually trigger a ForeSee survey dialog to display with javascript? or URL parameters?
I haven't been able to find any API documentation for ForeSee, and I've had a bug report come in related to the ForeSee Survey prompt dialog that gets randomly displayed. I've tried clearing cache and cookies, but it hasn't displayed for me yet, is there a way to trigger its display with javascript? Or maybe with certain URL parameters?
In foresee-trigger.js I've updated the FSR.sites array to include a reference to localhost:
var FSR = {
'version': '7.0.0',
'date': '01/01/2011',
'enabled': true,
'auto' : true,
'encode' : true,
'files': './foresee/', //default path when no match below
'id': 'etc',
'sites': [
/* several existing ones, etc.*/
{
name: 'localhost',
path: 'localhost',
files: '//localhost/subdirectory/foresee/',
domain: 'localhost'
},{
path: '.',
domain: 'default'
}]
};
A:
You should be able to manually set the sampling percentage for your current session by hitting the "fsradmin.html" page that should be located in the same directory as the foresee-trigger.js file. For example, localhost/YourApp/scripts/foresee/fsradmin.html. Setting the sampling percentage to 100% would ensure that you encounter the survey.
Another option is to change the actual sampling percentage in the foresee-surveydef.js file here:
criteria: {
sp: 75, //this is the sampling % - set it to 100 to ensure that it appears
lf: 1 // loyalty factor, (the # of pages the user has to hit before it appears)
},
If you chose the 2nd option, be sure to set the sampling % back to the original value before deploying your code, or everyone will always get the survey.
Finally here's a link to their documentation: http://demo.foreseeresults.com/_code/docs/ForeSee_Trigger_Code_Implementation_Guide.pdf
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing Date value to NetSuite via API
When populating a date field in NetSuite via the API (e.g Sales Order start date), you are required to specify a timestamp + timezone, even though the timestamp isn't shown in NetSuite.
Does anyone know the logic NetSuite is using to covert a date+timestamp to a date?
For example, sometimes when I pass a date+time of Oct 1 2016 00:00:00 UTC, I see Sept 30 2016 in NetSuite. Other times, I see the date appear as Oct 1 2016 in NetSuite. The logic seems inconsistent. Can anyone explain the logic?
A:
For me it depended on my timezone, and the timezone of the account that was writing to NetSuite.
I had this issue in the past. I resolved it by setting my Integration user account to have GMT timezone. After that, the dates/times have always appeared correct for each user, based on their timezone (set in preferences).
| {
"pile_set_name": "StackExchange"
} |
Q:
SELECT mode/modal value SQL
My first table dbo.Port contains aggregated details about each portfolio
Portfolio Yield Duration Coupon
Port1 0.62 1.10 0.98
Port2 0.52 0.91 2.46
Port3 0.40 0.70 0.37
My second table dbo.Security contains details about each portfolios individual securities
Portfolio Security Yield Duration Coupon Country Sector MarketValue
Port1 Sec1 0.35 0.50 2.25 US CORP 386.17
Port1 Sec2 0.16 0.23 1.75 UK CORP 224.64
Port1 Sec3 0.98 1.96 3.00 US CORP 148.00
Port1 Sec4 0.78 1.40 0.00 DE SOV 980.07
Port2 Sec1 0.35 0.50 2.25 US CORP 386.17
Port2 Sec3 0.98 1.96 3.00 US CORP 148.00
Port3 Sec1 0.35 0.50 2.25 US CORP 386.17
Port3 Sec4 0.78 1.40 0.00 DE SOV 980.07
Port3 Sec5 0.03 0.06 0.00 DE SOV 952.36
I can retrieve the modal country for portfolio 1 with the below separate query. which isUS
SELECT x.Country
FROM (
SELECT TOP 1 COUNT(dbo.Security.Country) as Count ,dbo.Security.Country
FROM dbo.Port
INNER JOIN dbo.Security ON (dbo.Port.Portfolio = dbo.Security.Portfolio)
WHERE dbo.Port.Portfolio = 'Port1'
GROUP BY dbo.Security.Country
ORDER BY Count DESC
) x
What I want my query to return is to return a joined query that selects the modal values of country and sector for each portfolio. Does anyone know how to incorporate this query into the first query or any other method so that I can retrieve MODE(dbo.Security.Country) etc. for each portfolio so that I end up with the below table
Portfolio Yield Duration Coupon Market Value Country Sector
Port1 0.62 1.10 0.98 1738.88 US CORP
Port2 0.52 0.91 2.46 534.17 US CORP
Port3 0.40 0.70 0.37 2318.60 DE SOV
Desired SQL
SELECT
dbo.Port.Portfolio
,dbo.Port.Yield
,dbo.Port.Duration
,dbo.Port.Coupon
,SUM(dbo.Security.MarketValue)
--Not working
,MODE(dbo.Security.Country)
,MODE(dbo.Security.Sector)
--Not working
FROM dbo.Port
INNER JOIN dbo.Security ON (dbo.Port.Portfolio = dbo.Security.Portfolio)
GROUP BY
dbo.Port.Portfolio
,dbo.Port.Yield
,dbo.Port.Duration
,dbo.Port.Coupon
A:
First of all, your query to retrieve the model country for portfolio 1 should include an ORDER BY clause otherwise it will just return the country of the first row that matches the WHERE clause.
Secondly, you could achieve the desired output using inline queries:
SELECT
P.Portfolio
,P.Yield
,P.Duration
,P.Coupon
,SUM(S.MarketValue)
,( SELECT TOP 1 Country FROM dbo.Security WHERE Portfolio = P.Portfolio GROUP BY Country ORDER BY COUNT(*) DESC ) Country
,( SELECT TOP 1 Sector FROM dbo.Security WHERE Portfolio = P.Portfolio GROUP BY Sector ORDER BY COUNT(*) DESC ) Sector
FROM dbo.Port P
INNER JOIN dbo.Security S ON (P.Portfolio = S.Portfolio)
GROUP BY
P.Portfolio
,P.Yield
,P.Duration
,P.Coupon
| {
"pile_set_name": "StackExchange"
} |
Q:
Union of IEnumerable and IQueryable
// get cats out of local db
var localDb = db.Categories.Select(c => c.Name);
// get cats out of wcf
var wcf = service.Categories().Select(c => c.CatName);
// create union set
var all = new HashSet<String>(localDb);
all.UnionWith(wcf);
The above code works fine, but the code below throws a runtime error.
var localDb = db.Products.Where(c => c.Category.Equals(name))
.Select(p => p.Name);
var wcf = service.Products().Where(c => c.CategoryId ==
service.CategoryByName(name).CategoryId)
.Select(p => p.ProName);
var all = new HashSet<String>(localDb);
all.UnionWith(wcf);
exception:
An exception of type 'System.ArgumentException' occurred in
System.Data.Entity.dll but was not handled in user code
Additional information: DbComparisonExpression requires arguments with
comparable types.
Can anyone explain why the first one works and the second doesn't?
A:
This line:
var localDb = db.Products.Where(c => c.Category.Equals(name))
.Select(p => p.Name);
tries to compare names (which I expect are strings) with category objects (which I expect are not)
You can't compare the two, so you get an error.
From your previous example I suspect you wanted to write
var localDb = db.Products.Where(c => c.Category.Name.Equals(name))
.Select(p => p.Name);
| {
"pile_set_name": "StackExchange"
} |
Q:
two y-axes with different scales for two datasets in ggplot2
I have two datasets (can be combined into a single one) that share common x values, while the y values are different - I want to plot the y values in one dataset and put the y-axis on the left of the plot, while plotting the y values in the other dataset and put the y-axis on the right of the same plot. Of course, the relative scales for the two y-axis values are different (actually should be "adjusted" according to the y values in the first dataset. The points in the two datasets will be in different colors in order to distinguish the two scales.
An example is shown below:
d1 = data.frame(x=c(100, 200, 300, 400), y=seq(0.1, 0.4, by=0.1)) # 1st dataset
d2 = data.frame(x=c(100, 200, 300, 400), y=seq(0.8, 0.5, by=-0.1)) # 2nd dataset
p1 = ggplot(data = d1, aes(x=x, y=y)) + geom_point()
p2 = ggplot(data = d2, aes(x=x, y=y)) + geom_point() +
scale_y_continuous(position = "right")
p1
p2
In ggplot2, I cannot do p1+p2 as it will show an error message Error: Don't know how to add o to a plot. Please help. Thank you!
A:
Up front, this type of graph is a good example of why it took so long to get a second axis into ggplot2: it can very easily be confusing, leading to mis-interpretations. As such, I'll go to pains here to provide multiple indicators of what goes where.
First, the use of sec_axis requires a transformation on the original axis. This is typically done in the form of an intercept/slope formula such as ~ 2*. + 10, where the period indicates the value to scale. In this case, I think we could get away with simply ~ 2*.
However, this implies that you need to plot all data on the original axis, meaning you need d2$y to be pre-scaled to d1$y's limits. Simple enough, you just need the reverse transformation as what will be used in sec_axis.
I'm going to combine the data into a single data.frame, though, in order to use ggplot2's grouping.
d1 = data.frame(x=c(100, 200, 300, 400), y=seq(0.1, 0.4, by=0.1)) # 1st dataset
d2 = data.frame(x=c(100, 200, 300, 400), y=seq(0.8, 0.5, by=-0.1)) # 2nd dataset
d1$z <- "data1"
d2$z <- "data2"
d3 <- within(d2, { y = y/2 })
d4 <- rbind(d1, d3)
d4
# x y z
# 1 100 0.10 data1
# 2 200 0.20 data1
# 3 300 0.30 data1
# 4 400 0.40 data1
# 5 100 0.40 data2
# 6 200 0.35 data2
# 7 300 0.30 data2
# 8 400 0.25 data2
In order to control color in all components, I'll set it manually:
mycolors <- c("data1"="blue", "data2"="red")
Finally, the plot:
library(ggplot2)
ggplot(d4, aes(x=x, y=y, group=z, color=z)) +
geom_path() +
geom_point() +
scale_y_continuous(name="data1", sec.axis = sec_axis(~ 2*., name="data2")) +
scale_color_manual(name="z", values = mycolors) +
theme(
axis.title.y = element_text(color = mycolors["data1"]),
axis.text.y = element_text(color = mycolors["data1"]),
axis.title.y.right = element_text(color = mycolors["data2"]),
axis.text.y.right = element_text(color = mycolors["data2"])
)
Frankly, though, I don't like the different slopes. That is, two blocks on the blue axis are 0.1, whereas on the red axis they are 0.2. If you're talking about two vastly different "things", then this may be fine. If, however, the slopes of the two lines are directly comparable, then you might prefer to keep the size of each block to be the same. For this, we'll use a transformation of just an intercept, no change in slope. That means the in-data.frame transformation could be y = y - 0.4, and the plot complement ~ . + 0.4, producing:
PS: hints taken from https://stackoverflow.com/a/45683665/3358272 and https://stackoverflow.com/a/6920045/3358272
| {
"pile_set_name": "StackExchange"
} |
Q:
How to disable the dashed contour for TabItem?
When a TabItem has focus it shows an inner dashed countour. How to make it transparent or to disabling it to get focus at all?
A:
If you're talking about the FocusVisualStyle you can remove it by adding the following to your TabControl
<TabControl ...>
<TabControl.Resources>
<Style TargetType="TabItem">
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
</Style>
</TabControl.Resources>
<!-- ... -->
</TabControl>
Update
To make sure we're talking about the same thing
Selected with FocusVisualStyle (dashed countour)
Selected without FocusVisualStyle. This is the look you'll get when the TabItem has focused (set by keyboard) and FocusVisualStyle is set to null
| {
"pile_set_name": "StackExchange"
} |
Q:
Assigning a property to itself
I don't understanding this error. Please check the code below:
class CardCarousel: UIView {
var numberOfRatesLabel: UILabel
var bestRates: BestRates! {
didSet {
numberOfRatesLabel.text = bestRates.title
}
}
override init(frame: CGRect) {
self.numberOfRatesLabel = numberOfRatesLabel
super.init(frame: frame)
initComponents()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initComponents()
}
private func initComponents() {
numberOfRatesLabel = UILabel(frame: .zero)
self.addSubview(numberOfRatesLabel)
}
}
I checked all the questions mentioning this error. I tried something but nothing better happened.
I found this error:
Assigning a property to itself.
If I put numberOfRatesLabel in the parameter of the init method I have this error:
Initializer does not override a designated initializer from its superclass
A:
The problem is here:
override init(frame: CGRect) {
self.numberOfRatesLabel = numberOfRatesLabel // <- no local declaration of numberOfRatesLabel
super.init(frame: frame)
initComponents()
}
You just should implement something like this:
convenience init(frame: CGRect, numberOfRatesLabel: UILabel) {
self.numberOfRatesLabel = numberOfRatesLabel
self.init(frame: frame)
initComponents()
}
That should do the trick. You don't have to override init(frame: CGRect). But as you initiate the label in initComponents()you can go for this:
var numberOfRatesLabel: UILabel?
override init(frame: CGRect) {
super.init(frame: frame)
initComponents()
}
All depends on your use cases.
| {
"pile_set_name": "StackExchange"
} |
Q:
Doctrine error to create database : Access denied for user
i tried to create a new database in Doctrine, with php app/console doctrine:database:create but i got an error : i fixed it thanks to this website
now i've got a second error, but i can't find any solution :
afther this :
pc11:Symfony Paul$ php app/console doctrine:database:create
i've got this error :
Could not create database for connection named symfony
SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: NO)
i tried without "symfony" but it did not work :
pc11:~ Paul$ php app/console doctrine:database:create
Could not open input file: app/console
Would you know how to fix this?
Thanks
A:
You're probably missing database configuration, it tries to connect to MySQL as the user root without a password and fails to get the permission to create the database.
Check your parameters.ini for settings related to the database connection.
| {
"pile_set_name": "StackExchange"
} |
Q:
Center parallax image
I have this simplify code to add parallax to my image.
When I start scrolling, the top value is incorrect. The distance is too big and when I come back at the top of the website the picture is not centered like the beginning.
How do I calculate the right top value?
$(document).ready(function(){
var scrolledDefault = $(window).height() / 2 - ($('.img__moi').height() / 2) + 25;
$('.img__moi').css('top', scrolledDefault);
$(window).scroll(function(e){
parallax('.img__moi', '0.2');
});
function parallax(element, vitesse){
var scrolled = $(window).scrollTop() + ($(window).height() / 2) - ($(element).height() / 2) + 25;
console.info(scrolled*vitesse);
$(element).css('top',-(scrolled*vitesse)+'px');
}
});
body{
background-color:#cccccc;
height:3000px;
}
.align__text{
position:absolute;
top:calc(50% + 30px);
left:calc(25% + 20px);
width:70%;
-webkit-transform:translateY(-50%);
transform:translateY(-50%);
z-index:2;
}
.header__top{
background-color:$blanc;
padding:5px 0px;
height:50px;
position:fixed;
top:0;
left:0;
right:0;
z-index:9999999;
}
.img__moi{
float:left;
width:25%;
position:absolute;
margin-left:50px;
z-index:2;
transition:all 300ms ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<div class="header__top"></div>
<img src="http://img15.hostingpics.net/pics/317625pexelsphoto.jpg" class="img__moi">
<div class="align__text">
<h1>The title here<br/> Two line</h1>
</div>
</header>
A:
Alternatively, if you rearrange your maths a little you have a set-up that's perhaps easier to apply to other divs without having to wrap them:
var moi = '.img__moi'; // defining the key image classname here
function scrollDef(el) {
var scrolledDefault = $(window).height() - $(el).height(); // or use $('body).height() to center div relative to the scroll area
scrolledDefault = scrolledDefault / 2;
scrolledDefault += 25;
return scrolledDefault;
} // DRY: by calculating scroll top in this way we ensure its defined in one way for greater parity
function parallax(element, vitesse) {
var scrolled = scrollDef(element) - ($(window).scrollTop() * vitesse); // have rearranged the maths slightly to make this work
$(element).css('top', scrolled);
}
$('.img__moi').css('top', scrollDef(moi));
// you could replace the above line with parallax('.img__moi', 0.2); to set the same starting condition
$(window).scroll(function() {
parallax('.img__moi', 0.2);
});
body,
html {
background-color: #cccccc;
height: 3000px;
}
.align__text {
position: absolute;
top: calc(50% + 30px);
left: calc(25% + 20px);
width: 70%;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
z-index: 2;
}
.header__top {
background-color: $blanc;
padding: 5px 0px;
height: 50px;
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 9999999;
}
.img__moi {
float: left;
width: 25%;
position: absolute;
margin-left: 50px;
z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<div class="header__top"></div>
<img src="http://img15.hostingpics.net/pics/317625pexelsphoto.jpg" class="img__moi">
<div class="align__text">
<h1>The title here<br/> Two line</h1>
</div>
</header>
| {
"pile_set_name": "StackExchange"
} |
Q:
Cosa vuol dire "ha risolto" in questo contesto?
Nella commedia Sotto paga! Non si paga! di Dario Fo (testo aggiornato nel 2007 e pubblicato da Einaudi) ho letto:
BECCHINO (senza prender fiato)
Grazie. Piuttosto, mi sapreste dire se abita qui un certo Prampolini Sergio? Non
so se al primo o al secondo piano, o anche al quarto, a meno che non ci sia un sottotetto...?
LUIGI
Sì, sta sopra, al terzo piano. Ma so di sicuro che non
è in casa. È all’ospedale! È sempre ammalato, poveraccio... una brutta vita!
BECCHINO (senza prender fiato)
Infatti è morto.
GIOVANNI
Ha risolto!
Non capisco cosa vuol dire Giovanni quando afferma che questo Prampolini Sergio "ha risolto". Significa forse che è morto? Potreste spiegarmelo? Ho cercato alla voce "risolvere" del Grande dizionario della lingua italiana e ho visto che al numero 4 appare questa accezione:
Fare cessare la vita.
Tuttavia, mi è sembrato strano che tutti e due gli esempi di uso di questo verbo con tale significato siano rinascimentali (si veda qui e qui).
A:
Per comprendere lo scambio, teniamo conto che si tratta di una commedia. Il commento di Giovanni è una battuta. Con «ha risolto», si intende che finalmente Sergio Prampolini ha risolto i suoi problemi di malato… morendo. La battuta può sembrare macabra, ma l’umorismo ha, tra i suoi meccanismi per strappare una risata, anche slittamenti di questo tipo.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't find how to use CONFIG:: directives properly
Let's say I have to compile two different versions of my .swf for different sites. The difference is in hostnames for the ajax and redirection, several minor tweaks in code and in graphics added to the project in .swc. I can switch different swcs easily, but the code tweaks are hard to manage easily. I've got
CONFIG::site1
{
private var _domainName:String = "site1.com";
}
CONFIG::site2
{
private var _domainName:String = "site2.com";
}
FB brings up an error: 1151: A conflict exists with definition _domainName in namespace internal.
What I need is smthn like this in C:
#ifdef SITE1
char hostname[] = "site1";
#endif
#ifdef SITE2
char hostname[] = "site2";
#endif
Is there any way to use compile directives that way using mxmlc?
P.S. Everything works now
A:
I think this documentation will help you.
In your case it is something like the following:
private var _domainName:String = NAMES::site;
And mxmlc arguments will look like:
-define+=NAMES::site,"'site1.com'"
| {
"pile_set_name": "StackExchange"
} |
Q:
How to have Mysql query (with multiple join) faster and more efficient
I have a big problem with the execution of a MySql query that is very slow.. too slow... unusable!
To read 1000 products with their prices it takes more than 20 seconds!!!
$dati = mysqli_query($mysqli_connect, "
SELECT *
FROM $tb_products
LEFT JOIN $tb_categories ON $tb_products.product_category = $tb_categories.category_id_master
LEFT JOIN $tb_subcategories ON $tb_products.product_subcategory = $tb_subcategories.subcategory_id_master
LEFT JOIN $tb_logos ON $tb_products.product_logo = $tb_logos.logo_id_master
LEFT JOIN $tb_prices ON (
$tb_products.product_brand = $tb_prices.price_brand
AND $tb_products.product_code = $tb_prices.price_code
AND $tb_prices.price_validity = (
SELECT MAX($tb_prices.price_validity)
FROM $tb_prices
WHERE $tb_prices.price_validity<=DATE_ADD(CURDATE(), INTERVAL +0 DAY)
AND $tb_products.product_code = $tb_prices.price_code
)
)
WHERE $tb_products.product_language='$activeLanguage' AND $tb_products.product_category!=0
GROUP BY $tb_products.product_code
ORDER BY $tb_products.product_brand, $tb_categories.category_rank, $tb_subcategories.subcategory_rank, $tb_products.product_subcategory, $tb_products.product_rank
");
EDIT:
I've changed, as suggested from Mr.Alvaro, the SELECT * with a more efficient SELECT [list of values] and the execution time dropped from 20 seconds to 14 seconds. Still too slow...
END EDIT
Each product can have different prices, so I use the (select max...) to take the most recent (but not future) price.
Maybe is this function that slow down everything? Are there better solutions in your opinion?
Consider that the same query without the join with the prices it takes only 0.2 seconds.
So I'm convinced that the problem is all in that part of the code.
$dati = mysqli_query($mysqli_connect, "
SELECT *
FROM $tb_products
LEFT JOIN $tb_categories ON $tb_products.product_category = $tb_categories.category_id_master
LEFT JOIN $tb_subcategories ON $tb_products.product_subcategory = $tb_subcategories.subcategory_id_master
LEFT JOIN $tb_logos ON $tb_products.product_logo = $tb_logos.logo_id_master
WHERE $tb_products.product_language='$activeLanguage' AND $tb_products.product_category!=0
GROUP BY $tb_products.product_code
ORDER BY $tb_products.product_brand, $tb_categories.category_rank, $tb_subcategories.subcategory_rank, $tb_products.product_subcategory, $tb_products.product_rank
");
I also considered the fact that it could depend on the power of the server but I would tend to exclude it because the second query (without prices) is quite acceptable as speed.
The prices table is as following
+----------------+-------------+
| price_id | int(3) |
| price_brand | varchar(5) |
| price_code | varchar(50) |
| price_value | float(10,2) |
| price_validity | date |
| price_language | varchar(2) |
+----------------+-------------+
A:
SOLVED
The problem was in the last JOIN with the prices table.
Following the suggestions I managed to execute the SELECT MAX (...) separately and it tooks 0.1 seconds to execute.
So I decide to run the main query without the prices and then, in the WHILE cicle to fetch the array, I run a second query to take the price for every single product!
This work perfectly and my page has dropped down from 20 seconds to a few tenths of a second.
So, the code become something like this:
$dati = mysqli_query($mysqli_connect, "
SELECT *
FROM $tb_products
LEFT JOIN $tb_categories ON $tb_products.product_category = $tb_categories.category_id_master
LEFT JOIN $tb_subcategories ON $tb_products.product_subcategory = $tb_subcategories.subcategory_id_master
LEFT JOIN $tb_logos ON $tb_products.product_logo = $tb_logos.logo_id_master
WHERE $tb_products.product_language='$activeLanguage' AND $tb_products.product_category!=0
GROUP BY $tb_products.product_code
ORDER BY $tb_products.product_brand, $tb_categories.category_rank, $tb_subcategories.subcategory_rank, $tb_products.product_subcategory, $tb_products.product_rank
");
and then..
while ($array = mysqli_fetch_array($dati)) {
$code = $array['product_code'];
$dati_prices = mysqli_query($mysqli_connect, "
SELECT *
FROM $tb_prices
WHERE $tb_prices.price_brand = '$brand' AND $tb_prices.price_code = '$code' AND $tb_prices.price_validity = (
SELECT MAX($tb_prices.price_validity)
FROM $tb_prices
WHERE $tb_prices.price_validity<=DATE_ADD(CURDATE(), INTERVAL +0 DAY) AND $tb_prices.price_code = '$code'
)
GROUP BY $tb_prices.price_code
") ;
}
Probably is not the best and elegant solution but for me works pretty well!
| {
"pile_set_name": "StackExchange"
} |
Q:
Tell Apache to always serve index.php, no matter what is in the URL
I have written a frontend SPA in Javascript. It uses Ember with its routing, fake URL, authentication and all the amazing stuff Ember handles almost implicitly.
The backend is written in PHP and the page shall be served by an Apache server.
Now, the page works just fine if the request is sent to the root file (aka index) and everything is handled from here. If I however reload the page at let's say localhost/login, Apache tries to find a file named login, which, naturally, doesn't exist, as everything is handled in Javascript and I get the widely-known 404 - The requested URL /login was not found on this server.
How do I tell Apache to always serve index.php, no matter what is in the URL?
A:
It should look something like the default .htaccess for Laravel, which will always serve everything through the /index.php page without the actual /index.php in the url ex /index.php/login will be just /login, but it's worth noting that this will not force it through the /index.php page if the file exists.
# Checks if the rewrite mod is on.
<IfModule mod_rewrite.c>
RewriteEngine On
# Force everything through the index.php file
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
| {
"pile_set_name": "StackExchange"
} |
Q:
Cyclic outputs using list comprehensions and modulo
I am trying to get this output using list comprehensions and modulo:
0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678
My current code is:
lst = [i for i in range(10)]
for j in range(len(lst) - 1), lst:
for i in range(1):
lst.append(lst.pop(0))
print(*lst)
How can I improve this code using modulo? Maybe even optimise it in 1 line?
A:
I think you may be over-complicating this somewhat - this would seem to have the intended result - using string.join. Note that we convert the members of the list to strings to enable us to use this approach.
Code:
lst = [str(i) for i in range(10)]
for i in range(len(lst)):
print(''.join(lst))
lst.append(lst.pop(0))
Output:
0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678
Alternatively - if you want the result in one string:
>>> print(''.join([v for x in [lst[i:] + lst[:i] + ['\n'] for i in range(len(lst))] for v in x]))
0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to disentangle a template from its arguments in C++?
Assume I receive two arguments to a template, T1 and T2. If I know T1 is itself a templated class (e.g., a container), and T2 can be anything, is it possible for me to determine the base template type for T1 and rebuild it using T2 as its argument?
For example, if I receive std::vector<int> and std::string, I would want to automatically build std::vector<std::string>. However if I were given std::set<bool> and double, it would produce std::set<double>.
After reviewing type_traits, relevant blogs, and other questions here, I don't see a general approach to solving this problem. The only way I can currently see to accomplish this task is to build template adapters for each type that could be passed in as T1.
For example, if I had:
template<typename T_inner, typename T_new>
std::list<T_new> AdaptTemplate(std::list<T_inner>, T_new);
template<typename T_inner, typename T_new>
std::set<T_new> AdaptTemplate(std::set<T_inner>, T_new);
template<typename T_inner, typename T_new>
std::vector<T_new> AdaptTemplate(std::vector<T_inner>, T_new);
I should be able to use decltype and rely on operator overloading to solve my problem. Something along the lines of:
template <typename T1, typename T2>
void MyTemplatedFunction() {
using my_type = decltype(AdaptTemplate(T1(),T2()));
}
Am I missing something? Is there a better approach?
WHY do I want to do this?
I'm building a C++ library where I want to simplify what users need to do to build modular templates. For example, if a user wants to build an agent-based simulation, they might configure a World template with an organism type, a population manager, an environment manager, and a systematics manager.
Each of the managers also need to know the organism type, so a declaration might look something like:
World< NeuralNetworkAgent, EAPop<NeuralNetworkAgent>,
MazeEnvironment<NeuralNetworkAgent>,
LineageTracker<NeuralNetworkAgent> > world;
I'd much rather users not have to repeat NeuralNetworkAgent each time. If I am able to change template arguments, then default arguments can be used and the above can be simplified to:
World< NeuralNetworkAgent, EAPop<>, MazeEnvironment<>, LineageTracker<> > world;
Plus it's easier to convert from one world type to another without worrying about type errors.
Of course, I can deal with most errors using static_assert and just deal with the longer declarations, but I'd like to know if a better solution is possible.
A:
This seems to work in the manner you're asking about, tested with gcc 5.3.1:
#include <vector>
#include <string>
template<typename T, typename ...U> class AdaptTemplateHelper;
template<template <typename...> class T, typename ...V, typename ...U>
class AdaptTemplateHelper<T<V...>, U...> {
public:
typedef T<U...> type;
};
template<typename T, typename ...U>
using AdaptTemplate=typename AdaptTemplateHelper<T, U...>::type;
void foo(const std::vector<std::string> &s)
{
}
int main()
{
AdaptTemplate<std::vector<int>, std::string> bar;
bar.push_back("AdaptTemplate");
foo(bar);
return 0;
}
Best C++ question this week.
A:
This is basically two separate problems: how to decompose an instantiation of a class template into the class template, and then how to take a class template and instantiate it. Let's go with the principle that template metaprogramming is easier if everything is always a type.
First, the second part. Given a class template, let's turn it into a metafunction class:
template <template <typename...> class F>
struct quote {
template <typename... Args>
using apply = F<Args...>;
};
Here, quote<std::vector> is a metafunction class. It is a concrete type that has a member template apply. So quote<std::vector>::apply<int> gives you std::vector<int>.
Now, we need to unpack a type. Let's call it unquote (at least that seems appropriate to me). This is a metafunction that takes a type and yields a metafunction class:
template <class >
struct unquote;
template <class T>
using unquote_t = typename unquote<T>::type;
template <template <typename...> class F, typename... Args>
struct unquote<F<Args...>> {
using type = quote<F>;
};
Now all you need to do is pass the instantiation into unquote and provide the new args you want into the metafunction class it spits out:
unquote_t<std::vector<int>>::apply<std::string>
For your specific case, just quote everything:
// I don't know what these things actually are, sorry
template <class Agent, class MF1, class MF2, class MF3>
struct World {
using t1 = MF1::template apply<Agent>;
using t2 = MF2::template apply<Agent>;
using t3 = MF3::template apply<Agent>;
};
World< NeuralNetworkAgent,
quote<EAPop>,
quote<MazeEnvironment>,
quote<LineageTracker>
> w;
A:
Your actual problem can be solved by just taking template template parameters.
template <class Agent, template<class...> class F1,
template<class...> class F2,
template<class...> class F3>
struct World {
// use F1<Agent> etc.
};
World<NeuralNetworkAgent, EAPop, MazeEnvironment, LineageTracker > world;
@Barry's quote is a fancier way of doing this, which is useful for more complex metaprogramming, but is IMO overkill for a use case this simple.
Rebinding arbitrary template specializations to a different set of template arguments is not possible in C++; at most you can deal with a subset (primarily templates only taking type parameters, plus some other combinations you may choose to support), and even then there are numerous problems. Correctly rebinding std::unordered_set<int, my_fancy_hash<int>, std::equal_to<>, std::pmr::polymorphic_allocator<int>> requires knowledge specific to the templates used.
| {
"pile_set_name": "StackExchange"
} |
Q:
Eclipse doesn't support C++ Project types
I want to start a C++ Project using eclipse,
but I found that some of the project types are not available in it after I had checked the
CheckBox - "Show project types and toolchains only if they are supported on the platform"
Only "Makefile project > Hello World C++ Project" is available in eclipse.
A:
It does support you have to download Eclipse IDE for C/C++ Developers which can be found here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular Material sorting, Cannot set property 'sort' of undefined
I have a Angular 8 application that uses Angular Material.
I want to sort the colums in a angular 8 application, using Angular Material
googled, courses
So this is how the file looks where sorting is implemented ts file looks like:
import { ActivatedRoute } from '@angular/router';
import { Component, OnInit, ViewChild, Inject, Input } from '@angular/core';
import { QRCodeDefinitionInfoApi, EcheqSubmissionInfoApi, QRCodeMedicalService } from 'src/app/generated';
import { MatPaginator, MatSort } from '@angular/material';
import { MAT_DIALOG_DATA, MatTableDataSource } from '@angular/material';
import { PublishState } from 'src/app/qrcode-definition/list/list-item';
import { I18n } from '@ngx-translate/i18n-polyfill';
class SortedSubmissions {
[key: string]: {
submissions: EcheqSubmissionInfoApi[];
};
}
@Component({
selector: 'app-echeq-qrcode',
templateUrl: './echeq-qrcode.component.html',
styleUrls: ['./echeq-qrcode.component.scss']
})
export class EcheqQrcodeComponent implements OnInit {
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
readonly ScanFequencyType = QRCodeDefinitionInfoApi.ScanFrequencyTypeEnum;
readonly PublishState = QRCodeDefinitionInfoApi.PublishStateEnum;
readonly ActionType = QRCodeDefinitionInfoApi.ActionTypeEnum;
source: QRCodeDefinitionInfoApi[];
datasource: MatTableDataSource<QRCodeDefinitionInfoApi>;
patientId: string;
submissions: EcheqSubmissionInfoApi[];
@Inject(MAT_DIALOG_DATA) public data: any;
@Input() item;
sortedSubmissions: SortedSubmissions;
public readonly displayedColumns = [
'title',
'lastScannedOn',
'totalScanned',
'publishState',
];
constructor(private i18n: I18n, route: ActivatedRoute, private qrCodeDefintion: QRCodeMedicalService ) {
this.patientId = route.snapshot.paramMap.get('patientId');
const data = route.snapshot.data;
this.source = data.definition;
}
ngOnInit() {
this.qrCodeDefintion.getQRCodeList(1, this.patientId).subscribe((subs) => {
(this.source = subs);
});
if (this.data && this.data.definition) {
this.source = this.data.definition;
}
// this.datasource.paginator = this.paginator;
this.datasource.sort = this.sort;
}
translatePublished(publishState: PublishState): string {
switch (publishState) {
case PublishState.DRAFT:
return this.i18n('Not published');
case PublishState.PUBLISHED:
return this.i18n('Published');
}
switch ( String(publishState) ) {
case 'Draft':
return this.i18n('Not published');
case 'Published':
return this.i18n('Published');
default:
return this.i18n( 'Not Published' );
}
}
}
and this is the html of the page:
<div class="header">
<h1 class="heading page-heading patient-list-heading">Scanned QR Codes </h1>
<div class="qrcode-menu">
</div>
</div>
<div class="mat-elevation-z8">
<table
mat-table
class="full-width-table"
[dataSource]="source"
matSort
aria-label="Elements"
>
<ng-container matColumnDef="title">
<th mat-header-cell *matHeaderCellDef mat-sort-header i18n>Name</th>
<td mat-cell *matCellDef="let row">{{ row.title }}</td>
</ng-container>
<ng-container matColumnDef="lastScannedOn">
<th mat-header-cell *matHeaderCellDef mat-sort-header>lastScannedOn</th>
<td mat-cell *matCellDef="let row">{{ row.lastScannedOn | date: 'dd MMM yy' }}</td>
</ng-container>
<ng-container matColumnDef="totalScanned">
<th mat-header-cell *matHeaderCellDef mat-sort-header i18n>totalScanned</th>
<td mat-cell *matCellDef="let row">{{ row.totalScanned }}</td>
</ng-container>
<ng-container matColumnDef="publishState">
<th mat-header-cell *matHeaderCellDef mat-sort-header="wasPublished" i18n>publishState</th>
<td mat-cell *matCellDef="let row">{{ translatePublished(row.publishState) }}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
<mat-paginator [pageSizeOptions]="[25, 50, 100, 250]"></mat-paginator>
</div>
but now I get this error:
ERROR TypeError: Cannot set property 'sort' of undefined
at EcheqQrcodeComponent.push../src/app/components/echeq-qrcode/echeq-qrcode.component.ts.EcheqQrcodeComponent.ngOnInit (echeq-qrcode.component.ts:66)
at checkAndUpdateDirectiveInline (core.js:18620)
at checkAndUpdateNodeInline (core.js:19884)
at checkAndUpdateNode (core.js:19846)
at debugCheckAndUpdateNode (core.js:20480)
at debugCheckDirectivesFn (core.js:20440)
at Object.eval [as updateDirectives] (EcheqQrcodeComponent_Host.ngfactory.js?
That sorting will work for every column.
Thank you
and if I do this:
ngOnInit() {
this.qrCodeDefintion.getQRCodeList(1, this.patientId).subscribe((subs) => {
(this.source = subs);
});
if (this.data && this.data.definition) {
this.source = this.data.definition;
}
// this.datasource.paginator = this.paginator;
this.datasource = new MatTableDataSource<QRCodeDefinitionInfoApi>();
this.datasource.sort = this.sort;
}
I dont get an error. But sorting doesnt work at all
My ngOnit looks now like this:
ngOnInit() {
this.qrCodeDefintion.getQRCodeList(1, this.patientId).subscribe((subs) => {
(this.source = subs);
});
if (this.data && this.data.definition) {
this.datasource = new MatTableDataSource<QRCodeDefinitionInfoApi>(this.source);
this.datasource.sort = this.sort;
this.datasource.paginator = this.paginator;
this.source = this.data.definition;
}
// this.datasource.paginator = this.paginator;
}
But if I do this:
<div class="mat-elevation-z8">
<table
mat-table
class="full-width-table"
[dataSource]="datasource"
matSort
aria-label="Elements"
>
Then the data is not visible anymore.
Thank you. But if I do that. I get this error:
Yes, thank you. But now I get this error: this.source =
this.data.definition;
core.js:12584 ERROR TypeError: Cannot read property 'definition' of undefined
at SafeSubscriber._next (echeq-qrcode.component.ts:61)
at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:196)
This is how I have it now:
ngOnInit() {
this.qrCodeDefintion.getQRCodeList(1, this.patientId).subscribe((subs) => {
(this.source = subs);
this.datasource = new MatTableDataSource<QRCodeDefinitionInfoApi>(this.source);
this.datasource.sort = this.sort;
this.datasource.paginator = this.paginator;
this.source = this.data.definition;
});
}
And this is the html file:
<div class="header">
<h1 class="heading page-heading patient-list-heading">Scanned QR Codes </h1>
<div class="qrcode-menu">
</div>
</div>
<div class="mat-elevation-z8">
<table
mat-table
class="full-width-table"
[dataSource]="source"
matSort
aria-label="Elements"
>
<ng-container matColumnDef="title">
<th mat-header-cell *matHeaderCellDef mat-sort-header i18n>Name</th>
<td mat-cell *matCellDef="let row">{{ row.title }}</td>
</ng-container>
<ng-container matColumnDef="lastScannedOn">
<th mat-header-cell *matHeaderCellDef mat-sort-header>lastScannedOn</th>
<td mat-cell *matCellDef="let row">{{ row.lastScannedOn | date: 'dd MMM yy' }}</td>
</ng-container>
<ng-container matColumnDef="totalScanned">
<th mat-header-cell *matHeaderCellDef mat-sort-header i18n>totalScanned</th>
<td mat-cell *matCellDef="let row">{{ row.totalScanned }}</td>
</ng-container>
<ng-container matColumnDef="publishState">
<th mat-header-cell *matHeaderCellDef mat-sort-header="wasPublished" i18n>publishState</th>
<td mat-cell *matCellDef="let row">{{ translatePublished(row.publishState) }}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
<mat-paginator [pageSizeOptions]="[25, 50, 100, 250]"></mat-paginator>
</div>
I also tried this:
ngAfterViewInit () {
this.qrCodeDefintion.getQRCodeList(1, this.patientId).subscribe((subs) => {
(this.source = subs);
this.datasource = new MatTableDataSource<QRCodeDefinitionInfoApi>(this.source);
setTimeout(() => {
this.datasource.sort = this.sort;
this.datasource.paginator = this.paginator;
});
});
Dont get any errors.But sorting doesnt work.
And if I do a console.log(this.datasource.sort) in the ngAfterViewInit(){}
then I see this:
MatSort {_disabled: false, _isInitialized: true, _pendingSubscribers: null, initialized: Observable, sortables: Map(4), …}
direction: (...)
disableClear: (...)
disabled: (...)
initialized: Observable {_isScalar: false, _subscribe: ƒ}
sortChange: EventEmitter
closed: false
hasError: false
isStopped: false
observers: (5) [Subscriber, Subscriber, Subscriber, Subscriber, Subscriber]
thrownError: null
__isAsync: false
_isScalar: false
__proto__: Subject
sortables: Map(4)
size: (...)
__proto__: Map
[[Entries]]: Array(4)
0: {"title" => MatSortHeader}
key: "title"
value: MatSortHeader {_disabled: false, _intl: MatSortHeaderIntl, _sort: MatSort, _columnDef: MatColumnDef, _showIndicatorHint: false, …}
1: {"lastScannedOn" => MatSortHeader}
2: {"totalScanned" => MatSortHeader}
3: {"wasPublished" => MatSortHeader}
length: 4
start: "asc"
_direction: ""
_disabled: false
_isInitialized: true
_pendingSubscribers: null
_stateChanges: Subject {_isScalar: false, observers: Array(4), closed: false, isStopped: false, hasError: false, …}
__proto__: class_1
So it seems that this is correctly. Isnt?
if I do this:
sortData(sort: Sort) {
this.datasource.sort = this.sort;
console.log(this.datasource.sort);
}
I see this:
MatSort {_disabled: false, _isInitialized: true, _pendingSubscribers: null, initialized: Observable, sortables: Map(4), …}
active: "totalScanned"
direction: (...)
disableClear: (...)
disabled: (...)
initialized: Observable {_isScalar: false, _subscribe: ƒ}
sortChange: EventEmitter {_isScalar: false, observers: Array(6), closed: false, isStopped: false, hasError: false, …}
sortables: Map(4) {"title" => MatSortHeader, "lastScannedOn" => MatSortHeader, "totalScanned" => MatSortHeader, "wasPublished" => MatSortHeader}
start: "asc"
_direction: "desc"
_disabled: false
_isInitialized: true
_pendingSubscribers: null
_stateChanges: Subject {_isScalar: false, observers: Array(4), closed: false, isStopped: false, hasError: false, …}
__proto__: class_1
A:
You have to change this.datasource = new MatTableDataSource<QRCodeDefinitionInfoApi>();
with this.datasource = new MatTableDataSource<QRCodeDefinitionInfoApi>(this.source);
And in HTML you have to pass [dataSource]="datasource" instead of [dataSource]="source"
Edit:
can you please change your ngOnInit method like give below
ngOnInit() {
this.qrCodeDefintion.getQRCodeList(1, this.patientId).subscribe((subs) => {
(this.source = subs);
this.datasource = new MatTableDataSource<QRCodeDefinitionInfoApi>(this.source);
this.datasource.sort = this.sort;
this.datasource.paginator = this.paginator;
this.source = this.data.definition;
});
// this.datasource.paginator = this.paginator;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Web scraping kahoot answer page not turning up children within class
I recently started learning web scraping in python, I have been tried to build a web scraper that find the answers for kahoots. To do this I need to get access to code within a class (or I believe it to be a class, I have not yet learnt html). How do I get access to the part that says <div id="app">. I have tried using the children method in Beautiful soup however this is not returning any results. I need access to the classes within this and I am wondering how to do this. I have attached my code below which cannot access objects within this container.
Many thanks
Edit
I am trying to find the answers for each question so that I can build a bot that plays the kahoot entirely by itself, Thank you for the responses,
from bs4 import BeautifulSoup
import requests
url = 'https://create.kahoot.it/details/disney/0a39590a-cc49-4222-bf28-dd9da230d6bf'
website = requests.get(url)
soup = BeautifulSoup(website.content, 'html.parser')
find_class = soup.find(id='app')
print(list(find_class.children))
A:
The data is loaded dynamically by JavaScript. But you can use requests module to simulate it:
import json
import requests
url = 'https://create.kahoot.it/details/disney/0a39590a-cc49-4222-bf28-dd9da230d6bf'
kahoot_id = url.split('/')[-1]
answers_url = 'https://create.kahoot.it/rest/kahoots/{kahoot_id}/card/?includeKahoot=true'.format(kahoot_id=kahoot_id)
data = requests.get(answers_url).json()
# uncomment this to see all data:
# print(json.dumps(data, indent=4))
for q in data['kahoot']['questions']:
for choice in q['choices']:
if choice['correct']:
break
print('Q: {:<70} A: {} '.format(q['question'].replace(' ', ' '), choice['answer'].replace(' ', ' ')))
Prints:
Q: What kind of animal is Goofy? A: Dog
Q: Who founded Disney? A: Walt Disney
Q: Which country was it illegal to show Donald Duck? A: Finland
Q: Why was it illegal in Finland? A: He weren't wearing pants
Q: Where does Mickey mouse live? A: Mickey mouse clubhouse
Q: Who is Mickey Mouse's girlfriend? A: Minne Mouse
Q: What is Minnie's favorite color? A: Pink
Q: Which year was Disney founded? A: 1923
Q: Who was the voices to Elsa and Anna in Frozen? A: Idina Menzel and Kristen Bell
Q: What did Scrooge McDuck love to bath in? A: Coins
Q: Who is Donald Duck's girlfriend? A: Dolly Duck
Q: Who are these guys? A: Huey, Dewey and Louie Duck
Q: What did the Sleeping Beauty touch to fall asleep in a hundred years? A: On a spindle
Q: Why did Snow white's stepmother hate her? A: Shes pretty
Q: What is the name of Jasmine's tiger? A: Rajah
Q: How many stepsisters did cinderella have? A: 2
Q: Which hair color does Ariel have? A: Red
Q: What is the name of these two characters? A: Mowgli and Baloo
| {
"pile_set_name": "StackExchange"
} |
Q:
Split label style in GeoServer CSS or SLD
I would like to split the style of my labels, which consist of 2 attributes.
I already managed to separate the lines, but I need to style them differently as well, as the second line should be bold.
Currently my map looks like this:
And I would like it to look like this:
I would prefer to do it in CSS, but I also prepared the style in SLD, so I would be happy for a solution in either of them.
My code looks like this in CSS:
* {
label: [IDENT][LOWERLIMIT];
-gt-label-auto-wrap: 1;
font-weight: normal;
font-fill: black;
}
and like this in SLD:
<Rule>
<TextSymbolizer>
<Label>
<ogc:PropertyName>IDENT</ogc:PropertyName><![CDATA[
]]>
<ogc:PropertyName>LOWERLIMIT</ogc:PropertyName>
</Label>
<Font>
<CssParameter name="font-fill">black</CssParameter>
<CssParameter name="font-weight">normal</CssParameter>
</Font>
</TextSymbolizer>
</Rule>
A:
Here is a solution in SLD but I think you should be able to generate the same in CSS.
The trick is to use 2 TextSymbolizers and offset them so that they don't overlap.
<TextSymbolizer>
<Label>
<ogc:PropertyName>STATE_ABBR</ogc:PropertyName>
</Label>
<Font>
<CssParameter name="font-family">Arial</CssParameter>
<CssParameter name="font-style">Normal</CssParameter>
<CssParameter name="font-size">10</CssParameter>
</Font>
<LabelPlacement>
<PointPlacement>
<AnchorPoint>
<AnchorPointX>0.5</AnchorPointX>
<AnchorPointY>1.0</AnchorPointY>
</AnchorPoint>
<Displacement>
<DisplacementX>
0
</DisplacementX>
<DisplacementY>
10
</DisplacementY>
</Displacement>
</PointPlacement>
</LabelPlacement>
</TextSymbolizer>
<TextSymbolizer>
<Label>
<ogc:PropertyName>MALE</ogc:PropertyName>
</Label>
<Font>
<CssParameter name="font-family">Arial Bold</CssParameter>
<CssParameter name="font-style">Normal</CssParameter>
<CssParameter name="font-weight">bold</CssParameter>
<CssParameter name="font-size">10</CssParameter>
</Font>
<LabelPlacement>
<PointPlacement>
<AnchorPoint>
<AnchorPointX>0.5</AnchorPointX>
<AnchorPointY>0.0</AnchorPointY>
</AnchorPoint>
<Displacement>
<DisplacementX>
0
</DisplacementX>
<DisplacementY>
-10
</DisplacementY>
</Displacement>
</PointPlacement>
</LabelPlacement>
</TextSymbolizer>
Depending on your font and polygon sizes you can play with the AnchorPoints and Displacements to adjust the exact placement of the labels.
| {
"pile_set_name": "StackExchange"
} |
Q:
Restore hacked website from database without source
I have a database backup from a hacked drupal site. The source code of the hacked website has been lost. When I try to make another installation of the site working using the old database, I have the following error:
Fatal error: require_once(): Failed opening required 'C:\ampps\www\drupal.fox\drupal/sites/all/modules/date/date_api/date_api.module' (include_path='.;C:\php\pear') in C:\ampps\www\drupal.fox\drupal\includes\bootstrap.inc on line 3168
How could I avoid such errors? is there any way to make drupal runs temporarly without missing modules or even is there a tool that able to download and install missing modules?
A:
Not sure about a tool to download all the modules, but you can do this pretty easily by checking the system table.
Run this:
SELECT * FROM 'system' WHERE 'filename' LIKE '%module' AND 'status' = 1
You will get a list of module names, and the filename shows where the file was stored. Now, you can download the modules from drupal.org (check the schema version if you have doubts about 1.x, 2.x, etc minor version).
If the status of the module is shown as 1, that means the module is enabled, and there can be tables or any other database changes done by this module. You should not uninstall those modules, because you are going to lose all that data when you uninstall it (!= disabling a module).
Also, use registry rebuild module, which adds a handy drush rr to rebuild the registry. You will also need to clear caches a lot (drush cc all) to fix any theme registry mismatches. If you have a custom theme and/or have custom tpl.php files custom modules or custom themes, you will not be able to restore the 100% functionality unless you have those files.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server 2014 Minimum Memory configuration - VMware
I am taking over a SQL Server 2014 environment which has been built and configured by a consultant.
They have set a minimum value for memory which I usually set to 0. According to the consultant and VMware documentation the minimum memory should be set in SQL Server when it is running on a virtual machine. I always set the Maximum leaving memory available for the OS, but do not set the minimum memory.
Any suggestions/thoughts are greatly appreciated!
A:
There is no clear best practice on this. It all depends on your VMWare configuration and failover requirements.
The idea behind this is the fact that it should be preventing SQL Server from releasing memory when the VMWare balloon driver thinks it needs this.
There are several possible problems with that. One of them being the fact that the balloon driver may be requesting memory because a physical host is failing and the VM needs to be moved elsewhere (or other VM's need to be moved to the host the SQL VM resides on).
In case of disaster, what do you prefer? A slow SQL Server or no SQL Server?
The balloon driver will just request memory from other processes on the server if SQL doesn't release it (SSRS, OS, whatever) and if the OS starts paging SQL will suffer anyway.
If you have this configuration because of you are overcommitting memory it might be a better option to reserve memory for the server in VMWare to make sure SQL actually has available what has been allocated.
This setting could be a good configuration, but setting it as a default seems wrong to me. You need to thoroughly understand what it does and what the effects on VMWare are to decide if it should be configured in your environment. Have a good chat with the datacenter/VMWare folks to understand how they have things set up too.
| {
"pile_set_name": "StackExchange"
} |
Q:
Feasibility of another product in peroxide effect mechanism of propene
In the Chain Propagation step of the reaction of propene ($\ce{CH3CH=CH2}$) and hydrogen bromide ($\ce{HBr}$), why is $\ce{CH3-\dot{\ce C}H-CH2-Br}$ free radical formed when a more stable, resonance stabilized allyl free radical ($\ce{\dot{\ce C}H2-CH=CH2}$) is possible?
Source : https://www.chemguide.co.uk/mechanisms/freerad/alkenehbr.html
A:
The energy cost of bromine radical abstracting hydrogen from propene is 89 kcal/mole. The gain of forming $\ce{HBr}$ is 18-28 kcal/mol (for a $\ce{H-Br}$ bond from $\ce{H2}$ and $\ce{Br2}$; variation is due to solvent effects) + 23 kcal/mol (from the $\ce{Br2}$ which was fractured into 2 Br radicals by 46 kcal/mol bond energy); so the gain is 41-51 kcal/mol vs a cost of 89, or a net cost (net energy requirement) of 38-48 kcal/mol. This would be a slow reaction with an activation energy even higher than 41-51 kcal/mol. (All data from CRC Handbook)
The alternate reaction, of adding a Br radical (with 23 kcal/mol energy above ground state) to propene, loses the pi bond and its energy (84 kcal/mol) and gains a $\ce{C-Br}$ bond (70 kcal/mol). The energy cost of forming the bromoradical is 84 but the gain is 70 kcal/mol for $\ce{C-Br}$ plus the 23 kcal/mol from the Br radical, or 93 kcal/mol. Net gain is 9 kcal/mol. This reaction will go spontaneously while the first will not (rate determined by activation energies, of course).
It turns out that allylic stabilization is only part of the story, and is, in fact, rather small: the bond strength of $\ce{H - allyl}$ is 89 kcal/mol vs the bond strength of $\ce{H - n-propyl}$ which is 98 kcal/mol.
| {
"pile_set_name": "StackExchange"
} |
Q:
Etymology of the name Mary?
Why does Strongs 4813 say "מרים [miryâm] \meer-yawm'\" is
From 4805; rebelliously; {Mirjam} the name of two Israelitesses: - Miriam
when St. Jerome writes (Liber de Nominibus Hebraicis col. 886):
Mariam plerique aestimant interpretari, illuminant me isti, vel illuminatrix, vel Smyrna maris, sed mihi nequaquam videtur. Melius autem est, ut dicamus sonare eam stellam maris, sive amarum mare: sciendumque quod Maria, sermone Syro domina nuncupetur.
Many, they tell me, think Maria means either illuminator or the Smyrna sea, but it does not at all seem so to me. For it is better that we say it signifies the star of the sea or bitter sea: and understanding that Maria in Syrian means lady.
and the OED for "Mary" says nothing about "rebellion":
The Hebrew name may be < Amorite, with the meaning ‘gift (of God)’; compare the Akkadian root rym ‘to give as a gift’. […] one element of the name has often been interpreted as ‘sea’, e.g. in pseudo-Epiphanius' explanation σμύρνα θαλάσσης ‘myrrh of the sea’ […] and St Jerome's stella maris
?
A:
What is the etymology of the name of Mary?
As a known and sure fact, we are unsure for there exists several interpretations in this matter. We are not even sure that in is of Hebrew origin. It may in fact be of Egyptian origin. Apparently there are nearly seventy (70) ways to interpretation the name of Mary.
Mary is a word of unknown origin.
To make a definitive interpretation seems almost unrealistic at the present moment in time.
It is antecedently probable that God should have chosen for Mary a name suitable to her high dignity. What has been said about the form of the name Mary shows that for its meaning we must investigate the meaning of the Hebrew form miryam. Bardenhewer has published a most satisfactory monograph on the subject, in which he explains and discusses about seventy different meanings of the name miryam (Der Name Maria. Geschichte der Deutung desselben. Freiburg, 1895)... Fr. von Hummelauer (in Exod. et Levit., Paris, 1897, p. 161) mentions the possibility that miryam may be of Egyptian origin.
Most interpreters derive the name Mary from the Hebrew, considering it either as a compound word or as a simple. Miryam has been regarded as composed as a noun and a pronominal suffix, or of a noun and an adjective, or again of two nouns. Gesenius was the first to consider miryam as a compound of the noun meri and the pronominal suffix am; this word actually occurs in II Esd., ix, 17, meaning "their rebellion". But such an expression is not a suitable name for a young girl. Gesenius himself abandoned this explanation, but it was adopted by some of his followers.
Here a word has to be added concerning the explanation Stella maris, star of the sea. It is more popular than any other interpretation of the name Mary, and is dated back to St. Jerome (De nomin. hebraic., de Exod., de Matth., P.L., XXIII, col, 789, 842). But the great Doctor of the Church knew Hebrew too well to translate the first syllable of the name miryam by star; in Isaiah 40:15, he renders the word mar by stilla (drop), not stella (star). A Bamberg manuscript dating from the end of the ninth century reads stilla maris instead of stella maris. Since Varro, Quintillian, and Aulus Gelliius testify that the Latin peasantry often substituted an e for an i, reading vea for via, vella for villa, speca for spica, etc., the substitution of maris stella for maris stilla is easily explained. Neither an appeal to the Egyptian Minur-juma (cf. Zeitschr. f. kathol. Theol., IV, 1880, p. 389) nor the suggestion that St. Jerome may have regarded miryam as a contracted form of me'or yam (cf. Schegg, Jacobus der Bruder des Herrn, Munchen, 1882, p. 56 Anm.) will account for his supposed interpretation Stella maris (star of the sea) instead of stilla maris (a drop of the sea).
It was Hiller (Onomasticum sacrum, Tübingen, 1706, pp. 170, 173, 876) who first gave a philological explanation of miryam as a simple word. The termination am is according to this writer a mere formative affix intensifying or amplifying the meaning of the noun. But practically miryam had been considered as a simple noun long before Hiller. Philo (De somn., II, 20; ed. Mangey, II, 677) is said to have explained the word as meaning elpis (hope), deriving the word either from ra'ah (to see, to expect?) or from morash (hope); but as Philo can hardly have seriously believed in such a hazardous derivation, he probably presented Mary the sister of Moses as a mere symbol of hope without maintaining that her very name meant hope. In Rabbinic literature miryam is explained as meaning merum (bitterness; cf. J. Levy, Neuhebraisches und chaldaisches Wörterbuch uber die Talmudim und Midraschim, Leipzig, 1876-89, s.v. merum); but such a meaning of the word is historically improbable, and the derivation of miryam from marar grammatically inadmissible. Other meanings assigned to miryam viewed as a simple word are: bitter one, great sorrow (from marar or marah; cf. Simonis, Onomasticum Veteris Testamenti, Halae Magdeburgicae, 1741, p. 360; Onom. Novi Test., ibid., 1762, p. 106); rebellion (from meri; cf. Gesenius, Thesaur. philol. critic. ling. hebr. et chald. Beter. Testamenti, edit. altera, Lipsiae, 1835-38, II, p. 819b); healed one (cf. Schäfer, Die Gottesmutter in der hl. Schrift, Münster, 1887, pp. 135-144); fat one, well nourished one (from mara; cf. Schegg, Evangelium nach Matthäus, Bd. I, München, 1856, p. 419; id., Jacobus der Bruder des Herrn, München, 1882, p. 56; Furst, Hebr. und chald. Hanwörterb. über d. alte Test., Leipzig, 1857-1861, s.v. miryam); mistress (from mari; cf. v. Haneberg, Geschichte d. biblisch. Offenbarung, 4th edit., Regensburg, 1876, p. 604); strong one, ruling one (from marah; cf. Bisping, Erklärung d. Evang. nach Matth., Münster, 1867, p. 42); gracious or charming one (from ra'am which word does not have this meaning in the Old Testament; cf. v. Haneberg, 1, c.); myrrh (from mor, though it does not appear how this word can be identified with miryam; cf. Knabenbauer, Evang. sec. Matth., pars prior, Parisiis, 1892, p. 44); exalted one (from rum; cf. Caninius, De locis S. Scripturae hebraicis comment., Antverpiae, 1600, pp. 63-64).
In 1906 Zorrell advanced another explanation of the name Mary, based on its derivation from the Egyptian mer or mar, to love, and the Hebrew Divine name Yam or Yahweh (Zeitschrift für katholische Theologie, 1906, pp. 356 sqq.). Thus explained the name denotes "one loving Yahweh" or "one beloved by Yahweh". We have already pointed out the difficulty implied in an Egyptian origin of the name Mary. Probably it is safer to adhere to Bardenhewer's conclusions (l. c., pp. 154 sq.): Mariam and Maria are the later forms of the Hebrew miryam; miryam is not a compound word consisting of two nouns, or a noun and an adjective, or a noun and a pronominal suffix, but it is a simple though derivative noun; the noun is not formed by means of a prefix (m), but by the addition of a suffix (am). Presupposing these principles, the name miryam may be derived either from marah, to be rebellious, or from mara, to be well nourished. Etymology does not decide which of these derivations is to be preferred; but it is hardly probable that the name of a young girl should be connected with the idea of rebellion, while Orientals consider the idea of being well nourished as synonymous with beauty and bodily perfection, so that they would be apt to give their daughters a name derived from mara Mary means therefore The beautiful or The perfect one. - The Name of Mary
Yona Sabar a professor of Hebrew and Aramaic in the department of Near Eastern Languages & Cultures at UCLA adds this to the subject:
The name’s origin seems to be Egyptian, meaning “wished-for child,” derived from myr (“beloved”) or mr (“love”).
More traditional explanations (as by Rashi) include the Hebrew mar (“bitter”) or meri (“rebellion”), signifying the bitter slavery in Egypt and the wish to rebel.
Variations of the name include Maryam (Greek-Christian; Arabic-Islamic), Maria (Latin), Maliah (Hawaiian), Mary (English, Christian, but occasionally Jewish, as well), Mira/Miri/Mimi (Israeli), Mirele (Yiddish) and combinations such as Marianna, Mary Kay, etc. Even Mayim (best known for actress Mayim Bialik) is a variant of Miriam. - Hebrew word of the week: Miriam
| {
"pile_set_name": "StackExchange"
} |
Q:
Как уменьшить звук audio html
Есть автовоспроизведение звука на сайте
<audio controls src="bgsound.mp3" autoplay="autoplay"></audio>
Как уменьшить громкость звука без участия пользователя. Звук очень громкий, потому надо его сделать потише по умолчанию.
A:
Воспользуйтесь свойством volume, у элемента audio
var audio=document.querySelector("audio");
audio.volume=0.5;
| {
"pile_set_name": "StackExchange"
} |
Q:
error: expression must have integral or enum type
In CUDA C, why does the following code
findMinMax<<sizeof(lum)/1024,1024>>(lum,&min_logLum,&max_logLum);
give this error?
error: expression must have integral or enum type
A:
You need to use triple angled brackets as part of kernel launch syntax:
findMinMax<<<sizeof(lum)/1024,1024>>>(lum,&min_logLum,&max_logLum);
That should resolve compilation error, provided the rest is correct (e.g., the set of arguments matches the kernel prototype).
Note that a few other things are suspicious in the way you launch the kernel:
You round the number of blocks per grid down instead of up. For example, if sizeof(lum) evaluates to 1500, you still launch only 1 block of 1024 threads. This may not be what you intend to do.
You pass host pointers &min_logLum and &max_logLum to the kernel, which, again, may be not what you intend to do here, however it is hard to tell without seeing the rest of your code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Numpy, change array's row value , each row satisfy different conditions
I have a 2d array, it has huge number of rows(lager than 5000).
For the sake of simplicity,assume A is a simple version of my matrix
A=([[1,2,2,3,3,3],
[[2,1,1,7,7,7],
[[4,4,1,1,1,1]])
Now, A only has 3 rows:
the 1st row has 3 values: one 1, two 2,three 3.
the 2nd row has 3 values, one 2, two 1,three 7.
the last row has 2 values, two 4, four 1.
now I can easily find the majority value for each row:
1st row is 3, 2nd row is 7, 3rd row is 1. (means my code already find each rows majority value and store them as [3,7,1] )
the second and third majority value for each row is also easy to find,for the second majority value, 1st row is 2, 2nd is 1, 3rd is 4. (means my code already find each rows second majority value and store them as [2,1,4] ).
For third,forth,fifth...majority value, still easy to find.
what I want to do is set each rows 1st majority value to 0, 2nd majority value to -1, 3rd majority(if exist) value to -2 ...., how to do this?
means set:
A=([[-2,-1,-1,0,0,0],
[[-2,-1,-1,0,0,0],
[[-1,-1,0,0,0,0]])
A is just a simple instance.My matrix has huge number of rows.
So, how to do this thing more easily and efficiently?
I don't want to write a for loop to set the value for each row.
(means i can do A[0,A[0,:]==3]=0, A[1,A[1,:]==7]=0, A[2,A[2,:]==1]=0,but this is too complicated)
what I want is a form like this:
A[:,A[:,:]==[3,7,1]]=0
A[:,A[:,:]==[2,1,4]]=-1
A[:,A[:,:]==[1,2]]=-2
but numpy doesn't has this ability.
Can any one give me an efficient method for this? thank u very much!!!
A:
Here's one method -
# https://stackoverflow.com/a/46256361/ @Divakar
def bincount2D_vectorized(a):
N = a.max()+1
a_offs = a + np.arange(a.shape[0])[:,None]*N
return np.bincount(a_offs.ravel(), minlength=a.shape[0]*N).reshape(-1,N)
binsum = bincount2D_vectorized(A)
m,n = A.shape[0],binsum.shape[1]
index = np.empty((m,n), dtype=int)
sort_idx = binsum.argsort(1)[:,::-1]
index[np.arange(m)[:,None], sort_idx] = np.arange(0,-n,-1)
out = index[np.arange(m)[:,None],A]
| {
"pile_set_name": "StackExchange"
} |
Q:
Does findAllBy return a sorted list?
Does findAllBy return a sorted list? I could not find any information in the Grails documentation about this. Assuming I have a class like so:
class Something {
int sortOrder
String label
static belongsTo = [ somethingElse: SomethingElse]
static mappedBy = [somethingElse: SomethingElse]
static mapping = {
tablePerHierarchy false
sort "sortOrder"
}
static constraints = {
}
}
Does Something.findAllBySomethingElse(somethingElse) return a list that is sorted by "sortOrder"? It's strange but my unit tests says no whereas my grails app (when i do run-app) displays the list in sorted order. I had to explicitly use findAllBySomethingElse(somethingElse, [sort: "sortOrder"]) to enable my unit tests (i.e. checking sort order) to pass.
A:
It does return a sorted list. But not in Unit Tests. They are not intended for such things, but can be extended to some degree. See the unit test documentation.
| {
"pile_set_name": "StackExchange"
} |
Q:
F# Checked Arithmetics Scope
F# allows to use checked arithmetics by opening Checked module, which redefines standard operators to be checked operators, for example:
open Checked
let x = 1 + System.Int32.MaxValue // overflow
will result arithmetic overflow exception.
But what if I want to use checked arithmetics in some small scope, like C# allows with keyword checked:
int x = 1 + int.MaxValue; // ok
int y = checked { 1 + int.MaxValue }; // overflow
How can I control the scope of operators redefinition by opening Checked module or make it smaller as possible?
A:
You can always define a separate operator, or use shadowing, or use parens to create an inner scope for temporary shadowing:
let f() =
// define a separate operator
let (+.) x y = Checked.(+) x y
try
let x = 1 +. System.Int32.MaxValue
printfn "ran ok"
with e ->
printfn "exception"
try
let x = 1 + System.Int32.MaxValue
printfn "ran ok"
with e ->
printfn "exception"
// shadow (+)
let (+) x y = Checked.(+) x y
try
let x = 1 + System.Int32.MaxValue
printfn "ran ok"
with e ->
printfn "exception"
// shadow it back again
let (+) x y = Operators.(+) x y
try
let x = 1 + System.Int32.MaxValue
printfn "ran ok"
with e ->
printfn "exception"
// use parens to create a scope
(
// shadow inside
let (+) x y = Checked.(+) x y
try
let x = 1 + System.Int32.MaxValue
printfn "ran ok"
with e ->
printfn "exception"
)
// shadowing scope expires
try
let x = 1 + System.Int32.MaxValue
printfn "ran ok"
with e ->
printfn "exception"
f()
// output:
// exception
// ran ok
// exception
// ran ok
// exception
// ran ok
Finally, see also the --checked+ compiler option:
http://msdn.microsoft.com/en-us/library/dd233171(VS.100).aspx
A:
Here is a complicated (but maybe interesting) alternative. If you're writing something serious then you should probably use one of the Brians suggestions, but just out of curiosity, I was wondering if it was possible to write F# computation expression to do this. You can declare a type that represents int which should be used only with checked operations:
type CheckedInt = Ch of int with
static member (+) (Ch a, Ch b) = Checked.(+) a b
static member (*) (Ch a, Ch b) = Checked.(*) a b
static member (+) (Ch a, b) = Checked.(+) a b
static member (*) (Ch a, b) = Checked.(*) a b
Then you can define a computation expression builder (this isn't really a monad at all, because the types of operations are completely non-standard):
type CheckedBuilder() =
member x.Bind(v, f) = f (Ch v)
member x.Return(Ch v) = v
let checked = new CheckedBuilder()
When you call 'bind' it will automatically wrap the given integer value into an integer that should be used with checked operations, so the rest of the code will use checked + and * operators declared as members. You end up with something like this:
checked { let! a = 10000
let! b = a * 10000
let! c = b * 21
let! d = c + 47483648 // !
return d }
This throws an exception because it overflows on the marked line. If you change the number, it will return an int value (because the Return member unwraps the numeric value from the Checked type). This is a bit crazy technique :-) but I thought it may be interesting!
(Note checked is a keyword reserved for future use, so you may prefer choosing another name)
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I complete the fourth maze in the garden of the Parfum Palace?
I want to know how to complete the fourth maze in the garden of the Parfum Palace in Pokemon Y. I know how to complete the first three mazes in the garden but the fourth one is a mystery.
Could anyone please tell me how to solve the fourth maze?
A:
From Cherrygrove on psypoke forums:
Refer to the image above.
At the start of the puzzle, Furfrou will be in Square 2. Ask Shauna to
wait in Square 1. Next, take the red path from Square 1 to Square 2.
Furfrou will run to Square 3. Take Shauna to Square 2 and ask her to
wait there. Finally, take the Blue path from Square 2 to Square 3 and
Furfrou will be trapped.
I hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
In Meteor Methods this.connection is always undefined
I am trying to implement some methods for a DDP API, for use with a C# remote client.
Now, I want to be able to track the connection to implement some type of persistent session, to this end, id hope to be able to use the session id given by DDP on connection, example:
{
"msg": "connected",
"session": "CmnXKZ34aqSnEqscR"
}
After reading the documentation, I see that inside meteor methods, I can access the current connection using "this.connection", however, I always get an undefined "this.connection".
Was it removed? If so, how can i access it now?
PS: I dont want to login as a user and access this.userId, since the app I want to create should not login, but actually just get a document id and do work associated with that, including changes to other collections, but all, regarding ONLY this id, and I dont want to have to include this id every time I call a function, since, this could possibly lead security problems if anyone can just send any id. The app would ideally do a simple login, then associate token details with his "session".
A:
I was using a file named ".next.js" to force meteor to use the newest unsupported javascript spec using a package.
Somehow this messed it up. Changed back to default javascript and it now works.
Thank you :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Optimize cassandra query
I'm in a try to optimize some cassandra queries which I use the row key as the criteria.
So my doubt is, considering the process of comparing the row key inside cassandra, what would be the best 'key_validation_class' for it?
Does the UTF8Type have a worse performance than Int32Type?
At now, I'm using some concatenated values in order to create my row key as UTF8Type, but i'm kind afraid it be a bad approach.
Thanks in advance.
A:
key_validation_class is just a convenient hint to cassandra to enforce validation criteria on a key. Think of it as constrain. Cassandra works internally with bytes only. This is unlikely to cause any performance issues.
Size of the "key name" is generally not an issue as long it's within reasonable limits (let's say 64-128 bytes is absolutely normal).
Decision if it's better to use UTF or Int32 is mostly driven by need to partition data and perform range slices.
Cassandra's main strength is lookup by a key - so don't worry about the key name at the beginning. Spend more time designing columns where right design decisions will pay off.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do I get different python version for implicit and explicit localhost
I have both python2.7 and python3.7 in my mac and ansible is installed using python3.
Python version and ansible version returns below:
$ python -V
Python 2.7.16
$
$ /usr/bin/env python -V
Python 2.7.16
$
$ /usr/bin/python -V
Python 2.7.16
$
$ ansible --version
ansible 2.9.7
config file = None
configured module search path = ['/Users/demo/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /Users/demo/Library/Python/3.7/lib/python/site-packages/ansible
executable location = /Users/demo/Library/Python/3.7/bin/ansible
python version = 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)]
Also have an inventory hosts with explicit localhost configuration.
localhost ansible_connection=local
I understand that setting ansible_python_interpreter for the inventory will use the specific version but wondering why I get two different python versions for below cases that use either implicit or explicit localhost. My understanding was that for both cases ansible will use the default python version.
$ ansible localhost -m setup | grep ansible_python_version
[WARNING]: No inventory was parsed, only implicit localhost is available
"ansible_python_version": "3.7.3",
$
$ ansible localhost -i hosts -m setup | grep ansible_python_version
[WARNING]: Platform darwin on host localhost is using the discovered Python interpreter at /usr/bin/python, but future installation of another Python
interpreter could change this. See https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
"ansible_python_version": "2.7.16",
A:
The answer is in the documentation
when Ansible needs to contact a ‘localhost’ but you did not supply one, we create one for you. This host is defined with specific connection variables equivalent to this in an inventory:
hosts:
localhost:
vars:
ansible_connection: local
ansible_python_interpreter: "{{ansible_playbook_python}}"
As you can see the implicit localhost declaration is defining an ansible_python_interpreter pointing to the one used by the current playbook on the controller (i.e. ansible_playbook_python documented in Ansible special variables)
The explicit localhost definition you posted does not define any and uses auto-discovery.
| {
"pile_set_name": "StackExchange"
} |
Q:
"What more" vs "what else" do you need?
I am providing you with food, shelter, clothes.
What more do you need
or
what else do you need?
Which one's correct?
A:
Both more and else are syntactically fine in OP's example, and in many contexts they'll mean exactly the same thing.
But note that idiomatically, What more do you need? is far more likely when what's being asked is effectively a rhetorical question (implying the speaker thinks you either don't or shouldn't need anything else).
Also note that when using else, to some extent the distinction between a rhetorical question and a genuine enquiry can be made more explicit by stress/emphasis...
1: What else do you need? (Probably: You don't need anything else - just get on with it)
2: What else do you need? (Probably: If you need anything else please tell me)
A:
In the context you have given, can mean different things.
What more do you need?
Can be taken as for example - "Isn't what is given enough? What else possibly could you need" implying that what is given should suffice.
What else do you need?
Can be taken as for example - "What are the other necessities that I can provide to you? What other requirements do you have?"
A:
You can say : What more do you need? (When you are really vexed up with that one)
You can say : What else do you need? (when you were really happy to help him, and you were asking do you need something more(Soft Tone) )
As far as I known.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set base class the values in the derived constructor
So I got this base class
abstract class Item
{
private int x, y, ataque, defesa, saude, raridade;
private char appearance;
private bool pickedUp;
private readonly Random rng = new Random();
public Item(Map argMap, int argAtaque, int argDefesa, int argSaude, int argRaridade, char argAppearance)
{
bool empty = false;
while (!empty)
{
x = rng.Next(1, argMap.ReLengthX() - 1);
y = rng.Next(1, argMap.ReLengthY() - 1);
if (!argMap.CheckTile(y, x)) empty = true;
}
pickedUp = false;
ataque = argAtaque;
defesa = argDefesa;
saude = argSaude;
raridade = argRaridade;
appearance = argAppearance;
}
}
And I got this derived class
class Armadura : Item
{
public Armadura(Map argMap, int ataque, int defesa, int saude, int raridade, char appearance) : base(argMap, ataque, defesa, saude, raridade, appearance)
{
ataque = -1;
defesa = 2;
saude = 0;
raridade = ReRNG().Next(Convert.ToInt32(Math.Round(argMap.ReLengthY() * 0.02)), Convert.ToInt32(Math.Round(argMap.ReLengthY() * 0.04)));
appearance = ' ';
}
}
So my question is, how do I get to set the values on :base, using the values that I set on the derived constructor (for example, set the base argAtaque with ataquewwww, therefore, argAtaque being equal to '-1')?
I tried this using a few ways but I didn't get this to work in any way.
I thank you in advance!
A:
The : base() syntax will work for constants and parameters, but not for more complex expressions with side-effects (as you found).
You'll be needing a initialization method on the base class.
abstract class Item
{
...
// If you use this constructor, call Setup() afterwards.
public Item() {}
// Constructor including a call to Setup()
public Item(Map argMap, int argAtaque, int argDefesa, int argSaude, int argRaridade, char argAppearance)
{
Setup(argMap, argAtaque, argDefesa, argSaude, argRaridade, argAppearance);
}
// Sets private variables for this Item
protected void Setup(Map argMap, int argAtaque, int argDefesa, int argSaude, int argRaridade, char argAppearance)
{
bool empty = false;
while (!empty)
{
x = rng.Next(1, argMap.ReLengthX() - 1);
y = rng.Next(1, argMap.ReLengthY() - 1);
if (!argMap.CheckTile(y, x)) empty = true;
}
pickedUp = false;
ataque = argAtaque;
defesa = argDefesa;
saude = argSaude;
raridade = argRaridade;
appearance = argAppearance;
}
}
Now you can setup the base class with the calculated values:
class Armadura : Item
{
public Armadura(Map argMap)
{
int ataque = -1;
int defesa = 2;
int saude = 0;
int raridade = ReRNG().Next(Convert.ToInt32(Math.Round(argMap.ReLengthY() * 0.02)), Convert.ToInt32(Math.Round(argMap.ReLengthY() * 0.04)));
char appearance = ' ';
Setup(argMap, ataque, defesa, saude, raridade, appearance);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert epoch time with moment.js in javascript
I'm already check this Using momentjs to convert date to epoch then back to date but it still cannot solve my problem.
Before I'm used moment.js, I'm just converted my epoch time like this
Scenario 1: Without moment.js
var val = 62460;
var selected_time = new Date(val * 1000);
console.log('Selected epoch is : ', val, 'and the time is ', selectedTime.getUTCHours(), ':', selectedTime.getUTCMinutes(), 'in UTC');
My console log shown like this
Selected epoch is : 62460 and the time is 17 : 21 in UTC
Scenario 2: With moment.js
var val = 62460;
var selected_time = moment(val).format('hh:mm:ss');
console.log('Selected epoch is : ', val, 'and the time is ', selected_time);
My console log shown like this
Selected epoch is : 62460 and the time is 08:01:02 in UTC
The correct time is 17:21:00.
Thanks.
A:
In the first scenario, you are multiplying by 1000, you forgot that in the second case.
var val = 62460
var selected_time = moment(val*1000).utc().format('hh:mm:ss');
Also, by default, MomentJS parses in local time. So you need to explicitly convert it to UTC.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I prompt for user input in AutoHotkey?
I'm writing an AutoHotkey script which needs to retrieve typed user input as a string. (Username, password, filename, etc.)
How do I retrieve user input with AutoHotkey?
A:
You can use AutoHotkey's built in InputBox.
InputBox, UserInput, Enter Name, Please enter a username:, , 300, 150
MsgBox, You entered %UserInput% as your username
Here's an excerpt from the InputBox documentation
InputBox
Displays an input box to ask the user to enter a string.
InputBox, OutputVar [, Title, Prompt, HIDE, Width, Height, X, Y, Font, Timeout, Default]
Remarks
The dialog allows the user to enter text and then press OK or CANCEL. The user can resize the dialog window by dragging its borders.
Example
InputBox, password, Enter Password, (your input will be hidden), hide
InputBox, UserInput, Phone Number, Please enter a phone number., , 640, 480
if ErrorLevel
MsgBox, CANCEL was pressed.
else
MsgBox, You entered "%UserInput%"
Source: Autohotkey documentation for InputBox
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make only eventSources droppable into FullCalendar?
i use FullCalendar and i call my Event with eventSources and ajax like this :
eventSources:
[
{
url: 'ajax.php',
type: 'POST',
data: {
obj: 'Event'
},
error: function() {
alert('there was an error while fetching events!');
}
},
],
the Return JSON Code look like this :
[{"id":"1","name":"Event One","town":"London","start":"2011-05-10","url":"","title":"Event One","className":"Event_class","description":"Hier some description","color":"#D42993","draggable":"false"},{another Events}]
So far it's all good, then i tried to make just those event Droppable(not the Calendar), so that i can drag an external object into it(for example a "Manager").
I change the eventSources in this way but it dont work :
eventSources:
[
{
url: 'ajax.php',
type: 'POST',
data: {
obj: 'Event'
},
error: function() {
alert('there was an error while fetching events!');
},
textColor: 'black',
disableDragging: true,
cache: true,
dropAccept: '.Personal',
droppable : true,
eventDrop: function(e, ui){ alert("drop")}
},
],
Can Someone Help me on this One? Thank you!
A:
I found it! just use eventRender like this :
eventSources:
[
{
url: 'ajax.php',
type: 'POST',
...
dropAccept: '.myClass',//class of my external elts
droppable : true
},
],
droppable: false, //make the rest of our Calendar not droppable
eventRender:
function(event, element) {//Our events -> from eventSources
element.droppable({//make only my events droppable
accept: '.myClass',//my external elts
activeClass: 'droppable-active',
hoverClass: 'droppable-hover',
drop: function(e, ui){ }//Actions
})
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ImageMagick OSX Snow Leopard bad CPU type
Installing imagemagick works.
But when I try to run a command it says bad cpu type.
What is this and how do I get rid of it so that it works right?
N.b. I'm 'behind the times' and only using a core solo (if that helps)
A:
It sounds like you may have a 64-bit build of imagemagick which you're trying to run on a 32-bit only CPU. As Greg noted, running the file command on it will confirm this; it will show you something like this:
styrone$ file /usr/local/bin/imagemagick
/usr/local/bin/imagemagick: Mach-O universal binary with 2 architectures
/usr/local/bin/imagemagick (for architecture x86_64): Mach-O 64-bit executable x86_64
/usr/local/bin/imagemagick (for architecture i386): Mach-O executable i386
If you don't see a line with "(for architecture i386)", that's your problem. You'll need to get a build that supports 32-bit Intel.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error installing mysqlclient with MariaDB 10.2
I have both installed python_devel and mysql_devel (that is MariaDB devel) still I get a file not found error when installing mysqlclient with pip:
Package python-devel-2.7.5-48.el7.x86_64 already installed and latest version
Package MariaDB-devel-10.2.8-1.el7.centos.x86_64 already installed and latest version
Nothing to do
root@host [~]# pip install mysqlclient
Collecting mysqlclient
Using cached mysqlclient-1.3.10.tar.gz
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient ... error
Complete output from command /usr/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-WQf5SH/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-moASQ3-record/install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.7
copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7
creating build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/compat.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb
creating build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.linux-x86_64-2.7
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,3,10,'final',0) -D__version__=1.3.10 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o
_mysql.c:29:23: fatal error: my_config.h: No such file or directory
#include "my_config.h"
^
compilation terminated.
error: command 'gcc' failed with exit status 1
----------------------------------------
Command "/usr/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-WQf5SH/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-moASQ3-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-WQf5SH/mysqlclient/
r
While maria and mysql headers are there that file is not:
root@host [~]# ls -al /usr/include/mysql
total 188
drwxr-xr-x 5 root root 4096 Aug 23 02:39 ./
drwxr-xr-x 71 root root 12288 Aug 23 16:48 ../
-rw-r--r-- 1 root root 3527 Aug 17 06:05 errmsg.h
-rw-r--r-- 1 root root 1602 Aug 17 06:05 ma_list.h
-rw-r--r-- 1 root root 4329 Aug 17 06:05 ma_pvio.h
-rw-r--r-- 1 root root 4111 Aug 17 06:05 ma_tls.h
drwxr-xr-x 2 root root 4096 Aug 23 02:39 mariadb/
-rw-r--r-- 1 root root 17223 Aug 17 06:05 mariadb_com.h
-rw-r--r-- 1 root root 2593 Aug 17 06:05 mariadb_ctype.h
-rw-r--r-- 1 root root 8199 Aug 17 06:05 mariadb_dyncol.h
-rw-r--r-- 1 root root 11227 Aug 17 06:05 mariadb_stmt.h
-rw-r--r-- 1 root root 852 Aug 17 06:11 mariadb_version.h
drwxr-xr-x 2 root root 4096 Aug 23 02:39 mysql/
-rw-r--r-- 1 root root 40532 Aug 17 06:05 mysql.h
-rw-r--r-- 1 root root 43551 Aug 17 06:15 mysqld_error.h
drwxr-xr-x 4 root root 4096 Aug 23 02:39 server/
root@host [~]# ls -al /usr/include/mysql/mariadb
total 12
drwxr-xr-x 2 root root 4096 Aug 23 02:39 ./
drwxr-xr-x 5 root root 4096 Aug 23 02:39 ../
-rw-r--r-- 1 root root 1619 Aug 17 06:05 ma_io.h
root@host [~]# ls -al /usr/include/mysql/mysql
total 28
drwxr-xr-x 2 root root 4096 Aug 23 02:39 ./
drwxr-xr-x 5 root root 4096 Aug 23 02:39 ../
-rw-r--r-- 1 root root 8560 Aug 17 06:05 client_plugin.h
-rw-r--r-- 1 root root 3793 Aug 17 06:05 plugin_auth.h
-rw-r--r-- 1 root root 3873 Aug 17 06:05 plugin_auth_common.h
root@host [~]# ls -al /usr/include/mysql/server/
total 656
drwxr-xr-x 4 root root 4096 Aug 23 02:39 ./
drwxr-xr-x 5 root root 4096 Aug 23 02:39 ../
-rw-r--r-- 1 root root 4507 Aug 17 06:05 big_endian.h
-rw-r--r-- 1 root root 5196 Aug 17 06:05 byte_order_generic.h
-rw-r--r-- 1 root root 4239 Aug 17 06:05 byte_order_generic_x86.h
-rw-r--r-- 1 root root 4089 Aug 17 06:05 byte_order_generic_x86_64.h
-rw-r--r-- 1 root root 4667 Aug 17 06:05 decimal.h
-rw-r--r-- 1 root root 4363 Aug 17 06:05 errmsg.h
-rw-r--r-- 1 root root 4441 Aug 17 06:05 handler_ername.h
-rw-r--r-- 1 root root 758 Aug 17 06:05 handler_state.h
-rw-r--r-- 1 root root 13184 Aug 17 06:05 json_lib.h
-rw-r--r-- 1 root root 8827 Aug 17 06:05 keycache.h
-rw-r--r-- 1 root root 3574 Aug 17 06:05 little_endian.h
-rw-r--r-- 1 root root 47238 Aug 17 06:05 m_ctype.h
-rw-r--r-- 1 root root 7745 Aug 17 06:05 m_string.h
-rw-r--r-- 1 root root 7838 Aug 17 06:05 ma_dyncol.h
-rw-r--r-- 1 root root 1944 Aug 17 06:05 my_alloc.h
-rw-r--r-- 1 root root 2208 Aug 17 06:05 my_attribute.h
-rw-r--r-- 1 root root 1980 Aug 17 06:05 my_byteorder.h
-rw-r--r-- 1 root root 4236 Aug 17 06:05 my_compiler.h
-rw-r--r-- 1 root root 14716 Aug 17 06:12 my_config.h
-rw-r--r-- 1 root root 8543 Aug 17 06:05 my_dbug.h
-rw-r--r-- 1 root root 2075 Aug 17 06:05 my_decimal_limits.h
-rw-r--r-- 1 root root 3900 Aug 17 06:05 my_dir.h
-rw-r--r-- 1 root root 5578 Aug 17 06:05 my_getopt.h
-rw-r--r-- 1 root root 34520 Aug 17 06:05 my_global.h
-rw-r--r-- 1 root root 1506 Aug 17 06:05 my_list.h
-rw-r--r-- 1 root root 2104 Aug 17 06:05 my_net.h
-rw-r--r-- 1 root root 27489 Aug 17 06:05 my_pthread.h
-rw-r--r-- 1 root root 42655 Aug 17 06:05 my_sys.h
-rw-r--r-- 1 root root 1982 Aug 17 06:05 my_valgrind.h
-rw-r--r-- 1 root root 2832 Aug 17 06:05 my_xml.h
drwxr-xr-x 3 root root 4096 Aug 23 02:39 mysql/
-rw-r--r-- 1 root root 39711 Aug 17 06:05 mysql.h
-rw-r--r-- 1 root root 28765 Aug 17 06:05 mysql_com.h
-rw-r--r-- 1 root root 1313 Aug 17 06:05 mysql_com_server.h
-rw-r--r-- 1 root root 1167 Aug 17 06:05 mysql_embed.h
-rw-r--r-- 1 root root 2420 Aug 17 06:05 mysql_time.h
-rw-r--r-- 1 root root 1021 Aug 17 06:12 mysql_version.h
-rw-r--r-- 1 root root 117146 Aug 17 06:15 mysqld_ername.h
-rw-r--r-- 1 root root 43551 Aug 17 06:15 mysqld_error.h
-rw-r--r-- 1 root root 1105 Aug 17 06:05 pack.h
drwxr-xr-x 3 root root 12288 Aug 23 02:39 private/
-rw-r--r-- 1 root root 5508 Aug 17 06:05 sql_common.h
-rw-r--r-- 1 root root 14602 Aug 17 06:15 sql_state.h
-rw-r--r-- 1 root root 1350 Aug 17 06:05 sslopt-case.h
-rw-r--r-- 1 root root 2534 Aug 17 06:05 sslopt-longopts.h
-rw-r--r-- 1 root root 1367 Aug 17 06:05 sslopt-vars.h
-rw-r--r-- 1 root root 2463 Aug 17 06:05 typelib.h
A:
Finally this is fixed in the devel branch of mysqlclient but not yet released, it was due to a recent change in MariaDB 10.2.8 that does change the location of the server headers to a /server folder to avoid colliding headers from server and client.
| {
"pile_set_name": "StackExchange"
} |
Q:
"Главное что" как-либо обособляется?
Мы в очередной раз забыли, что кварталы Рима – это понятие обширное и
главное что непредсказуемое.
"Что" хочу сохранить, а оно мне мешает выделить "главное".
Ооо... Запятую?
...это понятие обширное и главное, что непредсказуемое.
Ну и получилось: обширное и главное... 8-(
A:
А если так:
Мы в очередной раз забыли, что кварталы Рима – это понятие обширное, а главное, что (оно) непредсказуемое.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why Can't My Android App Update The Database? (Running)
I am creating an activity that will update the table "patients" in my database.
When I tried removing the conditions with $_POST method in php and tried putting temporary content on the variables, the result was successful. But when I put the $_POST method again, and run my android app, the result was unsuccessful. Please help me figure it out. Thank you.
This is the code, I'm creating a security questions activity:
import android.os.AsyncTask; import
android.support.v7.app.ActionBarActivity; import android.os.Bundle;
import android.util.Log; import android.view.Menu; import
android.view.MenuItem; import android.widget.ArrayAdapter; import
android.widget.Spinner; import android.widget.EditText; import
android.widget.Button; import android.view.View; import
android.content.Intent; import android.widget.Toast;
import org.json.JSONException; import org.json.JSONObject;
import java.util.HashMap;
public class Securityquestion_Activity extends ActionBarActivity {
Spinner question;
EditText answer;
Button submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_securityquestion_);
question = (Spinner)findViewById(R.id.securityQuestion);
answer = (EditText)findViewById(R.id.securityAnswer);
submit = (Button)findViewById(R.id.submit);
String[] questions = {
"What's the name of your first pet?",
"Where's your place of birth?",
"What's the sum of your birth date and month?",
"What's your father's middle name?",
"What's the surname of your third grade teacher?",
"Who's your first boyfriend/girlfriend?",
"Who's your first kiss?",
};
ArrayAdapter<String> stringArrayAdapter=
new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item,
questions);
question.setAdapter(stringArrayAdapter);
}
public void submit(View v){
String secquestion = question.getSelectedItem().toString();
String secanswer = answer.getText().toString();
Bundle extras = getIntent().getExtras();
String secID;
if(extras!=null){
secID = extras.getString("sec_id");
String[] args = {secquestion, secanswer, secID};
SaveSecurity saveSecurity = new SaveSecurity();
saveSecurity.execute(args);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_securityquestion_, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class SaveSecurity extends AsyncTask<String, String, JSONObject>{
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.56.1/dc/security.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("secquestion", args[0]);
params.put("secanswer", args[1]);
params.put("secID", args[2]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(JSONObject json) {
int success = 0;
String message = "";
if (json != null) {
Toast.makeText(Securityquestion_Activity.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
success = json.getInt(TAG_SUCCESS);
message = json.getString(TAG_MESSAGE);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (success == 1) {
Log.d("Success!", message);
Intent go = new Intent(Securityquestion_Activity.this, Home_Activity.class);
go.putExtra("all_ID","secID");
finish();
startActivity(go);
}
else if (success == 0) {
Log.d("Failure", message);
}
else{
Log.d("Failure", message);
}
}
}
}
This is the php code:
<?php
require_once 'connection.php';
header('Content-Type: application/json');
//This method here was the one I mentioned above
if(isset($_POST["secquestion"])&& isset($_POST["secanswer"])&& isset($_POST["secID"])){
//These are the variables I tried temporarily changing it's content when I tested the php
$ptnt_d = $_POST["secID"];
$scrty_qstn = $_POST["secquestion"];
$scrty_nswr = $_POST["secanswer"];
if(!empty($ptnt_d)&&!empty($scrty_qstn)&&!empty($scrty_nswr)){
$query = "Update patients Set patientsecurity='$scrty_qstn' and patientanswer='$scrty_nswr' WHERE patientid='$ptnt_d'";
$result = $db->query($query);
if($result){
$json['success']=1;
$json['message']="Security question and answer successfully saved.";
echo json_encode($json);
}
else{
$json['success']=0;
$json['message']="Oops! An error occurred.";
echo json_encode($json);
}
}
else{
$json['message']="You must complete all required fields.";
echo json_encode($json);
}
}
?>
A:
You aren't sanitizing your sql query properly:
Update patients Set patientsecurity='What's the name of your first pet?' and patientanswer='Bachoy' WHERE patientid='007-7992'"
Try doing something like $field = mysql_real_scape($_POST['field']);
| {
"pile_set_name": "StackExchange"
} |
Q:
WebService PHP+JSON - Como ler retorno
Ola!
Pessoal, gostaria de entender como ler o retorno, com a seguinte estrutura:
$ws = array(
'categoria' => array(
array(
'cat1' => array(
'dado1' => $dado1,
'dado2'=>$dado2
),
'subcategoria'=>array(
'dado3'=>$dado3,
'dado4'=>$dado4,
)
),
),
);
$json = json_encode($ws, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
$url = 'https://link.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Length: ' . strlen($json),
"Content-Type: application/json",
));
$jsonRet = curl_exec($ch);
curl_close($ch);
Com o código acima realizo o envio. Agora como faço para extrair individualmente os dados de retorno?
Ele vem nesse formato:
{"data":{"nome1":João,"status":["ativo"]}}
Quero poder interpretar somente o status, ou o nome1, separadamente com php.
A:
$retorno = json_decode($jsonRet);
$status = $retorno->data->status;
| {
"pile_set_name": "StackExchange"
} |
Q:
What is changing the char values inside my C string?
Something in my code is mysteriously replacing all the chars inside my const char *(the string upper, inside foo_add()) with garbage values. It seems to happen right after the call to malloc in foo_add(). I set breakpoints in Xcode inside the function, and upper is fine right before the malloc call, but filled with random values afterword. I'm a complete C newbie, so it's entirely possible there's something I'm doing that has some side effect I'm not aware of. I don't know if it's related to malloc or not, and I can't see why it would be. Code below. I added comments to show where the problem occurs.
//in Foo.h
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
typedef struct Foo {
struct Foo * members[26] ;
} Foo ;
const char * toUpper(const char * in) ;
const char * getSubstring(const char * str, size_t startingIndex) ;
void foo_init(Foo * f) ;
void foo_add(Foo * f, const char * str) ;
//in Foo.c
#include "Foo.h"
const char * toUpper(const char * in) {
size_t length = strlen(in) ;
char temp[length + 1] ;
for (size_t i = 0 ; i < length; i++) {
temp[i] = toupper(in[i]) ;
}
temp[length] = '\0' ;
char * out = temp ;
return out ;
}
const char * getSubstring(const char * str, size_t startingIndex) {
size_t size = (unsigned)(strlen(str) - startingIndex) ;
char temp[size + 1] ; //+1 for '\0' (terminating char)
for (size_t i = 0 ; i < size ; i++) {
temp[i] = str[i + startingIndex] ;
}
temp[size] = '\0' ;
const char * ret = temp ;
return ret ;
}
void foo_init(Foo * f) {
for (size_t i = 0 ; i < 26 ; i++) {
f->members[i] = NULL ;
}
}
void foo_add(Foo * f, const char * str) {
const char * upper = toUpper(str) ;
int index = ((int)upper[0]) - 65 ;
size_t length = strlen(str) ;
if (length > 0) {
if (f->members[index] == NULL) {
/* debugger says upper = "ABCXYZ" here, which is expected */
f->members[index] = (Foo *)malloc(sizeof(Foo)) ;
/* set another debugger breakpoint here - upper is now filled with garbage values */
}
/* take substr and call recursively until length == 0 */
const char * next = getSubstring(upper, 1) ;
foo_add(f->members[index], next) ;
}
}
//in main.c
#include <stdio.h>
#include "Foo.h"
int main(int argc, const char * argv[])
{
Foo f ;
foo_init(&f) ;
const char * str = "abcxyz" ;
foo_add(&f, str) ;
return 0;
}
A:
The culprit is this code:
const char * function(const char * in) {
char temp[..];
char *out = temp;
return out;
}
Here, temp is allocated on stack, not on heap. This means that its lifetime ends when the scope of the function exits. You should either allocate it dynamically on heap with, for example, char *temp = calloc(length+1, 1) or pass it from the called on a preallocated space (which could be on stack at that point).
| {
"pile_set_name": "StackExchange"
} |
Q:
method="GET" gives empty $_GET, method="POST" gives non empty $_GET. Why? (PHP 5.6.6)
test.php:
<?php
var_dump($_GET);
var_dump($_POST);
submit_get.php:
<form action="test.php?param=some" method="GET">
<input type="submit" value="Submit">
</form>
submit_post.php:
<form action="test.php?param=some" method="POST">
<input type="submit" value="Submit">
</form>
Submitting submit_get.php gives something like this:
array (size=0) empty array
(size=0) empty
Submitting submit_post.php outputs something like this:
array (size=1) 'param' => string 'some'
(length=4) array (size=0) empty
So, I do not quite get how are POST and GET methods are connected with $_POST and $_GET PHP variables and why a submitted form with method="POST" outputs empty $_POST and non-empty $_GET?
A:
A form sent via GET needs to have all values defined inside the form. The browser will then create the query string from these values (according to form evaluation rules, things like "successful controls" etc). Creating this query string means that any existing query string in the action URL gets replaced. If you need to have a fixed value inside the query string, use hidden form fields.
When using POST forms, all data from the form goes into the body of the request instead of replacing the query string. So there is no replacement taking place, and the query string in the action URL survives.
You probably are taking the superglobal variable names POST and GET too literal. $_GET is the parsed query string, it's independent of the HTTP method, i.e. it will always be present, even with POST, PUT and DELETE requests. $_POST is the parsed HTTP body when conforming to some constraints (the content-type header has to specify either application/x-www-form-urlencoded or multipart/form-data, and I think the method really has to be "POST" - "PUT" won't work that way, and "DELETE" must not have a HTTP body). Note that when NOT conforming to the constraints, even if you'd use the POST method, you won't get any data inside $_POST.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can a hotel kick you out if you let an unregistered guest share a room with you?
We are going to an event and because of this event all hotels are fully booked. Now a friend wants to join us, but can't find accommodation. We are okay with him crashing in our hotel room, either on the couch or on a self-inflatable mattress. We have done this in the past where we secretly sneaked the "guest" in.
It is not that we don't want to pay the tourist tax, it is that when ask and the hotel says no, we can't sneak him in, because we drew attention to ourself. In many hotels you can just order another bed, but there are also a lot that don't have that service.
I don't have any ethical problems with my behavior of secretly hosting a guest. I did pay for the room. I don't like being sneaky about it, since again I do pay for the hotel room. Also if I have to choose between sneaking someone in the room to crash on the couch or let him/her sleep on bench in the park. I opt for the first.
Am I just worrying to much and will being honest about it in the end be acceptable to most if not all hotels?
A:
The answer will vary from country to country and from hotel to hotel, but in general you're not allowed to do this and if the hotel finds it out, they can kick you out or charge you a fine.
In some countries they can even throw you in prison (worst case). For example in the USA there is the Defrauding an innkeeper law:
A person who, with intent to defraud, procures food, drink or
accommodations at a public establishment without paying in accordance
with his agreement with the public establishment is guilty of:
A felony punishable by imprisonment for not more than ten (10)
years, a fine of not more than ten thousand dollars ($10,000.00), or
both, if the value of the food, drink or accommodations is one
thousand dollars ($1,000.00) or more; or
Repealed by Laws 1984, ch. 44, 3.
A misdemeanor punishable by imprisonment for not more than six
(6) months, a fine of not more than seven hundred fifty dollars
($750.00), or both, if the value of the food, drink or accommodations
is less than one thousand dollars ($1,000.00).
I think in the most cases you will have to pay an extra fee.
A:
As far as my experience is concerned, it is the registered guest's prerogative as to whether to entertain guests in their room. If this were not the case then romantic rendezvous in hotels would not be permissible. I've never had a hotel decline this privilege and in many cases I have requested additional room keys for my guests. Of course, the maximum occupancy of the room must be observed.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to declar UITableViewController in Unwind segue from UITableViewController to UIViewController
I have my main view and a RoutinesTableViewController.
I wanted to unwind back to my man VC and tried this:
@IBAction func selectRoutine(segue:UIStoryboardSegue) {
let RoutinesTableViewController = segue.sourceViewController as RoutinesTableViewController
if let selectedRoutine = RoutinesTableViewController.selectedRoutine {
RoutineLabel.titleLabel = routine.valueForKey("name") as? String
}
}
I got an error in
let RoutinesTableViewController = segue.sourceViewController as RoutinesTableViewController
**Use of undeclared type RoutinesTableViewController **
But the above is definitely a UITableViewController class and controller
Is the segue.sourceViewController only for UIViewControllers?
A:
In this line
let RoutinesTableViewController =
you are assigning to a class. Perhaps you meant
let routinesTableViewController =
| {
"pile_set_name": "StackExchange"
} |
Q:
Use default data order in DataTables, but allow users to re-sort
I am using the Datatables plugin to work with some data:
My problem is that I would like to present the data in the order it is provided initially. So, disable DataTables auto sort on execution. However, I still want to provide the users the option to sort the tables themselves. bSort:false allows me to disable the initial sorting, but it also disabled the user's ability to sort.
How can I achieve both? FYI, the data is provided in a randomized order.
A:
The property you are looking for is "aaSorting". Leave "bSort" as is.
.dataTable({
"bSort": true,
"aaSorting": [],
... //other datatables properties
});
You can also set individual column sorting by applying "bSortable": True, or "bSortable": False to each column in "aoColumns".
.dataTable({
..., //other datatables properties
"aoColumns": [
{ "bSortable": True },
{ "bSortable": False }
]
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Unfold all sections in selected section
So in Visual Studio if I have a collapsed function code, when I unfold it, it also unfolds all the ifs, switches etc. inside of it. In visual studio code hovewer if I go for Fold All (Ctrl+K Ctrl+0) then if I wanna quickly check one function (f.e unfolding it by mouse click on the cross near line numbers), it unfolds the function but it doesn't go recursively, making me to unfold every other if/else or case. Is there a way to make this work the way I would expect it?
A:
Try Ctrl-K Ctrl-] recursive unfolding when the cursor is on the function to unfold.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to "set" and "puts" variable, which name consists of string and another variable?
I' trying to get a value of variable, which name consists of string "a" and iterator "i" (in this short example I skipped for loop). I was trying to do it with concat and append, with [] and "" and nothing working. Is there any solution for this problem?
set b0 0
set i 0
set a$i $b$i (here is my problem)
puts $a$i
puts should show "0"
A:
To read from a variable whose name is computed, use set with only one argument:
set a$i [set b$i]
puts [set a$i]
(There's a real sense in which the $ is a syntactic shorthand for calling this form of set; indeed, the $ syntax is newer.)
But Use Arrays Instead
In this case, you are almost certainly better off rewriting your code to use associative arrays.
set b(0) 0
set i 0
set a($i) $b($i)
puts $a($i)
| {
"pile_set_name": "StackExchange"
} |
Q:
MediaElement MediaFailed error 3100 IsolatedStorageFileStream
I receive mp3 files from web service and save them to isolated storage. The problem is that some of that files are playing fine in MediaElement, another - no (MediaFailed 3100 error: Error occured).
I'm using MediaElement.setSource(IsolatedStorageFileStream stream) method.
The most confusion about the problem - all those files play fine on wp7 phones, but when I use wp8 phone problem occurs.
I tried to recompile project to wp8 only, changed Capabilities in WMAppManifest.xml - but this not helped.
Thank you in advance for your help.
Project sample: http://sdrv.ms/19ENcHz
A:
Try to add extension to filename.
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the maximum number of columns allowed in Cassandra
Cassandra published its technical limitations but did not mention the max number of columns allowed. Is there a maximum number of columns? I have a need to store 400+ fields. Is this possible in Cassandra?
A:
The maximum number of columns per row is 2 Billion. This is per the link that you have embedded.
http://wiki.apache.org/cassandra/CassandraLimitations
400+ fields is not a problem.
A:
As per Cassandra technical limitation page, total no. of cells together cannot exceed 2 billion cells (rows X columns).
You can have a table with (1 row X 2 billion columns) and no more rows will be allowed in that table, so the limit is not 2 billion columns per row but limit is on total no. of cells in a partition.
https://wiki.apache.org/cassandra/CassandraLimitations
| {
"pile_set_name": "StackExchange"
} |
Q:
In IE dynamic attribute jquery with some number and its value is added, why ??
<DIV id=3949 class=tempClass channel-name="Brand" sizcache="50" nodeIndex="1" jQuery1362033550328="46"></div>
What is [jQuery1362033550328="46"]? It is showing in IE only not firefox.
A:
1362033550328 is the unix timestamp which is equivalent to Thu, 28 Feb 2013 06:52:00 GMT
Mostly its appended along with ajax requests to avoid ajax cache problems
| {
"pile_set_name": "StackExchange"
} |
Q:
Render multilpe times - Double render in rails
How to avoid this double render issue, i have been trying to replicate but couldn't. So is there any issue with this below code?
def check_count
assign_values_from_params
if count >= failed_count
render partial: params[:view_name], layout: false and return
else
render text: 'works' and return
end
end
def assign_values_from_params
# code
# code
# code
if @date.blank?
redirect_to main_index_path and return
end
if @counted_obj != 5
# call one function
end
end
Also should i try something this way Double render error rails ?
A:
Call performed? to check if render or redirect has already happened.
You might want to change your to code to something like this:
def check_count
assign_values_from_params
return if performed?
if count >= failed_count
render(partial: params[:view_name], layout: false)
else
render(text: 'works')
end
end
def assign_values_from_params
# code
if @date.blank?
redirect_to(main_index_path) and return
end
# code
end
| {
"pile_set_name": "StackExchange"
} |
Q:
$f(y)+\arctan(y)$ is constant
Suppose
$$
f(y)=\int_0^\infty e^{-yx}\frac{\sin{x}}{x}\,dx
$$
then show that $f(y)+\arctan(y)$ is constant and use this result to show that
$$
\int_0^\infty \frac{\sin{x}}{x}\,dx=\frac{\pi}{2}.
$$
MY THOUGHTS: So clearly we have to show that $f(y)+\arctan(y)=\frac{\pi}{2}$ for all $y$ so that
$$
\frac{\pi}{2}=f(0)+\arctan(0)=\int_0^\infty \frac{\sin{x}}{x}\,dx,
$$
but I have no idea how to begin to combine these two expressions to get the desired result. Any thoughts?
A:
Prove (using Dirchlet's test, for example) that $f(y)$ and $\int_0^\infty -e^{-yx}\sin x\, dx$ are uniformly convergent for $y > 0$ to justify
$$f'(y) = \int_0^\infty \frac{\partial}{\partial y} e^{-yx} \frac{\sin x}{x}\, dx = \int_0^\infty -e^{-yx}\sin x\, dx, \quad y > 0.$$
Compute
$$\int_0^\infty -e^{-yx}\sin x\, dx = -\frac{1}{1 + y^2}.$$
Since $f'(y) = -\frac{1}{1 + y^2}$, $f(y) = -\arctan(y) + C$, where $C$ is a constant. Show that $\lim\limits_{y\to \infty} f(y) = 0$ to deduce $C = \frac{\pi}{2}$. Let $y\to 0^+$ to obtain $$\int_0^\infty \frac{\sin x}{x}\, dx = f(0+) = \frac{\pi}{2}.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
If $a$ is separable over $F$ and $L/F$ is purely inseparable, then $\min_L(a) = \min_F(a)$
Let $K/L/F$ be a field extension such that $L/F$ is purely inseparable. If $a\in K$ is separable over $F$ then $\min_L(a)=\min_F(a)$.
All I have so far is that since $a$ is separable then $min_F(a)=(x-a_1)...(x-a_n)$, if there exists an $i \in \{1,...,n\}$ such that $a_i \in L$ then it is very easy to prove that $min_L(a)=min_F(a)$. If not, I don't know how to proceed.
A:
If $a\in K$ is separable over $F$, then $\min_L(a)$ divides $\min_F(a)$, hence $a$ is also separable over $L$. Write
$$
\min_L(a) = (X-a_1)\dotsm (X-a_m)
$$
for pairwise distinct elements $a_1 = a, a_2,\dotsc,a_m$ in an algebraic closure of $K$. Notice that these are all separable over $F$ (being roots of $\min_F(a)$). Expanding the above product, writing
$$
\min_L(a) = \sum_{i=0}^m\lambda_iX^i\in L[X],
$$
we see that $\lambda_i\in F(a_1,\dotsc,a_m)$ and hence they are separable over $F$. As the $\lambda_i$ also lie in $L$ and $L/F$ is purely inseparable, we conclude $\lambda_i\in F$ for all $i=0,\dotsc,m$. This shows $\min_L(a) = \min_F(a)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
API credentials are incorrect
I've tried to adapt the example from PayPal APIs Getting Started Guide to PHP:
<?php
define('PAYPAL_API_USER', '<snip>');
define('PAYPAL_API_PWD', '<snip>');
define('PAYPAL_API_SIGNATURE', '<snip>');
define('PAYPAL_API_APPLICATION_ID', 'APP-80W284485P519543T');
$endpoing = 'https://svcs.sandbox.paypal.com/AdaptiveAccounts/CreateAccount';
$headers = array(
'X-PAYPAL-SECURITY-USERID' => PAYPAL_API_USER,
'X-PAYPAL-SECURITY-PASSWORD' => PAYPAL_API_PWD,
'X-PAYPAL-SECURITY-SIGNATURE' => PAYPAL_API_SIGNATURE,
'X-PAYPAL-REQUEST-DATA-FORMAT' => 'JSON',
'X-PAYPAL-RESPONSE-DATA-FORMAT' => 'JSON',
'X-PAYPAL-APPLICATION-ID' => PAYPAL_API_APPLICATION_ID,
'X-PAYPAL-DEVICE-IPADDRESS' => '192.0.2.0', // :-? Also tried with my public IP address
'X-PAYPAL-SANDBOX-EMAIL-ADDRESS' => '<snip>', // Typed my account's e-mail
);
$payload = '{
"sandboxEmailAddress": "Sender-emailAddress",
"accountType": "PERSONAL",
"name": {
"firstName": "Lenny",
"lastName": "Riceman"
},
"address": {
"line1": "123 Main St",
"city": "Austin",
"state": "TX",
"postalCode": "78759",
"countryCode": "US"
},
"citizenshipCountryCode": "US",
"contactPhoneNumber": "512-555-5555",
"dateOfBirth": "1968-01-01Z",
"createAccountWebOptions": {
"returnUrl": "http://www.example.com/success.html"
},
"currencyCode": "USD",
"emailAddress": "[email protected]",
"preferredLanguageCode": "en_US",
"registrationType": "Web",
"requestEnvelope": {
"errorLanguage": "en_US"
}
}';
$options = array(
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => false,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_RETURNTRANSFER => true,
);
try{
$curl = curl_init($endpoing);
if(!$curl){
throw new Exception('Could not initialize curl');
}
if(!curl_setopt_array($curl, $options)){
throw new Exception('Curl error:' . curl_error($curl));
}
$result = curl_exec($curl);
if(!$result){
throw new Exception('Curl error:' . curl_error($curl));
}
curl_close($curl);
echo $result;
}catch(Exception $e){
echo 'ERROR: ' . $e->getMessage() . PHP_EOL;
}
... but I always get this back:
<?xml version='1.0' encoding='utf-8'?>
<ns3:FaultMessage xmlns:ns3="http://svcs.paypal.com/types/common" xmlns:ns2="http://svcs.paypal.com/types/aa">
<responseEnvelope>
<timestamp>2013-03-20T16:33:46.309-07:00</timestamp>
<ack>Failure</ack>
<correlationId>7d7fa53e6a930</correlationId>
<build>5343121</build>
</responseEnvelope>
<error>
<errorId>520003</errorId>
<domain>PLATFORM</domain>
<subdomain>Application</subdomain>
<severity>Error</severity>
<category>Application</category>
<message>Authentication failed. API credentials are incorrect.</message>
</error>
</ns3:FaultMessage>
I've double-checked the API credentials (user, pass and signature) and they're exactly as displayed in the profile page. I'm not fully sure of X-PAYPAL-DEVICE-IPADDRESS and X-PAYPAL-SANDBOX-EMAIL-ADDRESS.
I suspect I've misread something or omitted some curl option. Can you spot what's wrong in my code?
A:
Somewhat unhelpfully, the CURLOPT_HTTPHEADER option does not take a hash of Header=>Value pairs, only a list of strings, each of which must be a complete HTTP header.
So instead of $headers = array('X-PAYPAL-SECURITY-USERID' => PAYPAL_API_USER, ...) you need $headers = array('X-PAYPAL-SECURITY-USERID: ' . PAYPAL_API_USER, ...)
| {
"pile_set_name": "StackExchange"
} |
Q:
Looping through data array properties in VueJS
In vuejs you can do list rendering in the template like
<td v-for="item in items"></td>......
But can you iterate over that same data array property like....
for(var i = 0; i < this.items.length; i++)
this.$data.items[i]
A:
yes
Just don't worry about the this.$data.items, instead this.items, although it would also work ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Correctly disposing user control and its children
I have been looking for over 30 minutes now, but I simply cannot figure out what the problem is.
I have a TabControl and its items are to be closed by the user. Since each TabItem is in a way connected to a custom control and several objects that each use quite a lot of memory, I would like to dispose all objects that are used together with this TabItem.
To make it clearer and save you a lot of code here the simplified situation:
<UserControl x:Class="myProject.GridFour"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ScrollViewer Height="Auto" Margin="0" Name="scrollViewer11" Width="Auto" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"></ScrollViewer>
<ScrollViewer Grid.Column="1" Height="Auto" Name="scrollViewer12" Width="Auto" Margin="0" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"></ScrollViewer>
<ScrollViewer Grid.Row="1"> Height="Auto" Name="scrollViewer21" Width="Auto" Margin="0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"></ScrollViewer>
<ScrollViewer Height="Auto" Name="scrollViewer22" Width="Auto" Grid.Column="1" Margin="0" Grid.Row="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"></ScrollViewer>
</Grid>
</UserControl>
Now I set the content of the corresponding tabitem:
GridFour myControl = new GridFour();
myTabItem.Content = myControl;
Also I have custom objects that each contain a grid, which is added as content to the scrollviewers of my user control:
class MyClass
{
internal Grid _grid = new Grid();
internal Image _image = new Image() {Width = Double.NaN, Height = Double.NaN HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Stretch = Stretch.Fill};
//... a lot of variables, data, images and methods...
}
MyClass[] myObject = new MyClass[4];
for(int i = 0; i < 4; i++)
{
myObject[i] = new MyClass();
myObject[i]._grid.Children.Add(_image); //that actually happens when I initialise the object, it is just to show how everything is connected
}
myControl.scrollViewer11.Content = myObject[0]._grid;
myControl.scrollViewer12.Content = myObject[1]._grid;
myControl.scrollViewer21.Content = myObject[2]._grid;
myControl.scrollViewer22.Content = myObject[3]._grid;
Now when the user would like to close the tabitem obviously I would also like to get rid of myControl and of every single object myObject.
I tried to call the Dispose method on them via IDisposable but that always throws a NullReferenceException and I simply cannot figure out why.
I should maybe mention that every single myObject is within a Dictionary<string, MyClass> but I remove the object from there before I call dispose.
A:
class MyClass : IDisposable
{
internal Grid _grid = new Grid();
internal Image _image = new Image() {Width = Double.NaN, Height = Double.NaN HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Stretch = Stretch.Fill};
//... a lot of variables, data, images and methods...
public void Dispose()
{
// your custom disposing
_image = null; //or something like that
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
WKWebView only showing desktop site
I just migrated from UIWebView and my new WKWebView will only show the desktop version of the site I'm loading. My UIWebView showed the responsive site appropriately.
I have tried forcing a mobile User-Agent and confirmed that it is coming in on to the server
let userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/11A465 Twitter for iPhone"
webView.customUserAgent = userAgent
Does anyone have any other ideas I can try? Thanks
A:
I don't have control over the CSS of the page I'm displaying.
It was using the following to calculate breakpoints:
width=device-width, initial-scale=1
@media screen and (min-width: 650px)
Adding this to the template that uses that CSS solved it for me:
<meta name="viewport" content="width={{ $width }}, shrink-to-fit=YES">
Where {{ $width }} is:
UIScreen.mainScreen().bounds.size.width
| {
"pile_set_name": "StackExchange"
} |
Q:
Smarty - include template and update an existing variable
I've recently started working with Smarty and I'm trying to find my way around. Here's what I don't know in the very moment:
I'm including a file:
{include file="nforum/_partials/box_forum.tpl"}
In that file, I have this:
<a href="{$t->link}">{$t->title|truncate:$link_truncate}</a>
I would like to pass $link_truncate a value of 30 while including the template (not inside the box_forum.tpl - that's important to me!)
I'm trying with:
{include file="nforum/_partials/box_forum.tpl" $link_truncate = 30}
without success. How can I do it?
A:
declare, before include the template:
{assign var="link_truncate" value="30"}
| {
"pile_set_name": "StackExchange"
} |
Q:
Save and Load ListView content
I am writing an app in C# winForm, and I am using ListView to store some data.
I need to save this list of item when the form is closed and load it again when the form is opened again.
This is the code to add a new element on the list:
string[] timeitem = new string[2];
timeitem[0] = txtDescription.Text;
timeitem[1] = msktime.Text;
ListViewItem lvi = new ListViewItem(timeitem);
lstTimes.Items.Add(lvi);
What is the best way to save and load this list? I do not need a Dialog for the user, this list should be saved and loaded automatically each time the user open the form that contains the ListView item. I am open to use either .txt or xml file, whatever is the best/more easy to handle.
A:
You could write a simple helper class for that:
class ListItemsHelper
{
private const string FILE_NAME = "items.dat";
public static void SaveData(Items items)
{
string data = SerializeItems(items);
File.WriteAllText(GetFilePath(), data);
}
public static Items LoadData()
{
string data = File.ReadAllText(GetFilePath());
return DeserializeItems(data);
}
private static string GetFilePath()
{
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FILE_NAME);
}
private static string SerializeItems(Items items)
{
//Do serialization here
}
private static Items DeserializeItems(string data)
{
//Do deserialization here
}
}
Use:
ItemsStateHelper.SaveData(items);
Items data = ItemsStateHelper.LoadData();
Additionally, you would have to include some exception handling and choose where you want to save the file. In the code i posted it is saving on folder where the exe file is located.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to call a slot on quit
I want to update my database just before my Qt application closes.
I want something like connect(this, SIGNAL(quit()), this, SLOT(updateDatabase()))
One way could be to introduce a quit button, but is it possible to achieve this functionality if user presses Alt+F4?
A:
Use signal aboutToQuit() instead.
This signal is emitted when the application is about to quit the main
event loop, e.g. when the event loop level drops to zero. This may
happen either after a call to quit() from inside the application or
when the users shuts down the entire desktop session.
The signal is particularly useful if your application has to do some
last-second cleanup. Note that no user interaction is possible in this
state.
For example :
connect(this, SIGNAL(aboutToQuit()), this, SLOT(updateDatabase()));
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.