INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Detect a string in Google Sheet and output a different string based on the result
I use REGEXMATCH to detect strings in a sheet. I need to replace the cells values by texts.
For example, detect "One" and output "Text one", detect "Two" and output "A second text", detect "three" and output "Another text".*
I already use :
=IF(OR(REGEXMATCH('Sheet'!A2;"One");REGEXMATCH('Sheet'!A2;"Two"));"Texte 1";"My second text")
But it's only based on TRUE/FALSE, I will have up to 4 possibilities. | IFS allows more conditions:
=IFS(REGEXMATCH(A1,"One"),1,REGEXMATCH(A1,"Two"),2, ...) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "google sheets, spreadsheet"
} |
Custom Keras Loss (which does NOT have the form f(y_true, y_pred))
def charbonnier(I_x, I_y, I_t, U, V, e):
loss = K.sqrt(K.pow((U*I_x + V*I_y + I_t), 2) + e)
return K.sum(loss)
I would like to use this cost function and optimise it for U and V. I am currently struggling to get it working with Keras, since Keras loss functions can only have the form f(y_true, y_pred).
. So my question is: What is the correct way to implement this kind of loss function (which does not have the form f(y_true, y_pred)), in Keras? | Define the loss function as follows:
def charbonnier(I_x, I_y, I_t, U, V, e)
def loss_fun(y_true, y_pred):
loss = K.sqrt(K.pow((U*I_x + V*I_y + I_t), 2) + e)
return K.sum(loss)
return loss_fun | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "python, keras, deep learning"
} |
CQL solr-query getting error - cannot pass json query
I'm new to DSE. Working on DSE based queries to get date range
1) `select count(1) from tbl where solr_query='code:maf';` It gives the result.
But When I'am trying to use range query is gives error :-
`select count(1) from tbl where solr_query='{q:dt:[ 2017-11-15T10:12:10 TO 2017-11-15T12:10:10Z] }';`
**Error :-** `Invalid Request: Error from Server: Code:2200 [Invalid Query] message="Cannot pass JSON query" '{q:dt:[ 2017-11-15T10:12:10 TO 2017-11-15T12:10:10Z] }'`
Where I'am going wrong? Please help
Thanks, | you need correctly format your query - it should be JSON inside, like this:
select count(1) from tbl where
solr_query='{"q":"dt:[ 2017-11-15T10:12:10 TO 2017-11-15T12:10:10Z]"}';
See official documentation for detailed description. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "solr, cassandra, cql, datastax enterprise, solr query syntax"
} |
regex: replace matches with their ids
I'm having this situation and I'm wondering if i could do it with regex:
I have a string in this format:
{{We all}} love {{stackoverflow}}.
My question is how can I use regex replace to get:
match1 love match2 | s = '{{We all}} love {{stackoverflow}}.' #string to match
pat = re.compile(r'\{\{.*?\}\}') #pattern
#now replace each matched group by its index
for index,group in enumerate(re.findall(pat,s)):
s = re.sub(group, 'match'+str(index+1), s)
Works for any number of groups. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, regex"
} |
How do you plot functions for straight lines $y=mx+c$ with labels and intercepts?
I've taken screen captures from other problems, but the results are poor.
I'd like to be able to do lines, and move onto quadratic etc. later.
y=3x+2
show & label
* x & y axes
* origin
* y intercept
* line, labeled for function | Let me suggest a possible solution using the `pgfplots` package. The third chapter of the documentation is dedicated to easy-to-understand beginner tutorials.
\documentclass{article}
\usepackage{pgfplots}
\usetikzlibrary{intersections}
\begin{document}
\begin{tikzpicture}
\begin{axis}[domain=0:3,no marks,xlabel=$x$,ylabel=$y(x)$]
\addplot+[name path=A] {2*x-1};
\addlegendentry{$2 x - 1$};
\addplot+[name path=B] {0.5*x+1};
\addlegendentry{$x/2 + 1$};
\path[name intersections={of=A and B}]
node[draw,fill,circle,inner sep=1pt,pin={above left:Intersection}]
at (intersection-1) {};
\end{axis}
\end{tikzpicture}
\end{document}
> ;
With the regular CSV, it doesn't recognize any lines, but with the Windows version it works as expected (go figure!). How do I fix this? | As mentioned before, you should use `fgetcsv()` ... However, I still had problems with CSVs generated on Macs using that function.
PHP was not properly detecting line endings. To overcome the issue, I had to add `ini_set("auto_detect_line_endings", true);` to the function that was processing the CSV file. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "php, csv"
} |
About Java Positioning
I'm trying to change jButton position to right, when the jPanel appears, but the only change is jPanel appears and disappears.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
n++;
if((n % 2) == 1){
jPanel1.setVisible(true);
jButton1.setLocation(200, 0);
}
if((n % 2) == 0){
jPanel1.setVisible(false);
jButton1.setLocation(0, 0);
}
}
But if I write just the section below, double click will make the change of jButton position. I want to see the changes from one click.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
jPanel1.setVisible(true);
jButton1.setLocation(200,0);
} | I would suggest using the Border Layout manager with Flow Layout.
for more info go to this tuturial link | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "java, swing"
} |
cyrtsal report how to hide records based on condition of a field like date
hi all i have a question about hiding records in crystal report and i am using cyrstal report in vs 2008 ,i dont know its version as i am new in crystal reporting
lets say i have report like that
customer_Id customer_name OrderAmount Order_date
0 xyz 5 03/02/2010
1 abc 6 04/02/2010
3 dre 7 07/02/2009
4 kila 3 08/02/2009
i wana ask is there a pssibilty to hide the record if Order_Date year in 2009 and show only the records where Order_date year in 2010 to be like that :
customer_Id customer_name OrderAmount Order_date
0 xyz 5 03/02/2010
1 abc 6 04/02/2010
**note i do need the data of 2009 to make a bar chart for this year
thanks in advance | So the report itself will have a bar chart on to show 2009, but the list of records shouldn't show 2009?
Two options :
The first is a subreport.
The second is to use a suppression formula in the Details section that says "Year(Order_Date) = 2009". | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "crystal reports"
} |
flowplayer in a hidden div
I'm using a flowplayer. When I put it in the hidden area below, the player does not work.
<div class="hidden" style="display:none">
<div class="flowplayer" data-swf="flowplayer.swf" data-ratio="0.4167">
<video>
<source src="
</video>
</div>
</div>
Flowplayer is available at the following location: < | You're right, it doesn't.
But you can use a workaround of instead using:
visbility:hidden;
height:0px;
And then it works fine.
jsFiddle of a working example (warning: you will need sound) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, flowplayer"
} |
How to add vectors in Ada
I have a vector of the form (x,y,x) representing coordinates. I want to be able to do something like (x,y,z) + (x2,y2,z2) to produce a new set of coordinates. Ada says it cant use '+' for composite types, but surely there is a way I can do this? | If you have
type Vector is record
X : Float;
Y : Float;
Z : Float;
end record;
you can define `+` as
function "+" (L, R : Vector) return Vector is
(L.X + R.X, L.Y + R.Y, L.Z + R.Z);
Be careful when you define `-` similarly to use `-` throughout! that error is _very_ hard to spot. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "vector, ada, gnat gps"
} |
Express 4.7.2 render views
Apparently in Express 4.7.2 render does not explicit ends the execution, that means:
on Express 4.2
res.render('path/to/view');
res.render('path/to/view');
Render display the first view and ends the execution.
on Express 4.7.2
res.render('path/to/view');
res.render('path/to/view');
Throws 'Can't set headers after they are sent' error, for example:
app.get('/path', function(req, res) {
if ( someFancyValidation ) {
res.render('error_view');
}
res.render('succes_view');
});
We need an explicit 'return' statement in order to get the desirable result. | It should be
app.get('/path', function(req, res) {
if ( someFancyValidation ) {
res.render('error_view');
}
else//you missed this
res.render('succes_view');
});
You can't render twice for a single call. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "node.js, express"
} |
Magento displaying multiple product lists on custom page
I've created a custom module to help profile my customers, for example I've captured data on my customers on what mobile phone they are using, and what's their favourite colour. Once collected they will land on a thank you page (e.g. /survey/mobile/thankyou) and I want to display products that can help customers out, so I want to display two lists, say a mobile phone cover and a recharging kit. I figured that you can call a product list with the following code on a phtml
<?php
echo $this->getLayout()->createBlock('catalog/product_list')->setTemplate('catalog/product/list.phtml')->toHtml();
?>
I have 3 questions.
1. how do you pass a limit parameter to the list? say I want to display 3 products.
2. how do I past parameters to the list, e.g. phone_type = iphone/samsung?
3. is there a better way to do this? | 1/ The limit products in the list is set in the Admin -> System -> Configuration -> Catalog
2/ To my opinion, if you want to pass params to the list, try to enable filter for the attributes you want to use in Admin -> Catalog -> Attributes -> Manage Attributes
3/ To me, the best way is create a custom block which extends class Mage_Catalog_Block_Product_List and write a loading list function there in order to meet your needs. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, magento"
} |
Comparing long data type with varchar data in oracle
Consider following scenario :
CREATE TABLE test
(
name VARCHAR2(50),
type LONG,
CONSTRAINT c_type CHECK (type IN ('a', 'b', 'c', 'd', 'e', 'f'))
);
I want to `alter constraint` c_type and add a new type in check constraint say 'g'.
Now to alter a constraint we need to drop it and recreate it, but I want to drop the constraint only if it do not contains check for type 'g'.
I checked table `user_constraints`, it contains column search_condition but problem here is the data type for column "type" is `long` which i am not able to compare with `varchar`.
How to compare the `Long` data type? | I think that your problem isn't that the `TYPE` column is LONG but that `SEARCH_CONDITION` of `user_constraints` is a LONG.
So you can do something similar to the answers in this post, in your case it can look like this:
select count(*)
from
(SELECT XMLTYPE(
DBMS_XMLGEN.GETXML('select SEARCH_CONDITION from user_constraints ')
).extract('//SEARCH_CONDITION/text()').getstringval() srch_cond
from dual)
where srch_cond like '%'g'%'
Here is a sqlfiddle Demo | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "oracle, constraints, type conversion, check constraints"
} |
Problema con Sqflite
No se porque da ese error.... tengo 4 bases de datos hechas de la misma forma .... alguien me puede explicar? como nombre de un campo.
No sé si, como en otros DBMS, puedas usar el nombre de campo entre comillas para indicar que es un literal y no la palabra reservada. Yo en tu lugar, cambiaría el nombre del campo. | stackexchange-es_stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "flutter"
} |
Adding a custom marker to map - Android
I currently have an app which displays google maps to the user using MapView.
I have been trying to place a marker on the map using this code,
public boolean onTouchEvent(MotionEvent event, MapView mapView) {
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels((int) event.getX(),
(int) event.getY());
DemoOverlay demoOverlay = new DemoOverlay();
mapView.getOverlays().add(demoOverlay);
mapView.invalidate();
}
return false;
}
I have a Demo Overlay set up which puts a marker on the map, however when I touch the screen the marker never appears.
Any help would be appreciated !!! | Thanks for suggestions but I have decided to follow these tutorials as they cover exactly what I need,
This video in particular is the one which covers my question,
| stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "android, google maps, touch, overlay"
} |
How to know the size (Number of nodes) of the tree built using Scikit-learn?
decReg = DecisionTreeRegressor() clf = decReg.fit(X, Y)
Intuitively anyone would expect either decReg or calf should have a function which will return the number of nodes in the tree grown. But, I am unable to see any such function. Is there anything else to know the tree size? | According to the documentation, there's `tree_` attribute, you can traverse that tree to find any properties of interest. In particular, `children_right` and `children_left` properties seem to be useful. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, machine learning, scikit learn, regression, decision tree"
} |
Is the Ext module $\mathrm{Ext}^i_R(R/I^n,-)$ annihilated by a power of $I$?
Let $R$ be a Noetherian ring and $I$ an ideal in $R$. Let $M$ be a finitely generated $R$-module.
> Is, for all $i$ and $n$, the module $\mathrm{Ext}^i_R(R/I^n,M)$ killed by a power of $I$?
I've read somewhere that this is true when $R$ is local and $I=\mathfrak m$ is the maximal ideal, but can someone explain why this is true and whether it is true in the above, more general, setting? | Yes: let $N,M$ be any two $R$-modules ($R$ being an arbitrary commutative unital ring) and $J \subset R$ some ideal such that $JN=0$.
Then $\mathrm{Ext}_R^i(N,M)$ is a cohomology group in the complex $\mathrm{Hom}_R(N,I_{\cdot})$ where $I_{\cdot}$ is an injective resolution. But obviously, every module in this complex is annihilated by $J$, so that the same holds for its cohomology.
So in your case, $I^n$ annihilates $\mathrm{Ext}_R^i(R/I^n,M)$. | stackexchange-math | {
"answer_score": 2,
"question_score": 4,
"tags": "abstract algebra, ring theory, commutative algebra, modules, homological algebra"
} |
Is the hypothesis in this theorem too strict(group-theory)
Please take a look at this theorem: !enter image description here
This theorem is from the **sixth** edition of a book. In the updated version, in the **seventh** edition then he have included that $K'$ is a subgroup of $G' \cap \phi[G]$. But why did he update it like that? Isn't the correct version in the sixth edition, $K'$ does not have to be a subgroup of $\phi[G]$ for the theorem to be true? . | The update does not change anything; certainly, it is unnecessary, but it is also not really weakening the theorem. The proof given does, in fact, establish that $\phi^{-1}[K']$ is a subgroup of $G$. However, it is worth noting that the new statement is equivalent, since $K'\cap \phi[G]$ is a subgroup of $G'$ as well, which is contained in the image $\phi[G]$ and has that $$\phi^{-1}[K']=\phi^{-1}[K'\cap \phi[G]]$$ | stackexchange-math | {
"answer_score": 2,
"question_score": 3,
"tags": "group theory"
} |
Нужно считывать статус оформления по рег. номеру
Я начинающий в c# и это мой первый вопрос. Мне нужно взять с этого сайта < Тип, рег. номер, дату регистрации и когда был изменен Статус и сам статус. Парсить обычные сайты я могу, но вот на этом сайте есть кнопка подгрузить еще, которая ставит меня в ступор.Подскажите как это лучше сделать. | Вам необходимо:
1. Скачать html используя WebClient.DownloadString Метод
2. Подключить библиотеку HtmlAgilityPack через NuGet.
3. Распарсить html. Для этого вам потребуется писать XPath. В Google Chrome необходимо нажать правой клавишей мыши на элемент и выбрать Inspect.
 a (BB a) deriving (Show)"
