INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Writing PHP opcode and have it executed. How to do? How can I write PHP opcode, save it in a file and make the Zend Engine execute it? Any method or hack is welcome, as long as it does the trick.
There's a couple of user-space methods (from plugins) that can deal with Opcodes. * < (and < * < / < Neither produces plain text however because the opcodes are not designed to be a user-writable language (unlike Parrot).
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 11, "tags": "php, opcode, php internals" }
$x^y = y^x$ what is $y$? So today I came across an answer on MathStackExchange. I read it and found it well explained. But I stuck on a step where the user write "Solve using the properties of $W$ function". I don't know what property the user used. What I know about Lambert $W$ function is that, $W(x) = f^{-1} (x)$, where $f(x) = x\cdot e^x$. Can anyone solve the question or just tell me what the property the answerer used in the question which I have linked to you?
The step in question is how do the properties of the Lambert $W$ function, give us the following $$-\dfrac{y\log(x)}{x}\exp\left(-\dfrac{y\log(x)}{x}\right) = -\dfrac{\log(x)}{x}\implies-xy\log(x) = \operatorname{W}\left(-\dfrac{\log(x)}{x}\right).$$ There is actually a typo in the linked answer, (which I corrected), the desired result should be $$-\dfrac{y\log(x)}{x}\exp\left(-\dfrac{y\log(x)}{x}\right)= -\frac{\log(x)}{x}\implies= -\frac{y\log(x)}{x} = \operatorname{W}\left(-\dfrac{\log(x)}{x}\right).$$ Here we will use the fact that $$z = we^w \iff w = W(z).$$ We first make the substitutions $$s = -\frac{y\log(x)}{x},\qquad z = -\frac{\log(x)}{x},$$ and rewrite the first equation as $se^{s} =z.$ Using the noted property of $W$, then, we can rewrite this as $s = W(z)$, which reversing our substitutions gives: $$-\frac{y\log(x)}{x} = W\left(-\frac{\log(x)}{x}\right).$$
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "lambert w" }
Keycloak: getting back from user profile page In my application I have a link that redirects to the user's account page on the Keycloak server. In this page the user can update his personal information. The problem is that after entering his account page the user has no way to get back to the application. There's a way to let the user get back without editing the page theme?
I found the answer by looking at the freemaker template. In my case I had to: 1. Set the application URL in the **Base URL** option in the Keycloak client settings. 2. Append the parameter `?referrer=<Client ID>` on the URL that links to the user profile page. ie ` ID>` With these two settings the link to go back to the application will be visible.
stackexchange-stackoverflow
{ "answer_score": 23, "question_score": 7, "tags": "jboss, keycloak, keycloak services" }
How do i get with GetFiles only images and text files? This will get all the files: static void DirSearch(string sDir) { try { foreach (string d in Directory.GetDirectories(sDir)) { foreach (string f in Directory.GetFiles(d)) { Console.WriteLine(f); } DirSearch(d); } } catch (System.Exception excpt) { Console.WriteLine(excpt.Message); } } But I want to get all or most of images types files and text files only.
Here is something you can do you need to understand `Linq && Lambda Extension Methods \ Expressions` var fi = new System.IO.DirectoryInfo(sDir).GetFiles(). Where(f => !(f.FullName.EndsWith(".jpg") || f.Name.EndsWith(".txt"))).ToArray();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -5, "tags": "c#, .net, winforms" }
Is there a way to print an entire array and not just printing the contents of the array by iterating through them? In `C`, is there a way to print an entire array. For example print (in full) each row from a 2D array, NOT iterating through its contents and printing them independently? Below is an example of how I imagined the code would be: int main() { int Numbers[4][4] = {{5, 1, 1, 6}, {2, 2}, {3, 3, 3}, {4, 4, 4}}; for (int i=0; i<=3; i++){ printf("%i \n", Numbers[i]); } return 0; } I expect the output to be along the lines of: {5, 1, 1, 6} {2, 2} {3, 3, 3} {4, 4, 4} However, when run the code I get the following output -414054224 -414054208 -414054192 -414054176
No, there is no way to do what you are asking. You cannot do operations on whole arrays in C; you must iterate through and print each element separately. Array expressions in C lose their "array-ness" under most circumstances.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "arrays, c, printf" }
H2 Database : how unlock a database file for backup copy? I'm using h2database version 1.4.200 with hibernate for saving in database file. My programs needs to regulary save backup and I don't care about corruption's file's problems. After looking the documentation : < I decided to use parameter LOCK_FILE=NO. I saved my models and keeped the entity manager opened. When I tryed to copy the db file "data.mv.db", my database file was always locked even if I used Lock_FILE=NO. Parameter LOCK_FILE=NO, does it work correctly ? There is a alternative for copying speedly my db-file in java ?
Any attempt to copy the file when database is in use is a way to get a possibly corrupted backup. H2 has BACKUP command for online backups. BACKUP TO 'filename.zip' This command creates a ZIP archive with a consistent copy of the database file.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "backup, h2, lockfile" }
Can I exclude thumbs from ManipulationEnabled? I have FrameworkElements that have IsManipulationEnabled set to true, that's working nicely, but, there is an issue at my case, its that there is resizing thumbs at the FrameworkElements style. I need to exclude the thumbs from touch manipulation, because currently when the user moves the thumb with his finger, all the shape is moved instead of resizing it with drag delta at the thumb. I tried to put IsManipulationEnabled= false at the constructor of the thumbs, but, it didn't work. Any idea please ?
I've solve the issue! Ironically, I have set `IsManipulationEnabled` for thumbs to true, then inside thumbs I: protected override void OnManipulationStarting(ManipulationStartingEventArgs e) { e.Cancel(); } that's it Now, thumbs within shape style receive mouse events from touch, and the shape receives manipulation events :-)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "wpf, touch" }
Find a Line Not Tangent to Any Point on a Curve I am given the following: Let $C$ be a simple closed curve in $\mathbb{R}^2$ and let $p \in C$. Show that there exists a line in $\mathbb{R}^2$, passing through $p$, that is not tangent to $C$ at any point. First, we can assume that $p$ is the origin. My first attempt was to form the map $C \to \mathbb{R}P^1$ that maps $x \in C$ to the line joining $x$ and $p$. My hope was that the critical points of this map would correspond to tangent lines. Then I could use Sard's Theorem. I couldn't show that. My next thought was that we get a map $S^1 \to C \to \mathbb{R}P^1$ and maybe I could show something there. But, I could not think of anything. Any help is appreciated.
I guess we assume the curve having a non-singular $C^1$ parametrization, in which case your idea seems fine. Let $t\in S^1$ be the parameter and take e.g. $\theta(t)$ to be the angle (mod $2\pi$) of the line you mention wrt some fixed line. The critical values $\\{\theta(t): \theta'(t)=0\\}$ correspond to tangents and are of zero measure.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "differential topology" }
How to create special layout folder for galaxy Note 8? I have a layout folder for galaxy note 2 named **layout-large-xhdpi-1280x800**. Now I want to create a layout for Galaxy note 8 that is larger (8in). Which folder layout should I create? I have tested **layout-xlarge-xhdpi-1280x800**. but it is ignored and the layout in **layout-large-xhdpi-1280x800** is selected.
I think your problem can be fixed using changing layout folder name to **tvdpi**. Try using **tvdpi** , like Nexus 7
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, android layout, galaxy" }
COCOAPOD file not found for Xcode unit tests only I have added PLCrashReporter using POD use_frameworks! pod 'PLCrashReporter' I have imported following files in Briding Header to use in my swift project #import <CrashReporter/CrashReporter.h> #import <CrashReporter/PLCrashReport.h> If I run the project, then I don't get any problem and it works as expected If I do xcode unit-test I get the following error ( _Xcode->Product->Test_ ) ![enter image description here](
Add the pods separately for _Target_ and _TargetTests_ Make the following changes in **POD** file target ‘Target’ do platform :ios, ‘8.0’ use_frameworks! pod 'PLCrashReporter' end target 'TargetTests' do platform :ios, ‘8.0’ use_frameworks! pod 'PLCrashReporter' end Go to the **_Build Settings_** of TargetTests and set the value for “ **Other Linker Flags** ” as **$(inherited)** Do a **_POD install_** then do **_Clean Build Folder_** and run
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "ios, xcode, unit testing, cocoapods, plcrashreporter" }
The cohomology $H^*(BU(n); R)$ I am reading this post, Prop. 2.1. It seem that none of the argument is dependent on the we are working with coefficient in $\Bbb Z$. Hence, let $R$ be a unital commutative ring. > (I) Do the results for $H^*(BU, \Bbb Z)$ hold for $H^*(BU;R)$? > > (II) Are the arguments the same?
Yes. Alternatively, you can deduce the computation of $H^*(BU;R)$ from the computation of $H^*(BU;\mathbb{Z})$, since the canonical ring-homomorphism $H^*(BU;\mathbb{Z})\otimes R\to H^*(BU;R)$ is an isomorphism (this is true more generally for any space whose homology with coefficients in $\mathbb{Z}$ is free and finitely generated in each degree, by the universal coefficient theorem).
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "algebraic topology, homotopy theory, characteristic classes, classifying spaces" }
why js cannot be executed directly by browser I know my question is naive and may be funny for some. I know how to execute js in browser using html files. But if I have a file: example.js const posts = [{"title":"post1"}, {"title":"post2"}] function getPosts() { setTimeout(()=>{ posts.forEach((post)=> { let output = post; } ) document.body.innerHTML(output); },3000) } getPosts(); If I open file in browser (as we do with html files) why i see code instead of output? I am trying to clear few concepts here. Because as per my knowledge browser has engines to compile js then why it did not compile js?
When you visit a URL that returns JavaScript, a browser will render its source code as text. It doesn't execute it because none of the browser authors have considered _execute the JavaScript_ to be a more useful result. When JavaScript was first introduced, it was designed to use an existing DOM as its main I/O system. Browsers still expect JS loaded from the WWW to work that way.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "javascript, browser" }
Initializing a string array I try to initialize a string array with std::cin but I can not this is my code : string *words[6]; for (int i=0 ; i<6;i++){ cin >> words[i]; //error } can anybody help me!!
You don't need to create them dynamically: string words[6]; //notice I deleted '*' here for (int i=0 ; i<6;i++){ cin >>words[i]; } What you've created is array of pointers, in which every pointer must be initalized with `new` before you can use it and deleted afterwards.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -1, "tags": "c++" }
String operation in ruby for credit card number Working on a rails project where there's an order confirmation string with a credit card number with all but the last four digits starred out. What's the proper way to do a string substitution? What's the operation to get this credit_card_number = "1111111111111111" to this? credit_card_number = "************1111" Thanks, Kenji
If you're using ActiveMerchant, `ActiveMerchant::Billing::CreditCard` has an instance method called `display_number` which does this e.g. XXXX-XXXX-XXXX-4338 If you're not, copy activemerchant: def last_digits(number) number.to_s.length <= 4 ? number : number.to_s.slice(-4..-1) end def mask(number) "XXXX-XXXX-XXXX-#{last_digits(number)}" end credit_card_number = "1111111111111111" display_number = mask credit_card_number
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 5, "tags": "ruby on rails, ruby, string, credit card, activemerchant" }
How to make `docker-compose up $container_name` to attache not only to $container_name but to all containers it depends on? When I start a specific container with docker-compose up $container_name docker-compose starts this particular container, but attaches the log output for the $container_name only. How I can force it to output all the output for all the containers that $container_name depends on and which are started by the above command? I'd like to see the output of all containers that are started like by docker-compose up but with only the said and dependent containers being run.
You can use `--attach-dependencies` option: docker-compose up --attach-dependencies foo
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "docker, docker compose" }
volatile boolean called = false; Is this --> if ( !called && (called = true) ) { ... do once ... } an atomic operation? Say you have: volatile boolean called = false; Is this if ( !called && (called = true) ) { ... do once ... } an atomic operation? I know about **AtomicBoolean**. The question is not about that so try to resist your urges.
In a naive implementation this could boil down to: LOAD A ; called NEG ; negate BRF 1$ ; branch if false LOAD 1 ; true STOR A ; store into called 1$: ; do once Not exactly atomic, is it? The Java compiler probably changes the NEG/BRF sequence to BRT (branch if true), but that's about as much help as you can rationally expect. Strange question.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -4, "tags": "java, concurrency, synchronization, atomic" }
I need assistance converting Scaled data from StandardScaler in Python I have data that need to be scaled in Python. However, when I scale the data with StandardScaler(), the data get reshaped to an array and i also lose the data header. How do I convert the data back to a pd.DataFrame so I can have the headers back in place as they were before the scaling? scaler = StandardScaler() train_t = pd.DataFrame(np.arange(scaler.fit_transform(train)).reshape(1458,218), index=list(train.columns)) print(train_t)
Try this: scaler = StandardScaler() train_t = pd.DataFrame(scaler.fit_transform(train), columns = train.columns)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, pandas" }
Is "give me a five" the same as "give me five" or incorrect? I mean the physical gesture of slapping hands together. Any difference between them? Thanks.
_Give me five_ means slapping palms above each other's heads as a a greeting, celebration gesture, or sign of joy. Sometimes one can also say **Give me a five**, _Give me (some) skin!_ , _Skin me!_ , _Slip me five!_ , _Slip me some skin!_ , and _High five!_ with the same meaning. > **Give me five!**: _Sl._ Slap my hand! (as a greeting or to show joy)
stackexchange-english
{ "answer_score": 0, "question_score": 0, "tags": "differences" }
How to interpret Faraday's Law? Faraday's law is given by: $\nabla \times E = -\frac{\partial{B}}{\partial{t}}$ On the right hand side of the equation, we have a quantity representing how $B$ changes over time. On the left hand side of the equation we have a quantity representing the spatial variation of $E$ (the curl of $E$). The most common interpretation is that, we can determine the spatial variation of the induced electric field, if we know how $B$ changes over time. That is, the right hand side is producing the results obtained from left hand side of the equation. Suppose instead however, I set up an electric field such that $\nabla \times E$ is non 0, will this induce a time-varying magnetic field given by the above equation?
I think your last question stated in the following way might clear up your confusion. If I setup an electric field $\mathbf E(t, \mathbf x)$ such that $\nabla\times\mathbf E(t_0,\mathbf x_0)\neq 0$ at some spacetime point $(t_0, \mathbf x_0)$, then Faraday's law tells me that whatever $\mathbf B$-field there is around, it must necessarily satisfy $$ \frac{\partial\mathbf B}{\partial t}(t_0, \mathbf x_0)\neq 0 $$ This does not mean that $\mathbf B(t_0, \mathbf x_0)\neq 0$, the magnetic field could vanish for the instant $t_0$, but since its time derivative must me nonzero, it means that in the next instant the magnetic field must, in fact, be nonzero. So you can be guaranteed that if you have managed to setup an electric field with non-vanishing curl at some instant, then quite soon there will have to be a nonzero magnetic field around.
stackexchange-physics
{ "answer_score": 2, "question_score": 1, "tags": "electromagnetism" }
python - read .txt file line by line I am trying to read every line of my file which contains a list of usernames and than make a login system with it. I am trying to implement a basic login system which has usernames stored in a .txt file but my code doesn't work and I don't know why. I think that the problem is in my loop which checks for username. Here is my code but it doesn't work it just prints fail all the time: a = input('do you have an account y/n:') if a == 'y': b = input('insert username:') file1 = open('file.txt', 'r') lines = file1.readlines() for line in lines: if not lines: pass if line == b: print('pass') else: print('fail') else: d = input('new username:') f = open("file.txt", "a") print(d, file=f) f.close() Any ideas?
for line in lines: if not lines: pass if line == b: print('pass') If the file has any contents, `if not lines` will never be true. And since `if line == b` is indented underneath that, it never gets executed. Also, when you iterate over the lines in a file like that, `line` will have a newline character at the end, so `if line == b` would not be true anyway. You'll have to strip off the newline character. Try this instead: for line in lines: if line.strip() == b: print('pass')
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python, authentication, text files" }
How can pickled byte data be unpickled? How can pickled data be written and read back from a BytesIO object? I tried: import io import cPickle as pickle s1 = "foo" bytes_io = io.BytesIO() pickle.dump(s1, bytes_io, pickle.HIGHEST_PROTOCOL) s2 = pickle.load(bytes_io) which gives for the pickle.load line: Traceback (most recent call last): File "<stdin>", line 1, in <module> EOFError
You just did not rewind your buffer: `bytes_io.seek(0)` before `pickle.load`. Possibly you don't want to rewind to the front of the buffer, but just to the start of your pickled data. Then read out the stream position with `bytes_io.tell()` before pickling and seek to that position instead of `0`.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 7, "tags": "python, pickle" }
interpreting R native boxplot function I'm very new to R. I'm trying on the native boxplot function, using ~ shall combine different variables on the X axis. My book gives two examples boxplot(len ~ supp, data = ToothGrowth) and boxplot(len ~ supp + dose, data = ToothGrowth) I do understand the first one, but what does `+` in `boxplot(len ~ supp + dose, data = ToothGrowth)` do? The output is confusing for me (shown below). !enter image description here
In the second instance `len ~ sup + dose` is the equivalent of doing: TG_split <- with( ToothGrowth, split(len, list(supp, dose) ) ) boxplot(TG_split) i.e. it splits the `len` vector by the two factors `supp` and `dose`, and gives you the values of `len` for every combination of the two factors. TG_split $OJ.0.5 [1] 15.2 21.5 17.6 9.7 14.5 10.0 8.2 9.4 16.5 9.7 $VC.0.5 [1] 4.2 11.5 7.3 5.8 6.4 10.0 11.2 11.2 5.2 7.0 $OJ.1 [1] 19.7 23.3 23.6 26.4 20.0 25.2 25.8 21.2 14.5 27.3 $VC.1 [1] 16.5 16.5 15.2 17.3 22.5 17.3 13.6 14.5 18.8 15.5 $OJ.2 [1] 25.5 26.4 22.4 24.5 24.8 30.9 26.4 27.3 29.4 23.0 $VC.2 [1] 23.6 18.5 33.9 25.5 26.4 32.5 26.7 21.5 23.3 29.5
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r" }
What is better style: ++x or x++ in for loops I was having a discussion with a stubborn person I know over which of these two forms was more semantically correct, although there is no logical difference to the code: 1. for(int x = 0; x < 10; x++) // do something 2. for(int x = 0; x < 10; ++x) // do something Is it better to pre-increment or post-increment in a for loop?
If you don't need the side effect of post increment, then the pre increment version is the better choice. In case of an `int` it does not result in different code, but in case of an iterator you probably get better performance with pre increment because post increment needs to create a temporary copy of the original iterator. You can easily see that when comparing pre increment class T { T& operator++() { this-> .... // do the increment return *this; } } with the post increment class T { T operator++(int) { const T old{ *this }; this-> .... // do the increment return old; } } If the iterator is just a pointer then the compiler might be able to optimize so much that you don't see a difference, but if the iterator is more complex, then you will see a difference. Of course the same applies to prefix and postfix decrement.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -3, "tags": "c++" }
Swift: How I can partially apply generic function? i have some generic function, and i need to get a link to the generic function with a specific generic type. // my generic function func messageResult<M: SwiftProtobuf.Message>(_ dto: M?) { result(try? dto?.serializedData()) } // then i try get link to the function with a specific generic type // but i throw error let dtoResult = messageResult<Dto.OpenResult> error message: `'>' is not a postfix unary operator` ide highlighted: `let dtoResult = messageResult<Dto.OpenResult>` how i can write it correctlly?
You can specify the generic argument by type annotating `dtoResult` let dtoResult: (Dto.OpenResult) -> () = messageResult
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "swift, generics" }
Do not wish for something more than you work for Is the following sentence grammatically correct? * "Do not wish for something more than you work for." I'm pretty sure that the following separate sentences are correct, but it somehow sounds somewhat weird when put together: * Do not wish for something. * Owning a house is something to work for. I think that I'm confused because you can stress "Do not wish for something more" while you should stress "Do not wish for something" and "more than you work for".
You're missing a word: "Do not wish for something more than you work for it." The issue here is that "wish for something" and "work for (it)" are essentially independent clauses, and the "for" after "work" has to refer to something in the same clause. (Some people will tell you you can't finish a sentence with a preposition, but this is not true. However, the preposition does have to point to a noun or phrase _somewhere_.)
stackexchange-ell
{ "answer_score": -1, "question_score": 2, "tags": "grammar, sentence construction, grammaticality, ellipsis" }
Question about a double summation Suppose you have two arbitrary sequences of real numbers, say $\\{ \gamma_n \\}$ and $\\{ c_{n,m} \\}$. Suppose also that $c_{n,m}$ is not identically 0 for all pairs $(m,n)$, and also that for fixed $n$, $\sum_{m=0}^n c_{n,m} \neq 0$. If $$\sum_{m=0}^\infty \sum_{n=0}^\infty \gamma_n c_{n,m} = 0$$ Does it necessarily follow that $\gamma_n = 0$ for all $n$? My intuition tells me yes but I do not know how to prove it, and it is also entirely possible that it is not actually true. Any help appreciated. Thanks.
The answer is negative. Consider the case where $$ c_{n,m}=1 \qquad (n,m\geq0), $$ $$ \gamma_0=-1,\qquad \gamma_n=2^{-n} \qquad (n\geq 1). $$ Then, for fixed $m$, we have $$\sum_{n=0}^\infty\gamma_nc_{n,m}=-1+\sum_{n=1}^\infty2^{-n}=0. $$ Then summing over $m$ is just a sum of infinitely many zeros, yielding zero.
stackexchange-math
{ "answer_score": 5, "question_score": 3, "tags": "sequences and series" }
How do you make notations visible outside of a module signature in Coq? I've defined a module signature in Coq that defines several notations. When I try to use these notations outside of the signature however, Coq fails. A simplified version of my code is given below. Any help would be appreciated. Module Type Field_Axioms. Delimit Scope Field_scope with F. Open Scope Field_scope. Parameter Element : Set. Parameter addition : Element -> Element -> Element. Infix " + " := addition : Field_scope. (* ASSIGNS THE "+" OPERATOR TO SCOPE. *) End Field_Axioms Module Type Ordered_Field_Axioms. Declare Module Field : Field_Axioms. Print Scope Field_scope. (* SHOWS THAT THE SCOPE IS EMPTY. *) End Ordered_Field_Axioms.
You can replace: Declare Module Field : Field_Axioms. with: Declare Module Import Field : Field_Axioms.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "coq, theorem proving" }
Limit of product of matrices with spectral radius less than 1 If spectral radius of a square matrix $A$ is less than 1, then we know that $$\lim_{k \to \infty} A^k = 0.$$ Now, I want to know whether we can also conclude the following results? $$\lim_{k \to \infty} A^k (A^{T})^k = 0$$ where $A^{T}$ is the transpose of matrix $A$.
Hint: $A^T$ has the same eigenvalues as $A$. Then use algebraic limit rules.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "linear algebra, matrices, limits, spectral radius" }
How do you stop a dynamically loaded form from submitting with jquery? I'm working on an AJAX login system. Right now, when the user clicks on a link, the login form is dynamically loaded when the person clicks on a "log in" link. Since I'm using AJAX for this, I want to prevent the form from actually submitting when the submit button is clicked. I tried the following code as part of my load function, and the form loads correctely, but the form still submits normally. $('#loginBox').load('loginform.php'); $('#loginBox form').submit(function(event) { event.preventDefault(); }); How can I fix this?
**jQuery.load is an asynchronous function.** This means that the form may not be available (yet) when you try to match "#loginBox form". To make sure your code is executed after the form is loaded, you must pass your code as a callback function to load. $('#loginBox').load("form.html", function() { $('#loginBox form').submit(function(event) { event.preventDefault(); }); }); Btw - In your case it does not matter wether you use **event.preventDefault()** or **return false**. They will both prevent your form from being submitted. (See event.preventDefault() vs. return false)
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "javascript, jquery" }
Using the alternatives for copyrighted zero derivation words (e.g. "LEGO", "Xerox" We have seen how copyright infringement goes into zero derivation English words such as `a Xerox clone` or `He was Googling it` or even `A lego like construction`. (e.g. < To avoid copyright lawsuit, **is there a list of words alternative word/phrase that one can use for such zero derivation words that comes with arcane copyright laws?** What would be a good alternative for phrases such as: * Lego like construction * a Xerox clone * He googled long and hard to find her
1. Copyright isn't relevant to this. If any law is involved it will be _trademark_ law. But some genericised trademarks are no longer enforceable. 2. Specific answers for your examples are: 1. snapable bricks (perhaps. I'm not certain if there is a common generic name for Lego-like toys) 2. photocopier. In Australia we never say anything other than photocopier. 3. searched the internet for ... 3. Here is a list, though it is incomplete of course: < 4. Why are you asking about zero derivations? Only Googled is derived - Lego and Xerox aren't, at least not in the examples you gave.
stackexchange-linguistics
{ "answer_score": 3, "question_score": 0, "tags": "terminology, names, synonymy" }
Prove Inequality (with norm and an inner product) > Prove that for all $f,g\in C[a,b]$ with the inner product $\langle f,g\rangle=\int_{a}^{b}f(x)\overline{g(x)}dx$: > > $$\frac{1}{2}\int_{a}^{b}\int_{a}^{b}|f(x)g(y)-g(x)f(y)|^2dxdy\leq ||f||^2||g||^2-|\langle f,g\rangle^2|$$ I have started with $$\frac{1}{2}\int_{a}^{b}\int_{a}^{b}|f(x)g(y)-g(x)f(y)|^2dxdy=\langle f(x)g(y)-g(x)f(y),f(x)g(y)-g(x)f(y)\rangle\leq$$ By cauchy-schwarz $$\leq ||f(x)g(y)-g(x)f(y)||\cdot||f(x)g(y)-g(x)f(y)||$$ Can we continue with $$||f(x)g(y)-g(x)f(y)||\cdot||f(x)g(y)-g(x)f(y)||\leq [||f(x)g(y)||+||g(x)f(y)||]\cdot[||f(x)g(y)||+||g(x)f(y)||]?$$ Second thought: to try to prove $$\frac{1}{2}\int_{a}^{b}\int_{a}^{b}|f(x)g(y)-g(x)f(y)|^2dxdy+|\langle f,g\rangle^2|\leq ||f||^2||g||^2$$
It should be an equality: \begin{align} &\frac{1}{2} \int \int \lvert f(x)g(y)-g(x)f(y) \rvert^2 \, dx \, dy \\\ &= \frac{1}{2} \int \int \left( \lvert f(x) \rvert^2 \lvert g(y) \rvert^2 + \lvert g(x) \rvert^2 \lvert f(y) \rvert^2 - 2\Re(\overline{f(x)g(y)}g(x)f(y)) \right) dx \, dy \\\ &= \lVert f \rVert^2 \lVert g \rVert^2 - \Re\left( \int \int \overline{f(x)g(y)}g(x)f(y) \, dx \, dy \right) \\\ &= \lVert f \rVert^2 \lVert g \rVert^2 - \Re\left(\left( \int \overline{f(x)}g(x) \, dx \right) \left( \int \overline{g(y)}f(y)\, dy \right)\right) \\\ &= \lVert f \rVert^2 \lVert g \rVert^2 - \lvert\langle f,g\rangle \rvert^2 \end{align} (by expanding, linearity of the integral to bring out the real part, separating the $x$ and $y$ terms and using the definition of the inner-product).
stackexchange-math
{ "answer_score": 2, "question_score": 3, "tags": "linear algebra, inequality, normed spaces" }
Is possible to grab a pdf files from direct link to a folder in server? I just want to know if there is a method to grab a pdf file from a direct link like this : To a folder in the server for example : host.com/files/ if there is a method for ASP MVC it will be great and thanks . **Note** : I will use the method in my asp mvc application .
Try WebClient using (var webClient = new WebClient()) { webClient.DownloadFile(" Server.MapPath("~/files/mvc.pdf")); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, asp.net mvc, asp.net mvc 4, pdf" }
How to Invert (Negative) Android Vector Image (Path) Need area bound by Vector to be transparent and background (Remaining area) to be filled. Required to make it easy to dynamically fill color of vector (Toggle Button Drawable) when the same is bound by a Selector I Have Vector Path for Below generated from Studio: (Amber space is Transparent) ![enter image description here]( I want This: (Amber space is Transparent) ![enter image description here](
Thanks to @pskink - Per his suggestion I used myImageView.setColorFilter(Color.WHITE, PorterDuff.Mode.XOR); myStateListDrawable.addState(new int[] { android.R.attr.state_checked }, myImageView); To achieve my needs. Scroll down the below link - there are easy to understand examples with other options for ColorFilter <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "android, image, vector, togglebutton" }
How to show the image with menu item in Action bar in android I am developing the android application. have one doubt regarding show the image with menu item in Action bar in android How to show the image with menu item in Action bar in android Thanks in advance
<item android:id="@+id/menu_settings" android:icon="@android:drawable/ic_menu_preferences" android:orderInCategory="100" android:showAsAction="always|withText" android:title="@string/menu_settings"/>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, android" }
How to create a double underscore with no space in between? I want to add a link to my link of citations, and in the link there are several places where there are two consecutive underscores. Using the usual _ for an underscore, I did this: \_\_ Specifically for my link, I have this right now: but then I get a space in between the two underscore symbols. !What is happening Any ideas?
If you want to create line two times longer than `\_`, the solution may be as the following: \documentclass{article} \begin{document} \newlength\dunder \settowidth{\dunder}{\_} A\_B A\rule{2\dunder}{0.4pt}B Or as a definition \newcommand{\twound}{\rule{2\dunder}{0.4pt}} % As named as you want A\twound{B} \end{document} !enter image description here
stackexchange-tex
{ "answer_score": 1, "question_score": 3, "tags": "spacing, urls" }
Function interpolation I have a function that evolves over time. I know the function in the initial and terminal states. $f(t,x_1,x_2,...,x_n) = a_1x_1 + a_2x_2 + ... +a_nx_n$ $f(T,x_1,x_2,...,x_n) = b_1x_2 + b_2x_2 + ... + b_nx_n$ I want to approximate the function at some $\tau$, $t < \tau < T$. There is probably some way to interpolate the function just like drawing straight line between two points in space? The first thing that came into my mind is to do the following $f(\tau,x_1,x_2,...x_n) = \sum c_ix_i$ where $c_i = \frac{\tau}{T-t}a_i + (1-\frac{\tau}{T-t})b_i$ Is it the best I can do?
Your coefficient $c_i$ should be egal to $a_i$ when $\tau=t$ and should be equal to $b_i$ when $\tau=T$. Then, they should be $$c_i=\left(\frac{T-\tau}{T-t}\right)a_i+\left(\frac{\tau-t}{T-t}\right)b_i$$ If $\tau=t$ then $$c_i= \left(\frac{T-t}{T-t}\right)a_i+\left(\frac{t-t}{T-t}\right)b_i=1a_i+0b_i$$ If $\tau=T$ then $$c_i= \left(\frac{T-T}{T-t}\right)a_i+\left(\frac{T-t}{T-t}\right)b_i=0a_i+1b_i$$
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "approximation, interpolation" }
How to use Mongoose to query keyword in 2 fields Lets say I have a Mongoose model like this: var AdSchema = new mongoose.Schema({ vehicleDescription: String, adDescription: String, ... }); I want to search both fields for the same key word, for example find all WHERE vehicleDescription contains the word TEST, OR adDescription contains the word TEST. It needs to be case sensitive also. Currently I can query one field like this: var query = {}; query['adDescription'] = ({ $regex: search.keyWord, $options: 'i' }); But I need to search both fields at the same time. Thanks.
You can search for more than one fields at the same time by specifying the field and value in a `{field 1: value 1}, {field 2: value 2},...,{field n: value n}`format in the `find()`function. Additionally, you can also specify various conditions that the results must satisfy, such as AND, OR etc. In your case, a sample code in Node.js would look like this var result = db.collection('AdSchema').find({ $or: [ {vehicleDescription : { $regex: search.keyWord, $options: 'i' }}, { adDescription: { $regex: search.keyWord, $options: 'i' } } ] }); For more detail, refer the documentation page for MongoDB.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, mongodb, mongoose, mongoose schema" }
There is no register form but spams are sending register request in Drupal 7! There is no register or login form in `front-page` or any other pages in my website but every day I receive emails of my website that some people asked for registration, How does such a thing is possible and how do they do this?
By default there's a registration form at /user/register; bots will find it trivial to discover and submit that form. If you really don't want that path to be accessible you can just use a menu alter to deny access: function MYMODULE_menu_alter(&$items) { $items['user/register']['access callback'] = FALSE; }
stackexchange-drupal
{ "answer_score": 3, "question_score": 1, "tags": "advertising, users" }
Git Clone Repo from virtualbox Ubuntu 14.04 server http protocol I made a git repo on my virtual machine in /var/www/test Is there any simple way for me to clone this repo from my host machine via http protocol ? Trying with gittortoise/gitbash passing my http protocol but it seems that it doesnt find any repo on it, thou there it is for 100% Well I'm able to access it via web browser Configuration(Not enough reputation to post images here :/ ): <
You have to call `git update-server-info` on the repo in the virtual machine. Afterwards activate the **post-update** hook: On the virtual machine go to the `.git/hooks` directory. There should be some files with the ending `.sample`. Look for the `post-update.sample` file. To activate this hook just rename it to `post-update`. If this file is not there, simply create it with the following content: #!/bin/sh exec git update-server-info Make sure that the file is executable (`chmod 755 post-update`).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "git, ubuntu, ubuntu 14.04, tortoisegit, ubuntu server" }
Java - Swing Display Image Not Working I am new to Swing and am trying to display a simple image that I have dragged into my project using the code below. Everything compiles and runs, however, the image does not show up. Just by the way I would really prefer doing it this way opposed to getting the image from its file path. Code: public static void main(String[] args) throws IOException { // TODO Auto-generated method stub ImageProcessorApp IPA = new ImageProcessorApp(); IPA.displayImage(); } void displayImage() throws IOException { JFrame frame = new JFrame("frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 500); frame.setVisible(true); BufferedImage wPic = ImageIO.read(this.getClass().getResource("url-2.jpg")); JLabel wIcon = new JLabel(new ImageIcon(wPic)); frame.add(wIcon); System.out.println("added image"); }
Firstly you must call method .setVisible(); only after added all components in the Frame. Secondary - you must fix your path for Image, just add image in your project beside the Main class. This is worked solution : import javax.swing.*; import java.io.IOException; /** * Created by Алексей on 24.11.2016. */ public class Main { public static void main(String[] args) throws IOException { displayImage(); } public static void displayImage() throws IOException { JFrame frame = new JFrame("frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 500); JLabel imgLabel = new JLabel(new ImageIcon("src/url-2.jpg")); frame.add(imgLabel); frame.setVisible(true); } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "java, swing" }
Performance of views on redshift I have a cluster that I use, among other things, for reporting via PowerBi. For this I created views to show only the required fields so the queries run faster. If the source table is sorted by date and the view is 'select fields from table;' will it use the date if I query the view using WHERE on that field? Any recommendations? For better performance! Thank you!
For better performance in Redshift, It is absolutely important to set SortKey, DistributionKey and Encoding properly. I guess you want to generate date wise report. In that case, the "date" column should be the distribution key. Do not encode the "date" column which means keep the value ENCODING as RAW / NONE. Then, you can use the "date" column as a COMPOUND sort key. If you have any other column you want to filter with then use that column as the first key and the "date" column as the second key in the SORT key order. Otherwise, you can define the SORT key only using the "date" column.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "powerbi, amazon redshift" }
autowiring webapplicationcotnext in my spring 3.2 tests Following the instructions here, but i get the error unable to autowire WebApplicationContext. @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("applicationContext-test.xml") @WebAppConfiguration public class AjaxTest { @Autowired private WebApplicationContext webApplicationContext; //FAILS But this compiles : @Autowired ServletContext servletContext; private WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); And I don't understand why. **Edit** It runs fine using maven, it was my editor intellij showing an incorrect auto compile message, a bug in fact.
Your test class should implement `ApplicationContextAware` interface: public class ApplicationContextProvider implements ApplicationContextAware { private static ApplicationContext applicationContext = null; public static ApplicationContext getApplicationContext() { return applicationContext; } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } } Spring will automatically inject the application context.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, spring, testing, web applications" }
<0xEF,0xBB,0xBF> character showing up in files. How to remove them? I am doing compressing of JavaScript files and the compressor is complaining that my files have `` character in them. How can I search for these characters and remove them?
perl -pi~ -CSD -e 's/^\x{fffe}//' file1.js path/to/file2.js I would assume the tool will break if you have other utf-8 in your files, but if not, perhaps this workaround can help you. (Untested ...) **Edit** : added the `-CSD` option, as per tchrist's comment.
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 89, "tags": "file, unicode, utf 8, utf" }
Running sql command from Command Prompt I have a sql command I want to use to connect to my online database mysql -h your_ddbb_server_ip -u your_user I've installed MySQL installer 5.5 and ran the program. After installing I tried running the command from both command prompt and a program called 'MySQL 5.5 Command Line Client'. Neither program responded to the command. How and where do I run this?
From a command prompt (`cmd.exe`) be sure you have the mysql bin folder in the path (the installer prompts for that) so you can just type `mysql.exe` (or just `mysql`). Otherwise you have to navigate to the MySql bin folder (in my case that's `C:\Program Files\MySQL\MySQL Server 5.5\bin` cd "C:\Program Files\MySQL\MySQL Server 5.5\bin" mysql -h your_ddbb_server_ip -u your_user This command will launch an interactive shell. If you just want to execute a command you have to specify the `-e argument` mysql -h your_ddbb_server_ip -u your_user-e "SHOW DATABASES"
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, command prompt" }
PDO adds the apostrophe to the mySQL query After years of reading it's time to ask first question :) My problem is that after migrating the code from mySQLi to PDO we have got a problem as it seems PDO adds the apostrophes to the query. PHP code goes like that: $sort = $_GET['sort']; << table column name (mySQL VARCHAR only columns) .... $query = 'SELECT * FROM table WHERE xxx > 0'; $query .= ' ORDER BY :sort ASC ;'; $qry_result= $db->prepare($query); $qry_result->execute(array(':sort'=>$sort)); mysqli version went smoothly but now queries (mysql log file) looks like this: SELECT * FROM table where xxx > 0 ORDER BY 'SORT_VAR_VALUE' ASC; ^ 2 problems ^ So the table is NOT sorted, as sort order (from mySQL point of view) is wrong. phpinfo() does not get any results for search on "magic" nor "quotes" btw. Any idea ??
The placeholders in PDO statements are for values only. If you want to add actual SQL to the query you need to do it another way. First, you should sanitize `$sort` and surround it with backticks in the query. $sort = preg_replace('/^[a-zA-Z0-9_]/', '', $sort); Then you could double quote the query string and PHP will replace `$sort` with it's value for you: $query = "SELECT * FROM table WHERE xxx > 0 ORDER BY `$sort` ASC"; Or you could replace it with `preg_replace` like so: $query = 'SELECT * FROM table WHERE xxx > 0 ORDER BY `:sort` ASC'; $query = preg_replace('/:sort/', $sort, $query, 1); I would use the `preg_replace` method because it allows you to reuse the query if you assign the results from `preg_replace` to another variable instead of overwriting the original variable.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, mysql, pdo, apostrophe" }
2 column comparison using awk script I want to compare 2 columns in a file using awk. The columns I want to compare for an expression look like these: A1 123456 456783 NR A1 789876 432565 NM and so on. I want to separate the 4th and the 8th column from the file which have NR in both the 4th and the 8th columns. I have tried using awk `awk '$4 && $8 ~ /NR_/{print}'` but nothing happens when I run the script. Can someone help. regards.
Its hard to tell from one sample input line but it sounds like what you want is: awk '($4=="NR") && ($8=="NR")'
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "awk" }
Windows switch languages alternative hotkey I know Win+Space hotkey. However Windows 11 shows the keyboard language selection even when pressing something else, but I don't know what or how to disable it. It very frequently shows the selection dialog when playing FPS games or when programming. And I'm sure I'm not pressing Win or Space at that time, so it has to be some other shortcut Thank you
You may check and change or disable language hotkey in Windows 11 as follows: * Open the Settings app (`Win`+`I`) * Click "Time & Language" on the left * On the right click "Typing" * On the right again, scroll down and click "Advanced keyboard settings" * Click below on "Input language hot keys" * In the "Text Services and Input Languages" dialog select "Advanced Key Settings" * Select an entry and click "Change Key Sequence" * Here you may change hotkey or select "Not assigned" * Click OK to terminate.
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "windows 11" }
Why would you ever want to use tape instead of a HDD? > **Possible Duplicate:** > Advantages/Disadvantages of using tape instead of disk As I've never used a tape drive, this is probably a naive question. I was always guessing that tape must probably be cheaper which is why people would want it. But then I read this Slashdot comment which basically says that: * tape drives have crappy latency * tape drives are not as reliable as multiple hard drives * tape drives are extremely expensive for such a small (1.5 TB) storage capacity Furthermore, on that ask Slashdot thread, it is established that the read speed is just OK, nothing great. So why would I ever want a tape drive? It seems to me that it is simply made obsolete by HDs. Or am I wrong?
History! Quite frankly, go back many years and it was simply the thing to do for backups - many of the negatives were simply not a concern for the requirements. Every IT Department I knew would have tape rotations, schedules and just do it without thinking - when storage needs increase, they buy the latest tape technology and keep upgrading whilst trying to minimise change to business processes. As time goes on, disks are becoming cheaper and cheaper and backup to disk is becoming the normal. Give it a few more years and I would expect tapes to be history as always on disk based backup has so many advantages.
stackexchange-superuser
{ "answer_score": 4, "question_score": 2, "tags": "tape" }
Connection refused trying to get account info in Solana solana account <address> When I get account info, I have this error: Error: RPC request error: cluster version query failed: error sending request for url ( error trying to connect: tcp connect error: Connection refused (os error 111)
The error is indicating that the CLI RpcClient can not communicate with the Solana validator. This is usually caused by not having `solana-test-validator` running in another terminal. Many make the mistake of thinking that the localhost is running the validator all the time... it's not. In one terminal do: `solana-test-validator` which will startup up the local validator Open a second terminal and do `solana account` \- This will return account info for the default keypair
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "anchor, solana" }
How to make iphone apps in two different languages? Hey guys I was just wondering how to make apps in two different languages? I think that I should create two files with all the variables in different languages each. Is that right?
What do you mean by "idiom"? Are you talking about internationalization and localization? If so, start here. (Cocoa Touch has a fair amount of support for that built in.)
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 0, "tags": "iphone, cocoa touch, localization" }
Displaying dynamically generated images in Yesod I'm writing my first Yesod app. The application involves the user selecting to view a graph, dynamically generated based on data stored in a DB on the server. I know how to get the user request and create the image on the server's file system, but how do I create a response page presenting it? P.S. As I'm using GnuPlot to generate the image, I only know how to write it as a file to the file system, but If you happen to know how to get the data in memory it'll probably be even better. Thanks,
For a file on disk, you can use `sendFile` in your handler. getImageR = do -- ... save image data to disk somewhere sendFile typeJpeg "/path/to/file.jpg" For sending it from a `ByteString` in memory, use `sendResponse`. getImageR = do bytes <- -- generate image data sendResponse (typePng, toContent bytes) Make sure you specify the correct content type for your image.
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 10, "tags": "haskell, yesod" }
nodejs - npm install dependency if module doesn't exist in parent I have a use case where my project has dependency on Lodash, and then there are other node_modules which further have dependency on Lodash. When I do 'npm install' on my project. Lodash gets installed two times, one for my 'project/node_modules/lodash' and second for my dependency 'project/node_modules/dependency-1/node_modules/lodash'. I am thinking if it is possible to have 'lodash' dependency installed in my project's root only? When that happens, my dependency will try to load parent's node_module/lodash instead of its own. This should save me some Module loading in memory. Sine Module caching is based on FilePath, I don't want to keep two instances of Lodash loaded in memory, one for parent directory and one for dependency itself.
Use `npm dedupe`. It will flatten up your dependencies by moving them up in the tree where possible. See docs: < There is an issue which address this.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "node.js, npm, lodash" }
How to determine if a specific module is loaded in linux kernel I am just curious is there any way to determine if a particular module is loaded/installed. $ lsmod lists all modules (device driver loaded). Is there any way to check or a command that returns true/false boolean output if a module name is polled. For eg. if keyboard.o exists return true else false. I need this tip to complete my driver auto refresh program. PS: tried modinfo. I am using busybox client in my test DUT so can you give some alternatives other than modinfo?
not sure if `modinfo modname` and checking `$?` will work for you, just a suggestion. /tmp$ sudo modinfo e1000 /tmp$ echo $? 0 /tmp$ sudo modinfo keyboard ERROR: modinfo: could not find module keyboard /tmp$ echo $? 1 alternatively you also grep `/proc/modules`
stackexchange-stackoverflow
{ "answer_score": 27, "question_score": 56, "tags": "unix, linux kernel, insmod" }
Losing my session scope in IE and also in Chrome Incognito mode Everything is working fine in Chrome and Firefox, but if I use Incognito mode, then I lose my session scope navigating from one hyperlink to the next. Internet Explorer is also not working. Application.cfc: component { this.name = 'sessionScope' this.SessionManagement = true this.sessionTimeout = CreateTimeSpan(0,0,45,0) } Index.cfm: <html> <body> <cfdump var="#session#"> </body> </html> cfid keeps changing each time I refresh the page. This is a Lucee install, but I've added the ColdFusion tag to reach a wider audience.
_promoted from the comments for better visibility_ Does Lucee have the option of using J2EE sessions like Adobe's version does? It might help to use that instead of the standard cfid/cftoken.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "coldfusion, lucee" }
How can I get a string that shows the integer number of seconds since 1970? Here's what I tried so far: var value = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds.ToString() It gives me the answer below but I would like to get a whole number: "1500092088.9501"
Below are a few examples of various ways you can deal with this sort of scenario double secondsSince1970 = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; // int logic. ints are whole numbers so casting to an int will drop all decimals with no rounding. Console.WriteLine(((long)secondsSince1970).ToString()); // Math logic. .Net gives us some handy Maths to work with rounding decimals // Round up Console.WriteLine(Math.Ceiling(secondsSince1970).ToString()); // Round down Console.WriteLine(Math.Floor(secondsSince1970).ToString()); // Round nearest Console.WriteLine(Math.Round(secondsSince1970).ToString()); EDIT: Changed the int logic to cast to a `long` instead of an `int` because the `int.MaxValue` will be reached near the start of the year 2038
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#" }
Localization - the equivalence ratio and subrings. Let $R$ be a commutative ring with $1\in R$, and let $S\subseteq R$ a multiplicatively closed set. Let $A\subset R$ be a subring (with $1\in A$), and observe $S^{-1}A\subseteq S^{-1}R$. Is it possible that there exists $t\in R, s\in S$, such that $\frac{t}{s}\in A^{-1}S$ and $t \in R\setminus A$? We need to prove that there exist $s_1,s^*\in S, a\in A $ such that $\frac{t}{s}=\frac{a}{s^*}$, that is $s_1(s^*t-sa)=0$, but I have no idea how to start (if it is indeed true). If $S^{-1}A\triangleleft S^{-1}R$ is an ideal ($1\notin A$, we could reduce this question to $\frac{t}{1}\in A^{-1}S$ by multiplication with $\frac{s}{1}$ and $t\in R\setminus A$. Back to the question, is it possible that $\frac{t}{s}\in A^{-1}S$ with the above conditions? Thanks in advance.
Consider $R=\Bbb Z[i]$, $S:=\\{(1+i)^n: n\in\Bbb N\\}$ and $A:=\Bbb Z$. Then in $S^{-1}A$ we have $$\frac 2{1+i}=1-i=\frac{1-i}1$$ where the numerator is $\in R\setminus A$.
stackexchange-math
{ "answer_score": 1, "question_score": 4, "tags": "commutative algebra, localization" }
Generalized minimal residuals: eigenvalues and sets of functions Can someone help me on this exercise (2 parts)? Thanks! > Suppose that $S \subseteq \mathbb{C}$ is a set whose convex hull contains $0$ in it's interior (so $S$ is contained in no half-plane disjoint from the origin). How can you show that there is no $p$ $\in P_1$ (where $P_1$ is the set of polynomials of degree $1$ with $p(0)=1$) such that $||p||_S<1$? My idea would be to start from the opposition and to search for a contradiction. Suppose there is a $p \in P_1$ for which $||p||_S < 1$ ($p(0)=1$) and thus $||p||_S = \sup_{z \in S}|p(z)| < 1$. But because of the setting ($p(0)=1$), the supremum should be at least $1$. Contradiction. > Now, let $A$ be a matrix whose spetrum $\Lambda(A)$ (which is the multiset of its eigenvalues) has the above properties. Show that there is no $p \in P_1$ such that $||p(A)||<1$. I really have no idea on how to solve this part... Any help would be welcome!
You are right in the first part. Compactness of $S$, continuity of $p$, and $p(0)=1$ imply that the $\sup$ of $p$ over $S$ cannot be smaller than $1$. For the second question, consider using the _field of values_ , which is the set $$ F(A) = \\{x^*Ax: x\in\mathbb{C}^n, x^*x=1\\} $$ and the _numerical radius_ $$ \nu(A)=\max_{z\in F(A)}|z|=\max_{\|x\|_2=1}|x^*Ax|. $$ You can write $\max$ here because $F$ is compact (and $|\cdot|$ is continuous). It is also convex. Moreover, it is true that the convex hull of $\Lambda(A)$ is contained in $F(A)$. Note that $\nu(A)$ is a lower bound of $\|A\|_2$ ($\nu(A)\leq\|A\|_2$). Let $p\in P_1$, that is, $p(z)=1+\alpha z$ for some $\alpha\in\mathbb{C}$. Since $0\in\mathrm{conv}(\Lambda(A))$ and $\mathrm{conv}(\Lambda(A))\subset F(A)$, there is a $y\in\mathbb{C}^n$ such that $y^*y=1$ and $y^*Ay=0$. Since $\|p(A)\|_2\geq\nu(p(A))$, we have $$ \|p(A)\|_2\geq\nu(I+\alpha A) = \max_{\|x\|_2=1}|x^*(I+\alpha A)x| \geq|y^*(I+\alpha A)y|=y^*y=1. $$
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "linear algebra, eigenvalues eigenvectors, normed spaces, numerical linear algebra" }
undo stored procedure if there is an error on execution alter proc insert_toplam 'deneme2' @str nvarchar(100) as begin insert into tblSekiller(sekilURL) select @str insert into tbl_fake select @str end i want prevent procedure from inserting `table_1` if somehow the procedure give an error on line `insert into tbl_fake` is it possible?
You can use TRY-CATCH and do the following: BEGIN TRANSACTION; BEGIN TRY INSERT INTO tblSekiller(sekilURL) SELECT @str INSERT INTO tbl_fake SELECT @str END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION; -- if your insert generated an error, rollback END CATCH; IF @@TRANCOUNT > 0 COMMIT TRANSACTION; -- otherwise, commit the transaction GO
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "sql server" }
Which Microsoft applications can be extended using MEF? Which Microsoft products support extension through MEF? Right now I know that Visual Studio and NuGet can be extended using MEF. Are there any others? If so, which ones?
MEF is a relatively new technology (pre .NET 4.0, but still relatively new), so I wouldn't imagine there are many apps outside Visual Studio that implement this extension model, yet.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": ".net, mef" }
Expresso-store - Comma in quantity field It seems that if a user enters a comma in the quantity field (as in 2,000) the system ignores the figures after the comma and will add just the amount before the comma (ie '2'). Is there a way to prevent this happening? (version 2.4.1)
You should be able to use HTML5 form validators such as <input type="number" name="item_qty">
stackexchange-expressionengine
{ "answer_score": 0, "question_score": 0, "tags": "expresso store" }
Best way to store values in .Net Compact Framework using C#? I have a WinForm application and I have many forms in my application . These forms have some properties which I want to save when the form is closed and when i again load the forms, I want to populate form properties. I know some techniques like XmlSerialization or I can write my own xml files to store values. But I want expert advice to do this in the best way on Compact framework . What you all expert think could be the best way to store and retrieve data ?
How about SqlLite or similiar?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#" }
TypeError: _user2.default is not a constructor JS I am new to JS and ran into an issue. Basically what I am trying to do is create a new .js which only contains variables lets called the file **users.js** var newuser = { firstname:'Tony', lastname: 'franklyn', email: `[email protected]`, password: 'Franklin123', }; var User = { email: `[email protected]`, password: 'Checks', }; module.exports = { newuser }; Now in another file called **sign up** import news from './users.js'; const newUser = new news(); .typeText(Newuser.firstname) I am trying to reference _newuser_ But after I run my code I get a _TypeError: _user2.default is not a constructor_ Can someone explain why this is happening?
You cannot use the `new` operator on an object literal because the object literal is an object and not a class. You need to structure your code as follows: // user.js function User() { return { firstname: 'Tony', lastname: 'franklyn', email: `[email protected]`, password: 'Franklin123' } } let user = new User(); You may also use the `class` keyword if you are using ES6.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript" }
Video codec that can be read on clean installs of either Windows, OS X and Ubuntu I have to make a video that will need to be watched on different operating systems. Is there a "universal" video codec that can be played on Windows, OS X and Linux without requiring additional plugins or player other than those that comes on a default clean install of each of those systems? Compression is not an issue, I'm merely looking for compatibility (e.g. for audio, I would use WAV as a universal codec). Note : I must assume that the video will be distributed in countries where software patents are enforced, and therefore can't rely on the user to install non-free codecs on Linux. Thanks.
You should look into the mjpeg family of codecs. They're fairly simple, and it worked when I had to share movies between all three OS'es a few months back. mencoder in linux supports this, and it did play out of the box on the few Mac and Windows systems I tested in.
stackexchange-superuser
{ "answer_score": 2, "question_score": 1, "tags": "video, codec" }
Trilinos: Extracting a submatrix of an Epetra CrsMatrix Given a distributed Epetra CrsMatrix $A$, along with a a list of rows, a list of columns and a processor ID, I would like to extract a sub-matrix $A_{sub}$, all the entries of which should be stored on the specified processor. I think this may be done with Import/Export object with suitably defined maps but I cannot seem to find an example.
After some trial and error I have found a solution. Here is a minimal working example in Python. from PyTrilinos import Epetra, Galeri comm = Epetra.PyComm() my_id = comm.MyPID() if my_id ==0: my_range = [0, 1, 5 , 7] else: my_range = [] subset_map = Epetra.Map(-1, my_range , 0, comm) nx, ny = 4 GaleriList = {"n" : nx * ny, "nx" : nx, "ny" : ny } Map = Galeri.CreateMap("Linear", comm, GaleriList) Matrix = Galeri.CreateCrsMatrix("Recirc2D", Map, GaleriList) importer = Epetra.Import(subset_map, Matrix.Map()) Submatrix = Epetra.CrsMatrix(Epetra.Copy, subset_map,subset_map, 5) Submatrix.Import(Matrix, importer, Epetra.Insert) Submatrix.FillComplete()
stackexchange-scicomp
{ "answer_score": 0, "question_score": 0, "tags": "trilinos" }
Count regular expression matches in jQuery I need to count a group of regular expressions in a dynamically loaded `<div>` that I've loaded using the load() function. I also need to resize this `<div>` to the longest line of characters in it. Is there a way to achieve this? I've tried searching around and can't find anything, not even on SO. I should mention that the expression I am testing for is: Sat Mar 12 12:45:38 PST 2011 Using this regex: if ($('#result').text().match(/[A-Za-z]{3}\s[A-Za-z]{3}\s[0-9]{1,2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[A-Z]{3}\s[0-9]{4}/))
var str="The rain in SPAIN stays mainly in the plain"; var patt1=/ain/gi; //noticed the g. g will enable match of all occurance, and without it it'll only match the first occurance console.log(str.match(patt1).length); //4 matched JavaScript match regex function returns an array so you can basically do a length on that array and get the size of the matched elements. Make sure you are using the `g` in RegEx to search all occurance Based on your RegEx you can do the following: $('#result').text().match(/[A-Za-z]{3}\s[A-Za-z]{3}\s[0-9]{1,2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[A-Z]{3}\s[0-9]{4}/g).length //this should give you the total count of occurance
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "javascript, jquery, html, css" }
Can't assign iterator with no viable overloaded '=' error I have a field defined as const vector<record>* data; where record is defined as const unique_ptr<vector<float>> features; const float label; In my main code, I use vector<record>::iterator iter = data->begin() The compiler isn't happy with my code with the no viable overloaded '=' error at that iterator assignment line. It also produces this warning: /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/iterator:1097:7: note: candidate function (the implicit copy assignment operator) not viable: no known conversion from '__wrap_iter<const_pointer>' to 'const __wrap_iter<class MLx::Example *>' for 1st argument What am I doing wrong?
> _"an iterator should be lightweight and should now own the data, i.e. there should be no attempt to copy or even touch record when I make the assignment."_ It has nothing to do with the iterator would _own_ the data stored in data `data`, but the `const unique_ptr<>`, restricts accessing the template argument types only as `const` instances. This means in turn, you need to use vector<record>::const_iterator iter = data->begin(); // ^^^^^^ in your main code. It's much like writing const vector<record>* data; * * * As @Jonathan Potter mentioned in his comment auto iter = data->begin(); should work as well.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 4, "tags": "c++, stl, unique ptr" }
Write to firebase database from cloud function triggered by PubSub I'm trying to use a daily trigger to alter information in my Firebase database. I have a number of other cloud functions that work properly, but I can't seem to get this function to alter the database. const admin = require('firebase-admin'); exports.daily_job = functions.pubsub.topic('daily-tick').onPublish((event) => { console.log("This job is run every day!"); const databaseRef = admin.database().ref('/accountActions/dailyDeletion'); databaseRef.child('delete').set("Data has been deleted!"); return "End of database clearing"; }); This is the code I've been testing to see if the trigger is working. In my console it's showing that the function starts, the console statement is logged, and execution finishes in 40-90ms. But my database is never changed. The deletion statement never appears. Any help is greatly appreciated!
I found the answer to the problem. I had initialized the app according to Firebase's documentation on push notifications: admin.initializeApp({ credential: admin.credential.cert({ projectId: {projectId}, clientEmail: {email}, privateKey: {private key} }), databaseURL: {databaseURL} }); But for some reason this caused issues. I switched it out with a simple admin.initializeApp(functions.config().firebase); This seems to have fixed the issue, and push notifications are still working.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, firebase, firebase realtime database, google cloud functions" }
Unable to separate PdfPTable footer rows from the table header I followed the example from Chapter 4 in "iText in Action", which uses table.setHeaderRows() and table.setFooterRows(). When I use these same methods, all of the rows appear in the header. I call these methods after adding all of the header and footer cells (which make up the rows), but before adding any other cells to the table. I don't think it would be particularly helpful to include all of my code that does this. But I'd be happy to clarify anything that I might have left out of this question. Thanks.
Problem solved! I forgot that the rows in the header belong to a sub-table within a single cell (row), so I passed the wrong value to setHeaderRows().
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, pdf, header, itext, footer" }
Is $\tan^{-1}$ for $\arctan$ on my calculator wrong? On my calculator $\tan^{-1}$ is used to calculate the $\arctan$, but $\tan^{-1}$ actually is $\cot$. $\cot$ and $\arctan$ are not the same thing though. Am I missing something or is the labeling of my Casio fx-991ES really wrong? To make the question more clear: Is $\arctan = \tan^{-1}$ correct?
Calculators have to save space on the labels, therefore $\tan^{-1}$ is more convenient than $\arctan$. Moreover, the notation $f^{-1}$ conventionally denotes the functional inverse of $f$. It's rare to write $f^{-1}$ meaning $1/f$. On my calculator, for example, $\sin^{-1}$ and $\cos^{-1}$ are used in place of the more correct (in my opinion, since less confusing) $\arcsin$ and $\arccos$.
stackexchange-math
{ "answer_score": 7, "question_score": 3, "tags": "calculator" }
How to login in to Microsoft 2017 SQL Server I installed MSQL 2017 and I am now trying to follow a tutorial on how to use it. I can't seem to get it to connect. I have tried both ".","localhost" and my computer name as my server name. I must have missed a step the Microsoft website and youtube have been no help. I have attached a screen capture of the error messages. Thank you in advance for any help. ![enter image description here](
1. Check if SQL Server is running (Use the SQL Server Configuration Manager util) 2. Are you sure about the server name instance? (Use the SQL Server Configuration Manager util) 3. Check if your fire wall is not blocking the connection
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql server" }
Обрезка строки в java Приветствую. Есть строка - `"добрый день[флажек]дорогие друзъя."` Как можно разделить строку на две, до и после `"[флажек]"`?
Метод `split()` в Java разделяет данную строку вокруг данного регулярного выражения Синтаксис этого метода: `public String[] split(String regex, int limit)` или `public String[] split(String regex)`, где * regex - разграничение регулярного выражения; * limit - порог, результатом которого означает, как много строк, должно быть возвращено. split() возвращает массив строк. * * * String str = "добрый день[флажек]дорогие друзъя"; String[] strArr = str.split("\\[флажек\\]"); System.out.print("часть до разделителя: " + strArr[0] + ", часть после разделителя:" + strArr[1]);
stackexchange-ru_stackoverflow
{ "answer_score": 9, "question_score": -2, "tags": "java, строки" }
Calling variable from another event I want to call a variable from another event, for example public void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { var ccc = lblTicketsA; } public void btnSubmit_Click(object sender, EventArgs e) { try { ccc.text = "test"; } catch (Exception ex) { lblDisplay.Text = ex.Message; } } thank you
Make `ccc` an instance field like this: private SomeType ccc; public void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { this.ccc = lblTicketsA; } public void btnSubmit_Click(object sender, EventArgs e) { try { this.ccc.text = "test" } catch (Exception ex) { lblDisplay.Text = ex.Message; } }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, asp.net" }
Is Nike paying income taxes as news media reports? There have been articles written, Nike paid no Federal Income tax in 2020. However, looking at its Annual Report below, I see income taxes. So how are these news articles saying this? * No Federal Taxes for Dozens of Big, Profitable Companies * Nike and FedEx Among Companies That Paid $0 in 2020 Federal Income Tax I am seeing income taxes. * NIKE, Inc. - News, Events & Reports * 2020 Form 10-K PDF ![Screenshot of NIKE, Inc.'s consolidated statements of income](
Income Tax Expense is not just Federal - it's _any_ income tax, which for Nike includes State and Foreign taxes. If you look at Note 9 of the report you'll see a breakdown in which their federal income tax is actually _negative_ , which may be how they ended up on the NY Times list. In addition, income tax _expense_ does not necessarily equal income tax _paid_. Companies have various ways of deferring income tax so that it's accounted for in one year but actually paid in future years. So even a company with a positive income tax _expense_ may not pay it until future years. Whether the NYT criteria is tax accrued or tax paid I have no idea (and don't care) - it's behind a pay wall.
stackexchange-money
{ "answer_score": 4, "question_score": 0, "tags": "united states, stocks, income tax, financial statements, news" }
Php CLI script ignoring memory_limit, crashing at much lower number than limit for some reason, my one of my php scripts are ignoring the php.ini memory limit or ini_set. When i do a print_r(ini_get_all) it shows the global memory limit set to 100M (and local for that matter), when my script dies at Fatal error: Out of memory (allocated 24714304) (tried to allocate 571 bytes) Any tips on diagnosing this? The server has 8gigs of memory and never had problems running this script before. Any tips on debugging this? Thanks!
The single most common cause of this is that usually the CLI PHP binary is using a different php.ini file than you expect. This can be caused by user permissions, or simply different default php.ini files for installed versions of PHP. However, it sounds like you've profiled it a bit and your memory limit may be correct inside your script. In that case, it's quite possible that there is a hard memory limit on processes that is imposed by your operating system, in which case you'll have to figure out where the imposition comes from. I suggest taking a look at this thread, as that poster went through something very similar to your situation.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 6, "tags": "memory, limit, php, ini set" }
How can I find a website's login form URL variables? I am trying to make a code that will automatically login into a webpage for you, but I am having trouble finding the url variables for the submission. How can I find the url variables to submit the login? i.e. When I submit my username and password on the site, it passes it through to The username `<input>` has `id="userId"`, and the password `<input>` has `id="password"`, and this is all under a `<form>` which has `method="POST"` How can I find all variables that I need to submit?
The URL variables aren't always in the URL. Most Login forms use a method of transferring that data called "POST". In which the URL data cannot be seen by the user. You can try using < or < to view the data sent and received by your web browser. To find the name of the URL parameters (such as ?username=....&pas=...). You can look into the HTML of the page. Look for something like so: <form action="login.php" method="post"> <input type="text" name="username" value="User Types Username Here"> <input type="submit"> </form>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "html, url, authentication" }
See folder size updated in real-time I've searched the whole internet but couldn't find a answer. Is there any way/software to see folder size updated in real-time? I can't just leave the "properties" window open as it doesn't update in real-time.
And the answer is: _yes, there is_. Probably there are many other solutions up there on the Internet, but by installing the _Cygwin_ Software Environment, you will eventually write them yourself. So, just perform the following steps: **1.** Install the _Cygwin_ Software Environment by reading this Software Installation Procedure. **2.** Open a Terminal Window. **3.** Write these few characters at the command prompt: dobre@Laptop ~ $ while true; > do > du -hs . > done 16M . 16M . 16M . 16M . 16M . 16M . You may want to change the current home directory, represented above by the dot character (`.`) with any kind of directory you want to watch. Welcome to the world of the _Bourne-Again_ Shell-Scripting Environment!
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "windows" }
XSL disable-output-escaping XML SPY vs SAXON I need help with my XSLT. I have an XML with encoded HTML tags with a tag: ![input code]( Using XmlSpy (Altova) this DOES work: '<xsl:value-of select="de" disable-output-escaping="yes"/>' which returns html tags within the data tag. But executing this XSL on SAXON does not work. The XSL is executed and returns output, but the output-escaping seems to be ignored. Any ideas?
The key thing to remember is that disable-output-escaping is an instruction to the serializer, and it has no effect unless the XSLT processor is serializing the output. The most common reason for it "not working" is that the transformation output is going to a destination other than the serializer (for example, a DOM tree). So we need to know how you are running the transformation. Also related to this, there have been changes to the spec regarding what happens if you use disable-output-escaping while writing to a temporary tree (that is, to a variable). Processors are allowed to ignore disable-output-escaping entirely, but Saxon doesn't do that, except of course when the output isn't serialized. (That's because "escaping" is a serialization thing, and if you're not serializing, then you're not escaping anything, so there is nothing to disable).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "xslt, saxon, xmlspy" }
What temperature lighting should I use for photographing old paper photos? I know I should be using daylight lighting system to achieve natural looks of photographs, but I don't want to spend a lot of money for profesional lighting equipment, so I was thinking to just put a few lamps outside each side of the light box. Like this: ![enter image description here]( The problem for me is, I can't find powerful and cheap enough daylight bulbs. Maybe I could use warm white light bulbs and then change the white balance in camera settings? The question is. How would that affect the quality of a photograph as oppose to having the right color temperature lighting in the first place? Or do I strictly need the right temperature lighting to achieve best results? What do you think? Your opinion is more than welcome.
The color temperature of your bulbs is not as important as you seem to think. What is important if you require fairly critical color accuracy is that, regardless of the temperature their output is centered on, your bulbs need to output most if not all of the full spectrum of visible light. In general for photographic purposes you want lights with a Color Rendering Index of at least 90. Most incandescent or halogen lights are fairly close to full spectrum. Most typical consumer fluorescent lights are not. CFL bulbs made specifically for photography _can_ have as good a score as incandescent bulbs but you need to do your homework to find those that do because many of them don't.
stackexchange-photo
{ "answer_score": 9, "question_score": 5, "tags": "equipment recommendation, lighting, image quality, white balance, product photography" }
ASP.MVC application constants, what is the best/most elegant approach? Simple question really, I am just looking for community support what works best architecturally. Say, following case: `TempData["MySetting"]`? Where should I store `"MySetting"`? Should it be 1. in separate class so that the access will be `TempData[Config.MySetting];` 2. in web.config so that the access is `TempData[ConfigurationManager.AppSettings["MySetting"];` 3. inline, leave it as string `TempData["MySetting"];`? 4. in the DB in some constants table, so that var mySetting = (string)_db.GetConstant("MySetting"); TempData[mySetting]; I would not deal with option 4, just brought it for completeness of the picture. So what do you suggest **and why**? **Edit** Question is rather general about constants in asp mvc rather than TempData case. Thanks.
Do your settings change? Depending on environment you deploy? If yes, then you definitely want to store them in the Web.config file (you could even make a custom section if it's not as simple as a couple of key/value pairs). If they're the same on all the environments you use (including your own development box, the server and any testing/staging machines you might want to deploy) then I would go for the first option: declare a class with a few constants. As far as storing them in the database goes, it really depends what kind of settings. If you want them to be per-user of your website, then you might end up storing them in your database. Or in case you want to be able to change them (editing the web.config file while the website is running is not the best idea). I'd try staying away from leaving it as it is, inline.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "asp.net mvc, asp.net mvc 3, architecture, constants" }
Estimation of model with non linear dependent variable I am trying to verify whether two variables are linked by a relation of the type: |y|=a _x or y^2=a_ x. What could be the right statistical procedure to verify whether the above relations are correct and to estimate the parameter a? Thanks.
Both of these are still linear models, so OLS still works fine. Nonlinear least squares is only necessary when your dependent variable depends nonlinearly on the model parameters. The same logic applies for why we can estimate the model $$\ln{y}=a+bx$$ using OLS, i.e. because the model is linear in the parameters. An example of a model that would require nonlinear least squares would be $$y=a+cx^b.$$
stackexchange-stats
{ "answer_score": 4, "question_score": 1, "tags": "estimation, non independent, nonlinear, variable" }
Why running the generated Angular index.html without Grunt shows an empty page? I generated an Angular app and when I run `grunt server` it works (it shows the default page) but when I browse the files and double click index.html I get an empty page (except for the grey background). Why is that? Isn't it just JS/CSS/HTML?
Depending on your setup some files usually need conversion- for instance your styles may well be in compass or SASS and need to be converted to regular css. Grunt handles all the various conversions you need (as well as launching the static page server). Check out your console error log in the browser and I'll bet you'll see some "Failed to load resource" errors- for instance the css file may well not be there (when you're trying to run index.html directly). By the way, you can run: `grunt build` This will create a new directory "dist" with everything converted and ready for distribution- sounds like this might be what you're looking for.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "yeoman" }
How do I add a QueueManager to a Cluster as Partial Repository using PCF? I am using WebSphere MQ 8.0. I want add two Queue Managers, say QM1 and QM2, to a cluster programatically using Programmable Command Format (PCF) in Java. I am able to add QM1 to the cluster as a full repository using the following code. PCFMessageAgent agent = new PCFMessageAgent("QM1"); agent.setCheckResponses(false); PCFMessage[] responses; PCFMessage request = new PCFMessage(MQConstants.MQCMD_CHANGE_Q_MGR); request.addParameter(MQConstants.MQCA_REPOSITORY_NAME, "CLUSTER1"); responses = agent.send(request); **How do I Add QM2 as a partial repository to the cluster?** Any suggestions as to how I can improve/achieve this are welcome.
You need to follow the same procedure as for MQSC commands but using PCF. 1. Define the `CLUSRCVR` channel specifying `CONNAME('dns or ip(port)')` and `CLUSTER('CLUSTER1')`. 2. Define the `CLUSSDR` to the primary full repository. The QMgr will not resolve in the cluster until the last step. Also, be sure to define your RCVR channel as `CLUSTER1.QM1` instead of as `TO.QM1` so that you never have a channel shared across clusters.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "java, ibm mq, pcf" }
Check if variable is set in filter Thanks to your suggestions, I enabled wp_debug and discovered flaws with my plugin. I have a filter for sorting posts by votes. I use it when the `sort` URL parameter is on. `add_filter( 'posts_where', 'votes', 10, 2 );` I used to get `Undefined index: sort` so I modified my function to first check if the variable is set. function votes( $where, $query ) { $sort = array_key_exists('sort', $query->query_vars) ? $_GET['sort'] : null; if ( isset($sort) ) { $where .= " AND $sort >= votes"; } return $where; } This works fine but I'm not confident if it's correct. I'm wondering if there's a better method to do this.
The variable you have named `$query` is actually the WP_Query instance having filters applied to it. You can simply call its function `get` to retrieve query vars. For example: function votes( $where, $query ) { $sort = $query->get('sort'); if (!empty($sort) $where .= " AND $sort >= votes"; return $where; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, php, functions, filters" }
zip-file to buffer c++ I have to read a dat-file byte by byte from a zip-file in a char[] buffer. The zip-file contains only one dat-file. I guess unzip chunk by chunk would be good. I am using Visual Studio 2013 with c++. I have found zip-utils (< would this be ok, because its nearly 10 years old? Would Minizip be a good way? I guess zlib alone would not be enough for this use case, right? My question is, whats the best way to do the unzipping? I have no experience with handling zip-files and would like to hear a suggestion by somebody with experience. Thank you, Friedrich
Minizip would work. Please notice that it still requires zlib source code to link with. A zip file is not just chunks of zlib compressed content. It's an archive. There is a directory header, and per element header you must decode too even if the archive only contains a single file. Typically, the header will tell you from which offset in the zip file you'll find your DAT compressed content. Then you'll likely use zlib to decode chunk by chunk starting at the given offset. Please notice also that zip file format does not _always_ imply zlib as a compressor (you can have many different compressor). If you master the code that create the zip file, it's not an issue. But if it comes from _hostile_ user, then you should rely actually check the compressor used and assert it's zlib else you should deny decompressing the file because you'll not be able to do so.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, visual studio 2013, zip" }
Problem with aligning divs I have 3 divs each of 250 width and 125 height. How can I align them next to each other so that they work on most of the browsers?
This solves your problem <div style='float:left; width:250px; height:125px;'>First</div> <div style='float:left; width:250px; height:125px;'>Second</div> <div style='float:left; width:250px; height:125px;'>Third</div> This is optional <div style='display:inline-block'> <div style='float:left; width:250px;'>First</div> <div style='float:left; width:250px;'>Second</div> <div style='float:left; width:250px;'>Third</div> </div> The above makes sure that any content that comes under the main div is below all three of the inner div. Test them out put some content in both the different style and you will see what i mean. Remove the height value from the first to get a better explanation
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "css" }
How is ordering defined for UUIDs? I am stuck in the following problem. I have two UUIDs const boost::uuids::uuid first = Helper::String2UUID("43E3F007-3993-4587-801E-D24C012587E4")); const boost::uuids::uuid second = Helper::String2UUID("652335C1-6479-4D6A-9599-25A671366E05")); In Boost I am getting this to be true. BOOST_REQUIRE(first < second); But when I do query on SQL Server using ordering for that UUID column it turned out that second < first Looks like ordering for UUIDs is different from one application to another. Does it mean that there is no general rule for ordering UUIDs or am I doing something wrong?
There is no official ordering UUIDs since they are just an opaque string of 128 bits with no inherent meaning. Some applications may "helpfully" define them to be ordered, but since there is no official ordering to follow, they may make different decisions on how to do that. It may even vary between instances of the same application, e.g. due to endianness of the machine they're running on.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c++, sql server, boost, sql order by, uuid" }
How does IO monad work in System.Random import System.Random main = do g <- newStdGen a <-take 5 (randoms g :: [Double]) return () So this code doesn't work because apparently what I'm assigning to a has type [Double] instead of IO [Double] but I thought that you can't escape from IO ever? So how come I seemed to have escaped from IO even though g is type IO? I'm still confused on how IO monads work inside do notation.
You can't escape from `IO`, but inside a `do` block you're not actually _escaping_ per se. Loosely: when you write `g <- newStdGen` in a `do` block, you can then use `g` later in the block as if it just had type `StdGen`, instead of `IO StdGen`. At the end of the block, whatever you return will be wrapped back up in `IO`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "haskell, io, monads" }
Steam Summer Sale minigame - gold coins What do the gold steam coins do? I've been seeing them but haven't been able to figure out what it actually does, or if they do anything at all. !gold steam coin
The Giant Coin on the screen indicates that someone has activated the "Metal Detector" ability. You can see this by checking the right hand side ability list immediately after this occurs. Other abilities/items have similar but different effects on the battlefied area. For example, blue pluses indicate the medic ability has been activated, and green sparkles indicate good luck charms are active.
stackexchange-gaming
{ "answer_score": 16, "question_score": 12, "tags": "steam monster game" }
Disable or hide delete button on condition I have a list called _Tenders_. I need to make sure that when Tender status field is set to "open" no one can delete it. Ideally would be if I won't see options in ecb and ribbon. It is not connected to users permissions but with state of list item. Should I use jQuery or is there an easier way?
Could you check this post for some help? - <
stackexchange-sharepoint
{ "answer_score": -1, "question_score": 1, "tags": "ribbon, list item, ecb menu" }
Verify file copy in powershell Is there an easy way to verify all files were copied correctly when calling copy-item? I thought about using the checksum on all files, but I would imagine powershell (v2) would already have something, and I can't find it.
No there isn't and here is why. Copy-Item is a generic cmdlet that works for all namespace providers. So the items being copied could be files, or registry settings, or IIS configuration sections, etc. Verifying a file copy is quite a bit different than verifying a copy of registry settings. UPDATE: As pointed out by @Dave_S the XCOPY command's verification switch isn't the kind of verification you are looking for. If you are copying text files you could use the PowerShell `Compare-Object` commandlet. If you are copying binary files you could use the system `fc.exe` command with **/b** switch.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 6, "tags": "powershell 2.0" }
react native expo how to require an image? I'm learning react native expo I want to require an image from assets/images ![enter image description here]( The image I want to require is **noti.png** I got this error ![enter image description here]( What am i missing?
You are passing the location of the image incorrectly. as you can see in the error: `the module .. could not be found` To fix it, check the location of current file you are calling that image then go back to the exact location and call it. Also If you are using IDE they recommend you the location. ### Update: `require('../assets/images/noti.png'`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "react native, expo" }
Sublime Text 2 not detecting python library if installed in /opt I am attempting to install Sublime Text 2 in /opt/sublime_text. Once all the files are in there, I believe the executable not detecting the python libraries and throwing the following error: !enter image description here * I have python installed on my system already (2.7.3). * I am able to run Sublime Text 2 from my home directory. I've tried copying just the `__future__.pyo` file into the /opt/sublime_text folder but I get the same error message. Is there a solution which doesn't require me to extract all of the python libraries in the application folder?
You should have an lib/python26.zip package within the app folder. Check if this file is possible corrupted.
stackexchange-unix
{ "answer_score": 2, "question_score": 0, "tags": "python, sublime text" }
How can I set up lighting effectively if I have major space constraints? I need to photograph clothes on a mannequin (will be doing the ghost mannequin effect) what kind of lighting arrangement should I use? I am _very_ limited in space- about 6x7 feet. Lighting equipment consists of two strobes, soft-boxes, scrims, diffusion filters, reflectors & various light-stands. I would maybe consider buying another cheap light or maybe would add some constant light -someone suggested I should use two fluorescent tubes from the two sides of mannequin with one strobe to wash out background not sure if it would work & I'd rather not spend an extra dime on additional equipment- I'm hoping to make whatever equipment I have now do the job. Basically- how can I set up my lights to make the clothes look like they are worth buying?
The trick is going to be to bounce the lights off of something to try and increase the available space. Hopefully the walls are white, but if not, if you can get large, reflective white surfaces to put against the wall and then use the reflection to give you as much distance as possible to diffuse the light, then you can probably achieve what you are looking for. It's probably too small a space to do that much direct lighting, but it's really hard to give a best approach without seeing the space and trying some angles.
stackexchange-photo
{ "answer_score": 1, "question_score": 1, "tags": "studio lighting, product photography, limited space" }
Python удаление метаданных у фотографий Мне необходимо удалить метаданные у фотографии, хранящейся на компьютере, как я могу это сделать?
Попробуйте Это: > Вы можете попробовать загрузить изображение с помощью Python Image Lirbary (PIL), а затем снова сохранить его в другом файле. Это должно удалить метаданные. from PIL import Image image_file = open('image_file.jpeg') image = Image.open(image_file) # next 3 lines strip exif data = list(image.getdata()) image_without_exif = Image.new(image.mode, image.size) image_without_exif.putdata(data) image_without_exif.save('image_file_without_exif.jpeg') Надеюсь, чем-то смог помочь :)
stackexchange-ru_stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "python, файлы, метаданные" }
REGEX: Allow any characters including line break I want to limit the number of characters allowed in one of the questions in my ODK Xform. The question is about the user's comment so I need the field to accept any number of characters from 0 to 100 including line breaks. Otherwise it must show the proper alert. <bind nodeset="/widgets/Comment" type="string" constraint="regex(.,'^.{0,100}$')" /> I have the above code, but it does not allow me to have line breaks, I appreciate your help.
Use the `s` option to make `.` match any character, including newlines: <bind nodeset="/widgets/Comment" type="string" constraint="regex(.,'^(?s).{0,100}$')" />
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "regex, odk" }
PyQt5 How to addWidget at the specific position? I have a vertical layout, that contains one element and a spacer. When i add widgets to the layout it places below spacer.I'd like to get it on top of a layout. P.S. to add element, I use this command: frame.vert_layout.addWidget(wid)
A box layout also has a `insertWidget()` method that thakes the insert position: insertWidget(...) method of PyQt5.QtWidgets.QVBoxLayout instance insertWidget(self, int, QWidget, stretch: int = 0, alignment: Union[Qt.Alignment, Qt.AlignmentFlag] = Qt.Alignment()) Use that one instead, i.e: layout.insertWidget(len(layout) - 1, widget_to_add) `len(layout)` can be used to get the number of items in the layout.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "pyqt5" }
Combinations and Permutations in coin tossing I understand the formulae for combinations and permutations and that for the binomial distribution. However, I'm confused about their application to coin tossing. Consider three tosses. Outcomes with two heads are HHT, HTH and THH. So, there are three and that's what you get if you use the formula for combinations. With combinations "the order is not important". How does that apply in this case? In what way are these three outcomes different if the order is not important? What are the 6 permutations?
Imagine that you have three balls numbered $1$, $2$, $3$ representing the flips on which heads may come up. (I'm using your scenario of three flips). You want to look at cases where you get two heads in three flips, so you are going to pick two of the balls. Picking first ball $1$ and then ball $3$ gives the same result (sequence of tosses) as first picking ball $3$ and then ball $1$ (both result in the outcome HTH). Thus you are making an unordered selection of two of the three positions.
stackexchange-math
{ "answer_score": 2, "question_score": 9, "tags": "permutations, combinations, binomial distribution" }
Mysql minimum and maximum values of "rate" for each month I have a table with two fields - a field for "date" entered as day/month/year and a field "rate" > date | rate > > 24/01/05 | 1.9754 > 26/01/05 | 1.3723 > ... > and so on So, I like to find minimum and maximum values of "rate" for each month of year(s). My query selects only one row > SELECT DISTINCT DATE_FORMAT(date, '%d-%m-%y') as Date, MIN(rate) as r, MAX(rate) as mr FROM rates
This will get the rate values for each month and year SELECT YEAR(date) AS thisYear, MONTH(date) AS thisMonth, MIN(rate) AS minRate, MAX(rate) AS maxRate FROM rates GROUP BY thisYear ASC, thisMonth ASC If you need to have the individual date(s) on which the min or max occurs you'll need some additional grouping in there, however the above should suffice for your original question.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "php, mysql" }
Functional C# - using or returning Action's Browsing the net for better fault handling in C#, I've com across the following to implementation strategies. The first one is natural to me, while the other implementation I'm not certain what its advantages are? 1) ` static void Fault(Action protectedBlock, Action faultHandler) { try { protectedBlock(); } catch { faultHandler(); throw; } } ` 2) ` static Action Fault(Action protectedBlock, Action faultHandler) { return () => { try { protectedBlock(); } catch { faultHandler(); throw; } }; } ` Is 2) the preferred strategy when developing higher order functions in C#? And, I am wondering, if one approach is more efficient than the other.
The second case is like a Faultable Action Factory. Where you pass in a delegate of what you want to do, `protectedBlock`, and a delegate of what to do when an `Exception` occurs, `faultHandler`. The actions are returned wrapped in a try/catch structure as an aggregate `Action`. My problem with both these methods is no `Exception` is actually being caught so who ever is going to catch your throw has no information on which to act. The difference in execution between the 2 is when they actually execute. The 1st will be executed when it's called. The 2nd will execute whenever the returned `Action` is called. I don't think the efficiency difference would be significant.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "c#, metaprogramming, higher order functions" }
Wordpress slider plugin with dynamic height Cannot find a plugin for creating slideshow (for posts) in Wordpress. Already tried a couple of dozen. The need to: * responsive, auto width (using max-width, i think) * if img is vertically NOT TO CUT IT! i. e. proportions must be maintained, height varies relative only to the width * it must be free (or freemium) Wordpress Guru, if you know about these plugins, answer please.
Finally I found solution. If you need good slidedhow with dynamic height in posts use «oik-nivo-slider».
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "wordpress, slideshow" }