new to Haskell here. Trying to figure out how to make preorder traversal given various tree definitions. I`ve seen preorder for a tree defined as `data BB a = L | K a (BB a) (BB a) deriving Show`
prefixCollect L = []
prefixCollect(K w l r) = w : prefixCollect l ++ prefixCollect r
However, I am not sure how to perform same operation if the tree is defined differently: `data BB a = L | K (BB a) a (BB a) deriving Show` ?
Could please somebody help? | There is virtually no difference in how you would define the function; the difference in type definitions only changes how you would pattern-match against the argument.
prefixCollect L = []
-- K l w r instead of K w l r
prefixCollect (K l w r) = w : prefixCollect l ++ prefixCollect r
Both definitions define a tree in exactly the same way: as a node consisting of a value and two subtrees. The order in which the data constructor `K` lists those three values doesn't really matter. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "haskell, functional programming, binary tree, tree traversal, preorder"
} |
How can I easily remove lines that matches some regular expression from lastly modified files
I am new to Ruby and I often do the debugging with this tool. It requires to put this line on a place of the breakpoint
binding.pry
Then in the console I am able to debug. I don't want other solution, I am ok with that. But my code is often polluted with those lines that I need to get rid of before doing the commit. Is there any way that will check if a file contains this line and if yes, it'd delete it? Some git + sed magic I guess, or is there something built in git? | Ok, I came up with
sed -i -e '/binding\.pry/d' `git diff-index --name-only -G "binding\.pry" HEAD`
This works perfectly for my needs. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby, git"
} |
How to choose a proper method for PDE?
In most of the books I've seen, the authors explain various methods for solving partial differential equations, sometimes give recommendations about usage and limitations of the approach, but I never seen a complete algorithm or a guide how to choose an appropriate method. For example
1. Determine type of you PDE (type, order, linear/nonlinear etc)
2. If the PDE is linear, try method one.
3. If not, but the coefficients satisfy the conditions, try method two.
I would expected such a guide in various "PDE for engineers" books, but they do not have it. It would be also nice to have a summary or roadmap for pros and con of the different methods. Could anybody suggest such a book? | A complete algorithm is probably too much to ask for, but you might be interested in "Handbook of Differential Equations" by Daniel Zwillinger. (Google Books link.) | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "reference request, partial differential equations"
} |
If $X = g(Y) + Z$, with $Y,Z$ independent continu0us RVs, what is the conditional density $f_{X \mid Y=y}(x)$?
Let $(\Omega,\Sigma,P)$ be a probability space. Suppose that $Y:\Omega \to \mathbb R^n$ and $Z:\Omega \to \mathbb R^m$ are independent, continuous random vectors with probability density functions $f_Y$ and $f_Z$, respectively, and that $$ X = g(Y) + Z $$ for some function $g:\mathbb R^n \to \mathbb R^m$. It seems that it should be obvious that $$ f_{X \mid Y = y}(x) = f_Z(x - g(y)), $$ but how do we prove this fact?
(Feel free to take $m = n = 1$ for simplicity, if that is helpful. We can assume $g$ satisfies whatever mild regularity condition is convenient.) | By the definition of conditional the probability density function, a Jacobian change of variables, and the independence of $Y$ from $Z$.
$$\begin{align}f_{X\mid Y=y}(x) & =\dfrac{f_{X,Y}(x,y)}{f_Y(y)}\\\\[1ex] & = \begin{Vmatrix}\dfrac{\partial [ x-g(y),y]}{\partial [x,y]}\end{Vmatrix}\cdot\dfrac{f_{Z,Y}(x-g(y),y)}{f_Y(y)}\\\\[1ex] &= \dfrac{\lvert 1\rvert\cdot f_Z(x-g(y))\cdot f_Y(y)}{f_Y(y)}\\\\[1ex] &= f_{Z}(x-g(y)) \end{align}$$That is all. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "probability, probability theory"
} |
Adjusting position of minipage
I have been trying to include some tike-diagrams into my pdf using `\includepdf{...}` of `standalone` outputs. However, when I do that it makes an entirely new page with the diagram. So I tried using the `minipage` environment and now I get something like this:
My question is: on 27/05 DAG ran but "run date" was set to 20/05 and I don't know why. Is it because it was turned off on 20/05 and DAG got the "last scheduled date"? In this case, next week (June 3) it will run with "run date" set to 27/05 or 03/06?
What will be _execution_date_ and _next_execution_date_ in this case on June 3?
 you will see in `Run` this date `2019-05-27T11:00:00' | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "python, airflow, airflow scheduler"
} |
Load components dynamically in Angular2
I want to load components dynamically which means I don't know which component to load during compile time. I have read about DynamicComponentLoader here but the angular2 Api docs says this class is deprecated, so what is the current/correct way to do this? | Use `ComponentResolver` and `ViewContainerRef` as a replacement for `DynamicComponentLoader` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "angular"
} |
Scanner() not working with if - else statement
My intention is to let the user decide which method to use by cheking its input.
I have the following code:
try {
String test = scan.next();
if(test == "y") {
//do stuff
}
else if (test == "n") {
//do stuff
}
} catch (Exception e) {
System.out.println("false");
}
I tried to analyze with the debugger. It is not jumping in the `if`-statement. can you help me out here? | You need to use `equals` to compare strings
if(test == "y")
becomes
if (test.equals("y"))
Same for `"n"` obviously.
`==` test for reference equality, but you're looking for value equality, that's why you should use `equals`, and not `==`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "string, if statement, java.util.scanner"
} |
Create a scale key for jvectormap region colors
I'd like to create a key to my map that shows the values associated with the different colors, as at the bottom of the drawing:
!enter image description here
I can make a series of boxes easily enough. Is there a method somewhere I can input a value to get the color back that the map would use for that value? | First you need a map object. If you have created a map with `jvm.WorldMap` constructor you have it already, otherwise if you have created a map using jQuery wrapper you can do:
var map = $('#map').vectorMap('get', 'mapObject');
Then to convert the value to color do the following:
var color = map.series.regions[0].scale.getValue(someValue); | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "jvectormap"
} |
Testing in specific namespace
I'm trying to test some classes in namespace, currently I have this code:
describe Server::SessionController do
it "should create session" do
Server::LoginController.stub(:authenitcate).and_return(session_id)
Server::SessionController....
Server::SessionController....
end
end
How to get rid of repeatable `Server` namespace? | The RSpec Book ( < ) gives a solution :
3 module Codebreaker
4 describe Game do
5 describe "#start" do
> ... The second statement declares a Ruby module named Codebreaker.This isn’t necessary in order to run the specs, but it provides some conveniences. For example, we don’t have to fully qualify Game on line 4.
So, try to put your spec inside a `Server` module. HTH. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 4,
"tags": "ruby, rspec"
} |
What is the difference between an interlock and a transfer switch?
With respect to wiring a standby generator, what is the essential difference between an interlock and a transfer switch and what are the pros and cons of using one rather than the other? | An interlock needs a human to operate it. They cost less, in general.
A transfer switch can be (and usually is) automatic. They cost more, in general.
An interlock setup can usually feed power to any circuit in the panel (but if you overload the generator input the generator breaker will trip.) This is also controlled manually, by the user turning other breakers off and on.
A transfer switch setup can only feed specific circuits, since automatic operation means there's nobody to turn off circuits to shed load, so the loads connected to the generator must be less than or equal to what the generator can supply, if all are operating. | stackexchange-diy | {
"answer_score": 1,
"question_score": 1,
"tags": "generator, emergency preparedness"
} |
How to adapt couch to 5k for treadmill?
I had a look at the "treadmill version" on the c25k website, but it has runs lasting < 2 minutes. The treadmill that I want to use, is _very_ slow changing speeds - I'm concerned that going from walk to run (or back) could take several seconds, and out of a 90 second run, 10 seconds is a lot.
Should I not include the transitional time in the walk/run duration? Or should I count it as part of one or the other? It seems like the rapid walk/run transitions are designed for running outdoors, where it is easy to switch between them - how can I adapt the plan to work with a treadmill? | There shouldn't be any adaptation necessary.
The few seconds that it takes to ramp up to speed will be offset by the few seconds it takes to slow back down to the walk pace, and is a little bit more of a natural effort than most people that just suddenly go from run to walk or vice versa.
So, for the treadmill on your 90 second runs, start the time and change the speed, then at 90 seconds change the speed back down. The speeding/slowing of the belt will counter each other, and should give you a consistent effort across the entire workout time. | stackexchange-fitness | {
"answer_score": 1,
"question_score": 6,
"tags": "cardio, treadmill, couchto5k"
} |
SELECT COUNT(1) FROM table in dynamic query
I'm iterating through an array of table name strings and passing them to the following function:
FUNCTION table_empty(table_name VARCHAR2)
RETURN BOOLEAN
AS
row_count NUMBER := 0;
empty_sql VARCHAR2(255);
BEGIN
empty_sql := 'SELECT COUNT(1) FROM :tab_name';
EXECUTE IMMEDIATE empty_sql INTO row_count USING table_name;
DBMS_OUTPUT.PUT_LINE('Row Count: ' || table_name);
RETURN row_count > 0;
END table_empty;
However, I get this error
> Unexpected error: ORA-00903: invalid table name
Does anybody have any idea what causes this? | Bind variables are for _variables_ , not identifiers. The table name (and other identifiers) need to be known when the dynamic statement is parsed; variable values are then applied when it is executed. At the moment when the statement is parsed the table name is interpreted literally as `:tab_name`, which is an invalid name.
You need to concatenate the name:
empty_sql := 'SELECT COUNT(1) FROM ' || table_name;
EXECUTE IMMEDIATE empty_sql INTO row_count;
You might want to validate the table name first though. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "sql, oracle, plsql"
} |
Equal columns on table
This is my code: <
#my-table{width:100%;border-collapse:collapse;} /*or whatever width you want*/
#my-table td{width:2000px;padding:4px;border:1px solid #000;vertical-align:top;} /*something big or 100%*/
I'm trying to make it so no matter how many columns there are, each one is an equal width. However, this approach _should_ work but it doesn,t we can see one is clearly bigger because it has bigger content.
Can this be done, without having to specify specific CSS for the number of columns? | Set `table-layout:fixed` on the table, and remove fixed width you have set on `td`.
**UPDATED FIDDLE**
#my-table{
width:100%;
border-collapse:collapse;
table-layout:fixed
}
#my-table td{
padding:4px;
border:1px solid #000;
vertical-align:top;
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "html, css"
} |
Unable to set a URL as Default value in MySQL
I am using phpMYAdmin to set a URL as a Default Value to a Field of a Table in MySQL database, but of no luck.
The URL is like this one:
> <
Here is the Table field structure:
{varchar(255), utf8_general_ci, Not Null} | It's unclear what is wrong, but this will create a DEFAULT constraint for an existing table using an ALTER TABLE statement to to set the URL value if one is not provided when a record is inserted:
ALTER TABLE your_table
ALTER the_column SET DEFAULT ' | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, mysql, default constraint"
} |
Escaping data before import into database
I have a function in a WordPress plugin that takes a csv file and reads the data into a MySQL database table. Works fine except the raw data is not properly escaped and apostrophes cause issues. My code is below. How can I fix this issue?
if (($handle = fopen($file_url, "r")) !== FALSE) {
$j = -1;
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
foreach($data as $i => $content) {
$data[$i] = $data[$i];
}
$wpdb->query( "INSERT INTO games ( id, game_id, date, time, field, hteamno, vteamno, hcoach, vcoach, division, friendly, pool ) VALUES('" . implode("','", $data) . "') ");
$j++;
}
Thanks. | You could use `$wpdb->prepare()` with placeholders of the appropriate types (eg `%s` for string) to prepare your SQL string.
Or you could use `$wpdb->insert()`, which also allows placeholders, leaving WordPress to do the work. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, wordpress"
} |
difference between LoginToken and Session? node.js express connect
For example right here:
<
<
There's something called a login token. I don't understand what the point of that is, isn't there already a session? There's a session cookie and a session entry in the database. Can't you check against that instead of LoginToken?
Thanks. | This isn't really a node.js question, since it applies just as much to websites written in any language, but here's an answer.
Session cookies are generally quite short-lived, and reference a whole bunch of information about what you're currently doing on a website, which you don't want to store for every user for weeks or months. The login token is a much longer-lived cookie that just records that this web browser is authorised to connect as this user without having to go through the login process. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "javascript, session, node.js, connect, express"
} |
how to use bundle install without network access
I have a Windows 2012 server that is on an internal network. I used Railsinstaller to put the basic framework on the system. Rails new doesn't work when I reach the bundler section since I can't reach the net.
I have used "gem install rails -i repo --no-rdoc --no-ri" on a net accessible system then placed the gems on my server and ran "gem install --force --local *.gem".
Then "rails new D:\DTS_WEB --edge" and now fail at "unable to connect to github.com". Trying to start the rails server fails telling me that nothing has been checked out.
I modified my gems file with "gem 'rails', path: '....\Ruby2.2.0\lib\ruby\gems\'" but it still tries github.
I installed git with Railsinstaller along with rails. How can I get past this last obstacle and force everything to use local resources?
Is it possible to build everything on the net accessible node and just copy it into place on the server to use? My first attempt at that failed. | On a machine that has a network connection, you can install your app's gems to a directory within the project using `--path`:
$ bundle install --path=vendor/bundle
Then, you can copy the project folder (along with all the gems in vendor/bundle) to your internal machine. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, git, rubygems"
} |
R - change colors in ggplot2 plot
> **Possible Duplicate:**
> ggplot custom colors palette
Hello,
I am using this question - Making a stacked area plot using ggplot2 \- to make a nice stacked area plot.
The resulting grapg is nice, but I cannot find how to change the colors in `ggplot` graph. | you need to manual designate the colors you want to use, then use scale_fill_manual.
rhg_cols1<- c("#000000","#F8766D","#7CAE00","#00BFC4","#C77CFF" )
ggplot()+geom_bar()+opts()+ scale_fill_manual(values = rhg_cols1) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "r, ggplot2"
} |
Drawing a biggest possible circle inside a polygon - JSXGRAPH
I manage to create a circle inside triangle with this code, but circle inside other polygons are not maximum size:
var p1 = board.create("point", [0.0, 2.0]);
var p2 = board.create("point", [2.0, 1.0]);
//var pol = board.create("regularpolygon", [p1, p2, 3]);
var pol = board.create("regularpolygon", [p1, p2, 4]);
//var pol = board.create("regularpolygon", [p1, p2, 5]);
board.create("incircle", pol.vertices);
What is the easiest way to draw a maximum circle inside square and pentagon?
How about smallest circle around the polygon? | This is why geometry class in high school had you spending all that time drawing stuff.
Assuming a regular polygon (all sides same length, all "corners" same angle), it is immediately obvious that the centers of the largest inscribed circle and the smallest circumscribed circle are identical, and are given by the vector arithmetic mean of the polygon vertices.
The largest inscribed circle touches the polygon at the midpoint of each edge. The radius is thus given by the distance from the center to the midpoint of any one edge of the polygon.
The smallest circumscribed circle touches the polygon at every vertex. The radius is the distance from the center to any one vertex of the polygon. | stackexchange-softwareengineering | {
"answer_score": 8,
"question_score": 1,
"tags": "javascript, geometry"
} |
Need to add import androidx.core.view.children
Downloaded a demo to check something inside it these imports works
import androidx.core.view.children
import androidx.core.animation.doOnEnd
import androidx.core.animation.doOnStart
but i can't use inside my project , it gives me error with `children` and `animation`
> Unresolved reference: animation
BTW i added AndroidX from this
<
if this will make a difference | Those are Android-ktx Packages. You can read on any blog about android-ktx.
Implement KTX :
implementation "androidx.core:core-ktx:1.2.0"
This is releases of Android-KTX | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "android, kotlin"
} |
How to add to pythonpath in virtualenvironment
On my windows machine I created a virtual environement in conda where I run python 3.6. I want to permanently add a folder to the virtual python path environment. If I append something to `sys.path` it is lost on exiting python.
Outside of my virtual enviroment I can just add to user variables by going to advanced system settings. I have no idea how to do this within my virtual enviroment.
Any help is much appreciated. | "I can just add to user variables" just means adding an environment variable to the command shell. Virtualenv shouldn't (by default at least) clear environment variables. So it should just work if you already have `PYTHONPATH` set.
If you only want the path available to the virtualenv then modify the file called `Scripts/activate.bat` in the virtualenv folder and add the line:
set PYTHONPATH=path/to/dir | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 3,
"tags": "python, virtualenv"
} |
how to get a "lightbox" like behaviour in Qt
I have a Qt project where I'm using QGraphicsView framework, also I have popup windows on the scenes. (QDialogs)
When someone clicks on a certain button a popup window appears, and I'm invoking it with the `.exec()` method instead of `.show()` to make it the active one. Also I want to give it a visual effect like lightbox provides for html pages, so it would be obvious for the user too, that the background window won't communicate. Do you know any simple solution to make it work? or is it hard to implement in Qt? EDIT: I don't know if it's obvious of not, but it's a desktop application, not a web application. | Now I found another way to accomplish what I wanted. Like this:
`QWidget* mytranswidget = new QWidget(mybgwidget);
mytranswidget->setStyleSheet( "background:transparent; background-color:rgba(0,0,0,95)");
mytranswidget->setWindowFlag(Qt::FramelessWindowHint);
mytranswidget->setGeometry(mybgwidget->rect());
mytranswidget->show();`
I'm doing it at the beginning of my popup widget's constructor so it's being drawn before draw my popup, so it will be shown in the right order. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "qt, lightbox2"
} |
Can you use a C# library in a AMP-server?
Is it possible for me to build some database functionality in a C#-library (using LINQ 2 SQL) and then somehow import it into a php (joomla) project? | One way to do it is to register the .NET assembly as COM object (using `regasm.exe`) and then consume it from PHP. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, php, linq to sql, joomla"
} |
About the algebraic character of the solution of $\cos x=x$
The equation $x=\cos x$ is well-known because some facts. For example, with an old calculator, you can find approximations of the solution by typing any number and pressing the $\cos$ button repeatedly.
With Bolzano-Rolle combo, it is not difficult to show that this solution exists and is unique.
My question: **Is there some work about the rationality or trescendality of this solution**? Of course, $x$ is in radians. | If the solution is algebraic, then both $x$ and $\cos x$ are algebraic. This implies $\sin x=\pm\sqrt{1-\cos^2x}$ is also algebraic. So $e^{ix}=\cos x+i\sin x$ is also algebraic, which is not possible for any non-zero algebraic $x$ by Lindemann-Weierstrass Theorem.
Hence the solution is transcendental. | stackexchange-math | {
"answer_score": 4,
"question_score": 2,
"tags": "trigonometry, irrational numbers, transcendental numbers"
} |
Selectively prevent Session from being created
In my app, I have an external monitor that pings the app ever few minutes and measures its uptime / response time Every time the monitor connects, a new server session is created, so when I look at the number of sessions, it's always a minimum of 15, even during times where there are no actual users.
I tried to address this with putting the session creation code into a filter, but that doesn't seem to do it - I guess session automatically gets created when the user opens the first page?
all() { before = { if (actionName=='signin') { def session = request.session //creates session if not exists } } }
I can configure the monitor to pass in a paramter if I need to (i.e. < but not sure how to make sure the session isn't created. | Right now there is nothing you can do to prevent the session creation. See: <
Fortunately, until you are hitting high numbers of requests per second, this isn't a huge problem. One thing we did to get around the false data in our "currently active users" report, was to log the sessions to the database. We create a session record only when the user logs in. Then on specifically mapped URLs, we will "touch" that session record to update the last accessed time. The session record keeps track of user agent, IP, etc and is useful for many reasons. Doing something like this would get around the bogus session count. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "grails, session variables"
} |
How to modify incorrect date in a SQL Server database column in C#
I have a column in my SQL Server database of `nvarchar` datatype, and I store dates with `####/##/##` format in it. With my mistake some of dates store with `##/##/####` format.
How can I modify all dates in my database to format `####,##,##`?
Example: `01/01/2016` to `2016/01/01` | Use `CONVERT` function. Write simple SQL query:
UPDATE YourTable
-- get Date from nvarchar and format to yyyy/mm/dd
SET DateColumn = CONVERT(nvarchar,CONVERT(DATE, DateColumn, 103), 111)
-- only in rows that can be parsed from dd/mm/yyyy format
WHERE TRY_CONVERT(DATE, DateColumn, 103) IS NOT NULL
`103` \- `dd/mm/yyyy` format. `111` \- `yyyy/mm/dd` format. check this article
But actually you really should **store your dates in`DATE` type column not in `NVARCHAR`**. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "c#, sql server, date"
} |
Extruding along an area
I'd like to extrude a profile along the edge of an area. Furthermore, this profile should always stay in contact with the edges adjacent area. Imagine a ribbon that twists. The resulting area(s) are where my profile should extrude along with.
Profile (orange)   which is in permanent contact with the paths adjacent areas  . The origin point position is important.
3. Set the profile shape as a Bevel for your curve. It will align based on it's origin point.
_Add a Bezier Curve and tilt the control points. Add more control points if needed._
 - 4; ++i)
{
tmp = s.substr(i, 5);
// на этом месте вылетает, если строка меньше 4 символов
// ругается на то, что __pos больше длины строки
}
Почему `s.size() - 4` **положительное** число при `s.size() < 4`? | Дело в том, что значение, возвращаемое `s.size()`, имеет тип `unsigned` (беззнаковое), поэтому `s.size() - 4` всегда больше `0`.
Например, если длина равна 3, тогда 3 - 4 = -1, что соответствует `0xFFFFFFFF`, равное `MAX_INT`, т. е. примерно `2*10^9`).
В данном случаи поможет `(int)s.size()-4` | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c++"
} |
Unmarshalling to generic type in soap webservice anytype in xml
I am using soapwebservice. I have a generic class whose attribute in xsd is
<xs:element name="id" type="xs:anyType" minOccurs="0"/>
How can I pass value to this attribute through soap UI? I am using in xml `<id>amar</id>` which is not working properly. I am getting value null in java object populated by jaxb.
Where am I going wrong? I want it unmarshalled as a string type. Any help is appreciated. I searched and found link in stackoverflow. but even it does not give a clear insight into how to use in xml. | I solved it by using `<id xmlns:xs=" xsi:type="xs:string">myID</id>` | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "java, xml, web services, jaxb"
} |
Quickly restoring default notebook display color and font
(Not a duplicate. I've checked How to "undo" SetOptions (restore defaults)? and others.)
Suppose I change some display options, e.g.:
`SetOptions[EvaluationNotebook[], Background -> RGBColor[0.0, 0.0, 0.0], FontColor -> RGBColor[0, .85, .85], FontSize -> 20]`
Is there a way to restore all the default display options at once, in a line or two of code, without rebooting the notebook or digging through the menus? Something like `SetOptions[EvaluationNotebook[], Defaults]` or a similar idea? I haven't been able to find what I need in other questions. | Yes,
SetOptions[EvaluationNotebook[], Background -> Inherited, FontColor -> Inherited,
FontSize -> Inherited]
works in your case. Basically, when working with FrontEnd options `Inherited` is what you mean by "Default". But it doesn't always work through `SetOptions`, `CurrentValue` usually is a better choice.
* * *
**Update.** For `"UndefinedSymbolStyle"` discussed in the comments two solutions were found working:
SetOptions[EvaluationNotebook[], AutoStyleOptions -> {"UndefinedSymbolStyle" -> Inherited}]
CurrentValue[EvaluationNotebook[], {AutoStyleOptions, "UndefinedSymbolStyle"}] = Inherited | stackexchange-mathematica | {
"answer_score": 0,
"question_score": 1,
"tags": "notebooks, customization, stylesheet"
} |
Expressing relationship between two variables in pseudocode?
I have some pseudocode I am trying to analyze:
public static void test(float z) {
float y = 0;
for (float i = 1; i <= z; i++) {
if (y < z) {
y = 4 * i * i + 6;
}
}
return y;
}
From the function, I understand that `y = 4i^2 + 6` whenever `y < z`. However, I am having trouble capturing the relationship between y and z in an equation. I feel that it could be captured as a floor function (step function) -- for a certain range of numbers in z, y will have that specified value. | `y` becomes greater than `z` (and stops changing) for the first `i` such that `2*i^2 + 3 > z`. In other words, a minimal `i > sqrt((z - 3) / 2)`, which is `floor(sqrt((z - 3)/2)) + 1`. Now as you know `i`, compute `y`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, algorithm, function, time complexity, runtime"
} |
Browserify private global variable
How can I create a private custom global variable with `browserify`?
For example, a variable wich is accessible from all the browserify files (`require()`) but not outside the `browserify` block, `console` or others scripts cannot access to it.
I've tried global, but It's accessible from window / console.
EDIT: no answers? I really needs that to prevent self XSS (for eg, malicious scripts to stole user data or to send bad packets to delete his rooms ect...)
**Example code:**
Main.js
mycustomglobal.test = require('blabla');
mycustomglobal.test2 = require('blablablabla');
var users = require('./users.js');
Users.js file:
console.log(mycustomglobal);
// we need to be able to get test and test2
Console / or other script
console.log(mycustomglobal)
// we need to get undefined | I think something like this would suit your needs. You need to create a module, which I prefer to name `private_globals.js`:
var globals={};
module.exports=globals;
In your other files, you can use this module's exported object.
var globals=require("./private_globals")
console.log(globals.privateVar1);
globals.privateVar2=10;
I can think of no other way, unless you mess with source of browserify. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, browserify"
} |
What's the correct use of NSErrorRecoveryAttempting, NSError, and UIAlertView in iOS?
I'm having trouble finding examples of the correct way to use `NSError`, `UIAlertView`, and `NSErrorRecoveryAttempting` together on iOS. Most of the documentation and examples I can find cover the equivalent functionality on OS X, where the relevant behaviors are integrated by Cocoa. But in iOS it seems to be necessary do do this "by hand", and I can't find good examples of how it's done.
I'd very much appreciate a few examples of best practice in using information in NSError to support recovery attempts from `NSErrors` reported to the user. | According to Apple's documentation:
> Important: The NSError class is available on both Mac OS X and iOS. However, the error-responder and error-recovery APIs and mechanisms are available only in the Application Kit (Mac OS X).
So, I'm not sure if you can use `NSErrorRecoveryAttempting` even though it does appear to be defined in the documentation (it looks like this is an area of the UIKit docs that have not yet been updated after being copied from AppKit's documentation).
Here is how I handle errors in my code:
NSError *error = nil;
id result = [SomeClass doSomething:&error];
if (!result) {
NSLog(@"Do something failed: %@", error);
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Something failed!" message:@"There was an error doing something." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
[alert show];
return;
} | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 13,
"tags": "cocoa touch, ios, error handling, uialertview, nserror"
} |
How to figure out what spec version of api is implemented
I am migrating my app from jetty 7 to 9. jetty server 9 depends on org.eclipse.jetty.orbit:javax.servlet:3.0.0.v201112011016
I need to know what version of servlet-api is implemented by this artifact in order to add dependency on it. I want to add maven dependency only on api not implementation, so I could easily change servlet container later. | Google for Jetty documentation, click on the link, and find this page: < which indicates every Jetty version with the corresponding version of the servlet and JSP spec. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, maven, servlets, jetty"
} |
Can I push sub branch if the branch hasn't been merged yet?
We work the following way. I create separate branch for every issue and when the issue is done I push it to remote repo. I mean, I do
git branch issueXXX
git checkout issueXXX
//commits
git push origin issueXXX
After that team leader merges my branch to master.
Now I have a problem - I pushed the last issue, but team leader hasn't merged it to master yet and I have no idea when he will do it. However, my next issue is linked to the previous one. What should I do this way? I thought about creating sub branch from `issueXXX` and push it separately to remote, but I don't know if it possible as my previous issue hasn't been merged yet.
Could anyone say if is it possible or I should do something different (I just learn git)? | Yes, you can branch off `issueXXX` and push separately.
You'll now have two PRs. The latest will include the commits that already exist in the branch `issueXXX`. Once this branch is merged, the other PR will be left with the diff commits. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "git"
} |
java.lang.NoSuchMethodError: setBackground()
In my app I'm trying to set a Bitmap Image to `FrameLayout`, where the image came from `SQLite` database. I'm decoding that image converting it into `Drawable` and then setting it as background to `FrameLayout` but it gives me Error like `java.lang.NoSuchMethodError: android.widget.FrameLayout.setBackground()`
ByteArrayInputStream imageStream2= new ByteArrayInputStream(cardbackground);
Bitmap Imagebackground = BitmapFactory.decodeStream(imageStream2);
Drawable imagebakground=new BitmapDrawable(getResources(),Imagebackground);
framelayout.setBackground(imagebakground);
I'm using,,
android:minSdkVersion="14"
android:targetSdkVersion="19" | `setBackground()` method was added into API level 16. use `setBackgroundDrawable()` instead....
Drawable imagebakground = new BitmapDrawable(getResources(),Imagebackground);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
framelayout.setBackground(imagebakground);
} else {
frameLayout.setBackgroundDrawable(imagebakground);
} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "android, android drawable, android framelayout"
} |
Dump byte array as hexadecimal values
In JavaScript on Firefox, a Uint8Array shows like this on the console, using `console.log`:
Uint8Array […]
0: 131
1: 165
2: 116
3: 111
4: 112
How can I make it show as hexadecimal values, like this:
Uint8Array […]
0: 0x83
1: 0xa5
2: 0x74
3: 0x6f
4: 0x70
I'm trying to debug some websocket communication and have to look up the bytes in the format specification which only lists the values in hex. | You can't make the console do that (at least I know of no way to do that), but you could transform the array explicitly:
console.log([].map.call(yourArray, x => x.toString(16))
_edit_ — thanks for the correction; the typed arrays return new typed arrays from their `.map()`.
You could also make it a regular array with `Array.from()`. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "javascript, firefox"
} |
Rails nested form attributes are not being permits
I have a model named team group and a nested model salesforce_user_roles my form is sending me below information
<ActionController::Parameters {"create_salesforce_user"=>"0", "delete_salesforce_user"=>"1",
"salesforce_user_roles_attributes"=>
<ActionController::Parameters {
"0"=><ActionController::Parameters {"id"=>"11", "name"=>"Director, Channel Sales", "role_id"=>"00E7F000001AY", "_destroy"=>"false"}>,
"1577184453507"=><ActionController::Parameters {"name"=>"Eastern Sales Team", "role_id"=>"00E7F0000016xFLUAY", "_destroy"=>"false"} } >} >
For security, I am permitting only a few params. I am using `params.require(:team_group).permit(:name, :salesforce_user_roles_attributes)` to permit the nested model attribute but it's not saving anything in my database. How can I permit nested model params? | Can you confirm, have you added `accepts_nested_attributes_for` in model?
If yes, then follow this practice to permit them:
`params.require(:team_group).permit(:name, salesforce_user_roles_attributes: [:id, :name, :role_id, :_destroy])`
Thank you | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, nested forms"
} |
React onClick update useState variable and render updated
I know this question has been asked before, but the solutions were different from the way I structure/code my React app as shown below. How use one update/render based on the updated `listData`?
import React, { useState } from "react";
const PageName = () => {
const [listData, setlistData] = useState([]);
function add(){
let newrow = {};
listData.push(newrow);
setlistData(listData);
}
return (
<div>
{listData.length}
<button onClick={() => add()}>Add</button>
{
listData.map(function (row, i) {
return (
<p key={i}>row</p>
);
})
}
</div>
);
};
export default PageName; | If it is a state variable it is react's job to rerender. Your job is to ensure you are passing in a new reference to `setState()` without mutating the state.
Use `...` spread operator.
import React, { useState } from "react";
const PageName = () => {
const [listData, setlistData] = useState([]);
function add(){
let newrow = {};
let newListData = [...listData];
newListData.push(newrow);
setlistData(newListData);
}
return (
<div>
{listData.length}
<button onClick={() => add()}>Add</button>
{
listData.map(function (row, i) {
return (
<p key={i}>row</p>
);
})
}
</div>
);
};
export default PageName; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "reactjs"
} |
OfficeXmlFileException. How do I Solve this?
Exception in thread
"main" org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
How to solve this error? | As suggested in the thread you should use `XSSF` over `HSSF` or another higher version API. Also can you share your code snippet. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "exception, apache poi"
} |
Jquery FadeIn and Out on Multiple Divs
I'm usina script to fade div's in and out. It works fine on one but not not at all on the other one. Does anyone know why? Here is fiddle of it <
This is the JavaScript:
$(document).ready(function()
{ var book = $('#book');
var synopsis = $('#synopsis');
function runIt() {
synopsis.animate({opacity:'+=1'}, 1000);
synopsis.animate({opacity:'-=0.9'}, 2000, runIt).delay(2000);
}
runIt();}); | From what I can tell, you're wanting to do the same animation on `book` and `synopsis`, but you're only including the `animate` method on `synopsis`:
**EXAMPLE**
function runIt() {
synopsis.animate({opacity:'+=1'}, 1000);
synopsis.animate({opacity:'-=0.9'}, 2000, runIt).delay(2000);
book.animate({opacity:'+=1'}, 1000);
book.animate({opacity:'-=0.9'}, 2000, runIt).delay(2000);
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery, jquery animate, fadein, fadeout"
} |
Find the first quadratic form of the surface $z=z(x, y)$
Find the first quadratic form of the surface $z=z(x, y)$
The surface can be seen as $(0, 0, z)$? If so, then I have that $E=p^2,\, F=pq$ and $G=q^2$, where $p=\partial_xz,\, q=\partial_yz$. | **Hint:** Do not forget the coordinates $x$ and $y$, writing just $(0,0,z)$ you don't even get a surface! Consider $\varphi(x,y) = (x,y,z(x,y))$, and then compute $$E = \frac{\partial\varphi}{\partial x}\cdot \frac{\partial\varphi}{\partial x}, \quad F = \frac{\partial\varphi}{\partial y}\cdot \frac{\partial\varphi}{\partial x},\quad \mbox{and}\quad G = \frac{\partial\varphi}{\partial y}\cdot \frac{\partial\varphi}{\partial y}.$$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "calculus, geometry, differential geometry"
} |
The Torus is not homeomorphic to the unit circle
Let $T^2=S^1 \times S^1$ be a torus in $\mathbb{R}^4$, where $S^1:=\\{x \in \mathbb{R}^2 \mid \|x\|_2 = 1\\}$ is the unit circle. Does there exist a homeomorphic map $f: T^2 \to S^1$ ?
Intuitively this makes sense (somewhat), since $\mathbb{R}^4 \cong \mathbb{C}^2$ can be seen by considering the isomorphism $$ \mathbb{R}^4 \to \mathbb{C}^2, \; (a,b,c,d) \mapsto (a+\mathrm{i}b,c+\mathrm{i}d) $$ but I wonder whether it is possible to explicitely write down a homeomorphism $T^2 \to S^1$. I know that a homeomorphism is a continuous bijection with a continuous inverse map.
If not, I'd be interested in knowing how to start tackling this problem, because right now, I'm clueless as to where to start. | It is well-known that $\pi_1(S^1)\cong\Bbb Z$. From this it follows by functoriality that $\pi_1(S^1\times S^1)\cong\pi_1(S^1)\times\pi_1(S^1)\cong\Bbb Z\times\Bbb Z\cong\Bbb Z^2$.
Since they have different fundamental groups, they can't be homeomorphic. | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "general topology, continuity"
} |
Best way to get rows between specific month
I have a date being passed to my script in the format as yyyy-mm-dd.
I'm trying to grab all journal entries that fall within the month and year provided.
Should I just do this, where yyyy-mm is the date provided?
> SELECT * FROM table WHERE ts_date > yyyy-mm-01 AND ts_date < yyyy-mm-31
Seems like there might be a more efficient way of handling this. | I think you are looking for this:
-- Finds records from January
SELECT * FROM table WHERE MONTH(ts_date) = 1 AND YEAR(ts_date) = 2012; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql"
} |
How to set certain number of listener on one server and no listener on other server for same queue in spring amqp as we can not set 0 concurrency?
I have setup listeners on reply queues, I want those to be only on master (from where messages are queued) and other servers should have no listeners to reply queue. They should have listeners to all other queues.
Spring AMQP doesn't allow to set listener concurrency to be set to 0. So I cant set 0 listners to reply queue on slave servers.
How do I set 0 concurrency on slave servers for reply queues ? | I could do it using spring profiles. I just added "master" profile to all listener beans and activated master profile only on master server.
Few nice articles to begin with using profiles
<
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, spring, spring amqp"
} |
How do I go from truffle testrpc to mainnet?
I've been teaching myself ethereum via the stack `solidity/truffle/truffle-contract/testrpc/metamask`. I built a small dApp that runs on testrpc with proper unit tests which work great. I've written a function that I `truffle serve` that loads my contract named VEX from the local the file `f_deployed_contract`
$.getJSON(f_deployed_contract, function(data) {
App.contracts.VEX = TruffleContract(data);
App.contracts.VEX.setProvider(App.web3Provider);
});
Everything works! I was excited, so I deployed the contract of the working solidity code using a combination of Remix and Ether Wallet to the mainnet. It was mined and now lives here:
<
Now, how do I adjust my `TruffleContract` so I can use my dApp with metamask on the mainnet? | Using TruffleContract, you can just specify the address of your contract when trying to interact with it. From the documenation:
var MetaCoin = require("./path/to/MetaCoin.sol.js");
MetaCoin.at(contract_address).then(function(instance) {
//do promise things
}
So, Instead of using `Metacoin.deployed()` , which you're probably using, , you could use `.at(address)`.
Also, your contract lives at 0x4f5a4501f96cb95eeda376f4caa0b24f4dbbd796, not 0xe5e6c5d463815e339a2aac2e92594de595e2029e6448997799871d8cb2a5728b. The second one is the transaction which created your contract, the first one is the address of your contract. | stackexchange-ethereum | {
"answer_score": 1,
"question_score": 0,
"tags": "truffle, contract deployment, metamask, truffle contract"
} |
Decrease filesize when resizing with mogrify
I love the command line options of imagemagick. Mogrify is great to resize images and change quality, which is what I use most often. However, I have noted that the filesize if often larger than what it should be. Especially with small images. For instance, I have a regular 640px (width) photo, which I change to quality 80 and a width of 80px:
mogrify -quality 80 -resize 80 file.jpg
Works well and my image gets resized and the quality is changed to 80. However, the filesize is around 40Kb. For such a tiny image, that is huge! When I use mtPaint, and open the file and save it (not changing anything, just CTRL+O, CTRL+S), the filesize decreases with more than 95% to less than 2Kb! I have seen this is often the case.
What goes wrong? | I found the answer... it was in the "metadata"! Apparently this easily weighs about 18 Kb per image, so in the original you might not note this, but in the tiny resize it means 18 Kb + 2 Kb = 20 Kb total filesize. They significantly increased by doing:
`mogrify -strip file.jpg` | stackexchange-askubuntu | {
"answer_score": 7,
"question_score": 5,
"tags": "mogrify"
} |
What is the MGF of $X_{(1)}$ when $X_1,X_2$ are i.i.d Gamma variables?
I want to find the moment generating function (MGF) of the order statistic $X_{(1)}$ where $X_1, X_2$ are iid $\Gamma(\alpha, 1)$.
First attempt was to simply find the order statistic pdf in the usual way, followed by finding the the MGF in the usual way. However, things got tricky when calculating the CDF for the gamma distribution. I think there is a trick that I might be missing.
EDIT:
This is the pdf for the version of the gamma distribution I am using:
$$f(x) = \frac{\beta^\alpha}{\Gamma (\alpha)} x^{\alpha -1} e^{-\beta x}$$ | The CDF for your $\Gamma(\alpha,1)$ distribution can be written in terms of the Whittaker M function:
$$F(x) = \frac{x^{\alpha/2} e^{-x/2}}{\Gamma(\alpha+2)} M(\alpha/2,(1+\alpha)/2,x) + \frac{x^\alpha e^{-x} (1+\alpha)}{\Gamma(\alpha+2)}$$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "probability distributions, moment generating functions, order statistics, gamma distribution"
} |
Returning multiple values in UDF
I have written an AggregateFactory Vertica UDF which returns a single value
getReturnTypes(si,columnTypes args,columnTypes returnTypes){
returnTypes.addVarbinary(512);
//I want to add second returnType
returnTypes.addFloat("");
}
getProtoType(si,columnTypes args,columnTypes returnTypes){
returnTypes.addVarbinary(512);
//I want to add second returnType
returnTypes.addFloat("");
}
this is not working, how can I return two values from an AggregateFactory UDF? | You cannot. User Defined Aggregate Functions (as explained in the fine manual%7CAggregate%2520Functions%2520\(UDAFs\)%7C_____0)) return ONE value per group. You might want to write a User Defined **Transform** Function (maybe a multi-phase Transform Function). | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "user defined functions, vertica"
} |
Volume question on cuboid and sphere
A fish tank is in the shape of a cuboid with base $80$cm by $40$cm. The height of the tank is $35$cm.
i) Find the volume of the water in the tank when it is filled up to the depth of $30$cm
$$V= 80 \times 40 \times 30 = 96000\ \text{cm}^3$$
ii) $2400$ glass marbles with a radius of $0.5$cm, are placed in the tank. How much will the water level rise?
The answer to this question is $0.393$cm ($3$sf). However, I just don’t know how to approach the working of this part of the question. This question is from a past paper of an exam I’m studying for. It provides the answers to the questions but not the actual working which is how I know the answer. Could anyone do and explain the working for this question to justify the answer? | Firstly: find the Scale Factor($SF$):
$$30\cdot (SF)^{3} = 96000$$
Evaluating this we have that:
$$(SF)^{3} = \frac{96000}{30} = 14.736$$
Now that we have a $SF$ we need to find the volume of the marbles. Using the formula: $$\frac{4}{3}\pi r^{3}$$
Subbing in we find that $$\frac{4}{3}\cdot\pi\cdot0.5^{3} = 0.5236$$ Since there are $2400$ marbles we multiply by that quantity yielding $1256.64$.
Next we add this to our original volume of $96000$ which gives us $$96000 + 1256.64= 97,256.64 $$
Using our $SF$ to find the height again and letting Height $= h$:
$$h\cdot (SF)^{3} = 97,256.64$$
Therefore $h = 30.393$ after some simplification.
To get the final answer we have to subtract the original height from the final height. This gives us: $30.393 - 30 = 0.393$. Which according to your paper is the answer. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "algebra precalculus, volume"
} |
How to leave empty the search pattern in Directory.GetFiles()
`Directory.Getfiles(@"path","searchpattern",SearchOption.AllDirectories)`
How can I leave the pattern empty?
I want to get all files of a directory and its subdirectories. But I don't want a search pattern.
`""` Doesn't work when I do it no results is shown.
I tried writing `null` but it doesn't work either. | You can use Wildcard symbols. `Directory.Getfiles(@"path","*",SearchOption.AllDirectories)` should be what you're looking for.
You can check the official documentation here | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "c#"
} |
Magento 2.4.3-p3 cron not running, but works manually
This is an intermittent problem as sometimes order confirmation emails are received, i.e. the cronjob runs automatically and doesn't remain as 'pending' in cron_schedule table. But most of the time it's stuck as pending as cron doesn't run. (php bin/magento cron:run works).
I'm getting mulitple errors in var/log/magento.cron.log:
Magento supports PHP 7.3.0 or later. Please read
Although, PHP 7.4.32 is installed and crontab is valid:
/opt/cpanel/ea-php72/root/usr/bin/php /home/****/public_html/bin/magento cron:run 2>&1 | grep -v "Ran jobs by schedule" >> /home/****/public_html/var/log/magento.cron.log
Any ideas? | That path looks like php7.2
/opt/cpanel/ea- **php72** /root/usr/bin/php -v
Paste above command in console, I bet it will show 7.2
And... What about pasting just **php -v**?
Not sure what would be the right path in your server, maybe replacing that **ea-php72** by **ea-php74**? If not, contact your hosting provider | stackexchange-magento | {
"answer_score": 1,
"question_score": 1,
"tags": "cron, magento2.4.3"
} |
How to add security while using GET and POST method?
I developed a small application Contact Manager and while updating the contacts, the contact id is being sent using GET method. But a user can change the Id and edit any contact, how can i add security to it?
<td>
<a href="home.php?action=update&contactid=<?php echo $contact->contact_id; ?>">Update</a>
</td>
_ & **contactid=1**_
If i change the id to some other number, another contact will show up. | You can't control what the client asks the server to do.
If you want to add restrictions on who can modify particular contacts then you need to Authenticate (username + password, client SSL cert, OpenID, etc) users and then check if they are Authorized (this will depend on the business logic you decide on) to modify the entry in question. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "php, security, post, get"
} |
Download Excel file from web url using Ruby on Rails
I am trying to create an application that crawls a website providing free financial data in .xlsx format. They upload files once a month and not always on the same day.
Is it possible to download any new files from a specific URL and dump it into my S3 bucket, before reading it into a database? I have read up about creating a worker using Sidekiq. I expect that this will play a crucial part in the process.
Can anybody perhaps give some advice or point me to a tutorial that can help? | Yes, you can, and you don't even need `Sidekiq`. Take a look at AWS SDK for Ruby, and do the following things:
1. Just write a ruby script that downloads the xlsx files then upload to S3. Be sure the script starts with `#!/usr/bin/env ruby`, and give it execute permission.
2. Add this script to your crontab jobs, and make it run everyday. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "ruby on rails, ruby, excel, amazon s3"
} |
Kohana Exception: A valid cookie salt is required
Проблема с captcha kohana... сделал все, как нужно вроде, но выдает такую ошибку. Скажите, как исправить можно?
!alt text | `Cookie::$salt = '1234567890..'; //` google
Прописать в `bootstrap.php` до подключения модулей | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "php, kohana"
} |
Django template for loop and display first X matches
Not sure exactly how to phrase my problem but I essentially want to loop through a list and show the first 4 matches only.
{% for reward_type in reward_types %}
<h2>{{ reward_type.name }}</h2>
<div class="reward_category">
{% for category in reward_categories %}
{% if category.reward_type == reward_type %}
.
.
Show the first 4 matches
.
.
{% endif %}
{% endfor %}
</div>
{% endfor %} | Use your view function to prepare your list before passing it to the template.
Django template isn't intended for complex matching like this.
Exactly as discussed ;-) | stackexchange-stackoverflow | {
"answer_score": -6,
"question_score": 3,
"tags": "django, templates"
} |
No zero before the decimal point or after second decimal
I have simple calculating in my app
-(IBAction)calculate {
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setRoundingMode: NSNumberFormatterRoundHalfUp];
[nf setMaximumFractionDigits: 2];
float value1 = [[nf numberFromString: textField1.text] floatValue];
float value2 = [[nf numberFromString: textField2.text] floatValue];
float x = value1 * value2 / 100;
label2.text = [nf stringFromNumber: [NSNumber numberWithFloat: x]];
[nf release];
}
Now, when I calculate result looks like this: `,75` or `64,5`
I need to my result looks like this: `0,75` or `64,50`
**My problem is there no zero before the decimal point or after second decimal** | Where you set your text in the UILabel, use
label2.text = [NSString stringWithFormat:@"%.2f",x];
This will ensure you get 2 decimal places. You don't even need a number formatter. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "ios, xcode, zero, decimal point"
} |
How to automatically convert a MySQL column to lowercase
Is there a property that I can add to a column so that it converts its value to lowercase? Instead of doing it for every single value through PHP? | You could probably do it through a trigger that fires on insert or update. Myself, I'd rather just create a view that has a lower-case version of the column in question. The SQL for the view might look like
SELECT ID, LOWER(MY_COLUMN) AS MY_COLUMN_LOWERCASE
FROM MY_TABLE; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "mysql, sql"
} |
Java Mallet LDA keyword distributions
I have used Java-Mallet API for topic modelling with LDA. The API produce following results: topic : keyword1 (count), keyword2 (count)
For example
topic 0 : file (12423), test (3123) ... topic 1 : class (2415), test (314) ...
Is it right that topic 0 = file (12423/12423+3123 ....), test(3123/12423+3123). | That's one way to evaluate probabilities. You can also add a smoothing parameter (usually 0.01) to each value, and add 0.01 times the size of the vocabulary to the denominator to make it add up to 1.0. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, lda, topic modeling, mallet"
} |
C# Regular Expression To Match Number at end of a string
I have a string that ends with _[a number] e.g. _1 _12 etc etc.
I'm looking for a regular expression to pull out this number | Try this:
(\d+)$
Here is an example of how to use it:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
Regex regex = new Regex(@"(\d+)$",
RegexOptions.Compiled |
RegexOptions.CultureInvariant);
Match match = regex.Match("_1_12");
if (match.Success)
Console.WriteLine(match.Groups[1].Value);
}
} | stackexchange-stackoverflow | {
"answer_score": 29,
"question_score": 11,
"tags": "c#"
} |
Add class to List item but changes over time
I have a list of tweets as list items.
<ul>
<li><a href="#">Tweet 1</a></li>
<li><a href="#">Tweet 2</a></li>
<li><a href="#">Tweet 3</a></li>
</ul>
I need to get the first tweet to show then change after say 5 seconds.
I am not sure what you call this and have been searching the web for over 4 hours now. Its not a feed because I already have the list of tweets but I am not sure what to use to get the effect I want.
Please can you point out what this is called so I can finally research the correct thing. | Create an ID for the `ul` element so you can find it easily:
<ul id="tweetList">
<li><a href="#">Tweet 1</a></li>
<li><a href="#">Tweet 2</a></li>
<li><a href="#">Tweet 3</a></li>
</ul>
then, you can do this:
var firstTweet = $('#tweetList li:first()');
firstTweet.addClass('tempClass'); //add the class
setTimeout(function(){
//after 5k ms, remove it.
firstTweet.removeClass('tempclass');
}, 5000); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery"
} |
Zooming to selected feature using PyQGIS
I want to create a function that selects a feature and zooms to it (similar in QGIS). Therefore there is following function:
QgsMapLayerRegistry.instance().addMapLayer(self.vlayer)
def zoomTo(self):
layer = self.vlayer
atable = self.ui.table
selectList=[]
for i in atable.selectionModel().selectedRows():
ID = atable.item(i.row(),0).text()
selectList.append(int(ID))
layer.setSelectedFeatures(selectList)
The selected features are highlighted on the map. But I have no idea how to make a "zoom" to the selected features or some kind of focus them in the middle of the map. | You need to set the extents of the map canvas to the extents of the selections:
box = layer.boundingBoxOfSelected()
iface.mapCanvas().setExtent(box)
iface.mapCanvas().refresh() | stackexchange-gis | {
"answer_score": 27,
"question_score": 17,
"tags": "pyqgis, features, select, zoom"
} |
Update TCP load balancing to HTTP(S) load balancing on GCP
I use kubernetes cluster on Google Cloud Plataform and I want to change my load balancer from "TCP load balancing" to "HTTP(S) load balancing" (layer 7).
Currently the configuration about "TCP load balancing" is:
{
GlobalArrayList = new GlobalArrayList<String>();
}
RealmMainActivityMainActivity `ThisApp GlobalArrayList;` MainActivityRealmResolts
//Realm
Realm mRealm = Realm.getDefaultInstance();
mRealmResults = mRealm.where(jobCategory.class).findAll();
mRealm.addChangeListener(mRealmListener);
//
GlobalArrayList= (TaskApp) this.getApplication();
GlobalArrayList.GlobalArrayList();
for (int i = 0; i < mCategoryRealmResults.size(); i++) {
GlobalArrayList.add(mRealmResults.get(i).getContents());
}
GlobalArrayList.add(addArrayList.add | ##
ArrayList`ThisApp``GlobalArrayList`
`ThisApp``GlobalArrayList`
`GlobalArrayList.GlobalArrayList.add(mRealmResults.get(i).getContents());`
##
`GlobalArrayList`
//
public ArrayList<String> GlobalArrayList;
RealmResultscontents`contentsList`
//
public void GlobalArrayList(){
`init***`
//
GlobalArrayList= (TaskApp) this.getApplication();
Application`app`
Java
public class ThisApp extends Application {
//
public ArrayList<String> contentsList;
//
public void initContentsList(){
contentsList = new ArrayList<String>();
}
app = (ThisApp) this.getApplication();
app.initContentsList();
for (int i = 0; i < mCategoryRealmResults.size(); i++) {
app.contentsList.add(mRealmResults.get(i).getContents());
} | stackexchange-ja_stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "android, java"
} |
Exercise about a limit with greatest integer function
> Let:
>
> $$f(x) := \begin{cases} x+3 &\text{, if } x\in (-2,0) \\\ 4 &\text{, if } x=0 \\\ 2x+5 &\text{, if } 0<x<1\end{cases}\;.$$
>
> Then find $\lim_{x\to 0^-} f([x-\tan x])$, where $[\cdot]$ is greatest integer.
Since $x$ is approaching zero from the negative side, $x>\tan x$
Therefore $[x-\tan x] =0$
$$\lim_{x\to 0^-}f( [x-\tan x])=[x+\tan x] +3 =3$$
But the right answer is 4.
Basically, I am having a problem in choosing the right function for the given limit, because $f(x)=4$ for $x=0$, but $x$ actually isn’t 0, then how can it be the answer? | For $-\pi/2 < x < 0$ you have $\tan x < x < 0$, hence $x - \tan x > 0$. On the other hand, in a suitable left neighborhood $-\sigma < x <0$ of $0$ (with $\sigma > 0$), you have also $2x < \tan x$, therefore $x - \tan x < -2x$; moreover you can also choose $\sigma$ so small that $-2x < 1$. Thus $-\sigma < x < 0 \Rightarrow 0 < x - \tan x < 1$ and this entails $[x - \tan x] = 0$ everywhere in the small left neighborhood $]-\sigma , 0[$ of $0$.
Finally, you find:
$$\lim_{x \to 0^-} f([x - \tan x]) = \lim_{x\to 0^-} f(0) = f(0)\; ,$$
therefore you have to check the text of your exercise: if $f(0) = 0$ as you wrote at the beginning, the answer is $0$; if $f(0) = 4$ as you wrote at the end, the answer is $4$. ;-) | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "real analysis, calculus, limits"
} |
kivy undefined symbols text_input
In my app I make use of TextInput in the .kv file. When I run the app on Android on my HTC One X+ (Cyanogenmod OS 10) and I press the TextInput field to type my Keyboard appears, but also it automatically adds this symbol: (symbol for encoding doesn't support the character). So pressing TextInput automatically inserts as text. The strange thing is that this doesn't happen on my PC and also not when using the Kivy Launcher on my phone. It only happens when I use Buildozer to package the app and run it on my phone.
TextInput:
id: txt_field
text: "What you type here"
font_size: '20sp'
multiline: False
size_hint_x: .8
Did someone else also got this problem? I could make an input filter, but I'm curious to why this happens. | This issue has been solved in the stable and the master versions you just need to clean your existing builds and the package cache. Run the following command. From your app dir.
bulldozer android clean
rm -rf ~/.buildozer/android/packages
rm -rf ~/.buildozer/android/cache
Then just rebuild your apk. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, kivy, textinput, undefined symbol"
} |
What do you call a rope you set to return to an original point?
Say, you don't want to get lost in a tunnel, so you set a rope that leads back to the entrance (or likewise follow another rope set by another person).
I searched for guide rope and guiding rope but I'm not sure whether it's the right word:
!
Example sentence (in case it is needed):
> The male can find a female miles away, as if they were following a [...] | If you want to be mythological, the term is **Ariadne's Thread**. When Theseus entered the Labyrinth to kill the minotaur, he unwound a ball of thread given to him by Ariadne. Following the thread allowed him to escape the maze. | stackexchange-english | {
"answer_score": 11,
"question_score": 2,
"tags": "single word requests"
} |
Programmatically change Required background modes
I have an app that need Location Based Services in the background. So in info.plist I setrRequired background modes to "App registers for location updates". and everything works fine.
My question is, how can I disable it running in background? Is it possible to add an option and let users set it on/off?
As I know info.plist can not be change programmatically so how can I do this? | The key is the description - it supports registering for location updates. So all you should have to do is tell your location manager to stop updating when the app goes into the background (or before) and it should then not be using location updates in the background.
There is no way to re-define the info.plist abilities of the app at runtime. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "iphone, ios, ipad, core location, cllocationmanager"
} |
Modify a variable in remote bash script
I want to modify an existing variable on a remote machine. On a local machine I use 'sed' for that. But how can I achieve this on a remote machine?
comlink.sh: The remote file containing the variable that should be changed.
#!/bin/bash
test=1
new=2
ready=0
How I change that variable locally:
sed 's/ready=.*/ready=1/' /home/pi/comlink.sh > tmp
mv tmp /home/pi/comlink.sh
My approach of what I want to achieve remotely:
sed 's/ready=.*/ready=1/' ssh pi@[myIP] /home/pi/comlink.sh > tmp
mv ssh pi@[myIP] tmp /home/pi/comlink.sh
But this is not the right way or syntax. I think I might need some help here. Thanks! | Do this: it's really just a quoting challenge -- execute the sed command remotely
ssh pi@ip "sed -i 's/ready=.*/ready=1/' /home/pi/comlink.sh" | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "bash, shell, variables, ssh, sed"
} |
"java -version" command has different results in Inno Setup
I am trying to build up a installer for my software by Inno Setup.
But a weird thing happened
I try to run the Pascal code to get the Java version in Inno Setup script
Exec('cmd.exe', '/c java -version 2> ' + tempDirPath+jdkVersionInfoFile, '',
SW_HIDE, ewWaitUntilTerminated, ResultCode)
The result is `java verison "1.6"`.
And when I typed the command `java -version` in console window, then I get the result is `java version "1.8"`.
Why are the results different? | While I cannot imagine how exactly this happens on your machine without more details, differences like this typically stem from the fact that Inno Setup is 32-bit application.
It's likely that 32-bit version of Java is run by Inno Setup (32-bit application) and 64-bit version of Java is run by Windows command interpreter (64-bit application). And you have different versions installed for these platforms.
(Assuming that you run 64-bit version of Windows).
See Install Mode: 32-bit vs. 64-bit article in Inno Setup documentation. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "java, inno setup, pascalscript"
} |
Why do Python's trigonometry functions give different results than my calculator?
I was trying to make a simple calculation program for trigonometry with right angled triangles given the possible values of "x", "none", and two others with numbers. I know about the functions math.cos(), math.sin(), etc. but they are giving me different numbers from what my calculator is giving me.Here's an example of some of the code I was trying to use:
if hyp == "none" and opp == "x":
answer = adj * math.tan(ang)
After entering the values `None` for hyp, `6` for adj, `x` for opp, and `37` for ang, I receive the value:
-289.036
On my calculator, the same is met with '4.521'. Why are they giving different results? | Take a look at the documentation for the `math.tan` function in Python:
> `math.tan(x)`
>
> Return the tangent of _x_ radians
This applies to all the trigonometric functions. You must convert degrees to radians first, with the `math.radians` function:
math.tan(math.radians(ang)) | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 0,
"tags": "python, math"
} |
Scala/Akka Future onComplete Success compiler error
I have an actor that waits for the results of a future. Calling onComplete of the future causes a compiler error:
> error: constructor cannot be instantiated to expected type [scalac] found : akka.actor.Status.Success [scalac] required: scala.util.Try[Iterable[Any]] [scalac] case Success(result: List[PCBInstanceStats]) => { [scalac] ^
Actor's receive:
case "pcbStatus" => {
val future = Future.traverse(context.children)(x => {
(x ? "reportStatus")(5 seconds)
})
future.onComplete {
case Success(result: List[PCBInstanceStats]) => {
self ! result
}
}
Not sure how to provide the right type of parameter for this. | [scalac] found : akka.actor.Status.Success
That means the compiler sees your `Success` and thinks it's an `akka.actor.Status.Success`, when really you mean a `scala.util.Success`. You probably have an import somewhere that is importing the akka Success class.
Either remove the import for `akka.actor.Status.Success`, or resolve the ambiguity by either fully-qualifying the class, or using an import alias, e.g.
import scala.util.{Success => ScalaSuccess}
future.onComplete {
case ScalaSuccess(result) => ...
// or
case scala.util.Success(result) => ...
} | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 5,
"tags": "scala, akka, actor, future"
} |
Master.FindControl giving NullReferenceException
I am trying this
if (!IsPostBack)
{
Label theLabel = Master.FindControl("HeadingLabel") as Label;
if (theLabel != null)
{
theLabel.Text = "Our Valuable Customers ";
}
}
i am getting a NullRefernceException error ,i am following a video series ,so i am doing the same ,but not able to run the code.He is is using .Net version =2.0 and i am using 4.0.
here is code for my master page
<asp:Label ID="HeadingLabel" runat="server" Font-Bold="True"Text="Online Shopping Website"></asp:Label> | Looks like `Master` is null. If so, the page you're on isn't actually based on the master page.
Make sure the `aspx` actually has a master page specified in the `@Page` directive. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, asp.net, master pages"
} |
Regex that checks every instance of cast() is preceded by safe_
I'm very new to making Regexes and wondering how to check a string (SQL Query) where every instance of "cast()" is directly preceded by "safe_" (i.e. if "cast()" is used, it's always used as "safe_cast()") | This expression
(?<=\bsafe_)cast\(\)
might likely check for those with `safe_`, and
(?<!\bsafe_)cast\(\)
for those without.
The expression is explained on the top right panel of this demo if you wish to explore/simplify/modify it.
### DEMO 2
* * *
Edit:
If you wish to exclude `safe_cast()`, this expression might be an option:
^(?!(.*\bsafe_cast\(\))).*$
### DEMO 3 | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "regex"
} |
Mesh Analysis does not display anything
I'm trying to use the mesh analysis in the properties panel to inspect my model for the thickness, I want the visual tools rather than the plain selection from the Print3D add-on. However when I check it on, it does nothing. Am I missing something here?
Thanks, Matthew | Found the issue, I was using matcaps, mustn't like the combination of matcaps and the mesh analysis. | stackexchange-blender | {
"answer_score": 3,
"question_score": 1,
"tags": "mesh, 3d view"
} |
cypher connections to a group of nodes
With this cypher query I'm able to find all nodes that I want
match (t:FacebookPage)-[l:LIKED_BY]-(p:FacebookPost)-[r:WRITTEN_BY]-(n:FacebookAccount)
where n.facebookId IN ["alpha", "beta", "gamma"]
return t,l,p,r,n
Now I would like a subset of theese nodes: the t-nodes that are connected to more than one distinct n-node. Thanks in advance. | you can use `WITH` and `WHERE` clause to do additional filtering. Like so
match (t:FacebookPage)-[l:LIKED_BY]-(p:FacebookPost)-[r:WRITTEN_BY]-(n:FacebookAccount)
where n.facebookId IN ["alpha", "beta", "gamma"]
with t,count(distinct(n)) as count where count > 1
return t
If you want to return all relationships I think you must do two `MATCH` clause, because filtering works depending on what your return(aggregate)
match (t:FacebookPage)-[l:LIKED_BY]-(p:FacebookPost)-[r:WRITTEN_BY]-(n:FacebookAccount)
where n.facebookId IN ["alpha", "beta", "gamma"]
with t,count(distinct(n)) as count where count > 1
match (t)-[l1:LIKED_BY]-(p1:FacebookPost)-[r1:WRITTEN_BY]-(n1:FacebookAccount)
return t,l1,p1,r1,n1 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "neo4j, cypher, graph databases"
} |
Are there any written records of Norse mythology dated prior to Christianization?
As I understand it, most of what we know about Norse mythology is based on texts written in sagas by Christians in the late Middle Ages. Do we have any contemporary accounts of Norse mythology from the period in which it was still believed? | Aside from some short inscriptions on stone, no.
The received texts of the sagas generally all date to after about 1000 A.D. and were written or copied at times when Christianization had taken hold.
That said, however, it is important to remember that it is likely that the received texts may, in many cases be close copies of manuscripts written during pagan times.
Also, do not assume that Christianization was universal. In many cases there were scribes and others who were only nominally Christian or sympathized with old customs. Just as a single example of this, Yule continued to be celebrated in Scotland for centuries and centuries after Christianization. | stackexchange-history | {
"answer_score": 3,
"question_score": 7,
"tags": "religion, vikings, sources, norse mythology"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.