INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Using Try Catch to convert value In the following example below, I am returning a value from a database and converting the value to a double, if it falls over due to being NULL, then 0 is being set as the default value. using (SqlCommand cmd = new SqlCommand(sql.ToString(), conn)) { try { this.value = Convert.ToDouble(cmd.ExecuteScalar()); } catch (Exception) { this.value = 0; } } By using a Try Catch in this instance, would this be considered bad practice? What would be a better way to handle this scenario?
> By using a Try Catch in this instance, would this be considered bad practice? Absolutely. Aside from anything else, you're returning 0 if _anything_ fails, not just if the return value is null. (Do you _really_ want to continue as if everything's fine if it turns out that the entire table's been deleted?) If you want to detect a null return value, you should do so explicitly: object result = cmd.ExecuteScalar(); return result == null ? 0d : (double) result; This will _still_ throw (and deliberately) if there's a non-null return value which _isn't_ a `double`. You should know what type your query should return, and fail if it turns out you've got the wrong type.
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 1, "tags": "c#, sql" }
How to handle unserialize data **cla** is an array that I save into the database (MySQL) using php $input = serialize($_POST['cla']); //in the database I have: a:3:{s:6:"t9ffj7";s:27:"Paul";s:7:"71ciz86";s:27:"Peter";s:7:"awez69g";s:27:"Marie";} To get the array from the database, I unserialize it and apply the var_dump() to it. <?php $output = var_dump(unserialize($row['li_file'])); echo $output; ?> then, I get this as output: array (size=3) 't9ffj7' => string 'Paul' (length=4) '71ciz86' => string 'Peter' (length=5) 'awez69g' => string 'Marie' (length=5) I would like to used each key to get the corresponding value. so that, e.g. $first_element = array['t9ffj7']; echo $first_element; //I expect **Paul** Could someone help me ?
<?php $output = unserialize($row['li_file']); foreach($output as $key=>$val){ //echo $val; or echo $output[$key]; } ?>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Formula for the sequence formed by the digits of the natural numbers > Consider the following sequence: $$1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8, 1, 9, 2, 0, 2, 1, 2, 2, 2, 3, \ldots$$ which is formed by extracting the digits of the natural numbers. Is there any formula for the general term of this sequence? All I can think of is an algorithm to obtain its terms: "Set $n = 1$. While $n$ is not too big {extract digits from $n$ and insert them into the sequence, then set $n = n + 1$}"
Given a number $n$, the total number of digits to represent $1$ to $n$ can be obtained as follows. Let $k = \left \lfloor \log_{10}(n) \right \rfloor$. Then the number of digits from $1$ to $10^k-1$ is given by $$\sum_{l=1}^k l \cdot 9 \cdot 10^{l-1} = k \cdot 10^k - \dfrac{10^k-1}9$$ Hence, the number of digits needed to list $1$ to $n$ is $$f(n) = \underbrace{k \cdot 10^k - \dfrac{10^k-1}9}_{\text{Number of digits from $1$ to $10^k-1$}} + \overbrace{(k+1)\left(n+1-10^k\right)}^{\text{Number of digits from $10^k$ to $n$}} = (n+1)(k+1) - \dfrac{10^{k+1}-1}9$$ where $k = \left \lfloor \log_{10}(n) \right \rfloor$. The function you are after is the inverse of $f(n)$.
stackexchange-math
{ "answer_score": 3, "question_score": 5, "tags": "sequences and series" }
It is ok to delete found.000 folders range from ntfs partion? I am using `windows-Ubuntu` dual boot and have one `ntfs` partition which is used by both windows and `Ubuntu` But i don't understand why Ubuntu creates `found.000` `found.001` etc.folders? I want to know all these folders are important ? or it is fine if we delete it ?. ![enter image description here](
These folders are created by the Windows Check Disk file system scans. They have nothing to do with Ubuntu. They may not have been visible on your Windows system, but they are visible on Ubuntu. They may contain data rescued after a Windows system crash, so go through them in case you may miss something.
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 0, "tags": "partitioning, directory, ntfs" }
Unexpected String Can anyone help with this debug issue? Trying to take the variables and throw them in a Change for CSS to get the background to change into a gradient. var gradientAlpha = "#999"; var gradientBravo = "#555"; $('#banner-gradient') .change(function() { $('.banner-gradient').css({'background': 'linear-gradient(135deg,' + gradientAlpha + ',' + gradientBravo ')'}); }) .change();
Missing a `+` after `gradientBravo` `gradientBravo` is a variable which you trying to add to a string. So you should have + before and after. $('#banner-gradient').change(function() { $('.banner-gradient').css({'background': 'linear-gradient(135deg,' + gradientAlpha + ',' + gradientBravo+')'}); });
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, jquery" }
Calculate a formula in Reverse Polish Notation I hope I'm writing this post in correct forum. I've got a equation `-11*2*(-1)*3` which i transferred into RPN -> `11,2,*,1,-,*,3,*,-`. And here I have problem with resolving it: 11*2 = 22 22-1= 21 22*what = ? what should i multiply by in last equation (I've got nothing left on stack) ...?
There seems to be some confusion in the question about whether $−$ is a binary or unary operator. Certainly you shouldn't be doing any subtraction when computing this product... I would translate this expression (it's not an equation, there's no equals sign) as $$−11,2,*,−1,*,3,*,$$ or if you require that we use only positive integers and interpret $−$ as a unary negation operator, $$11,−,2,*,1,−,*,3,*.$$
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "polish notation" }
PySpark add column if date in range by quarter I have a df as follows: name date x 2020-07-20 y 2020-02-13 z 2020-01-21 I need a new column with the corresponding quarter as an integer, e.g. name date quarter x 2020-07-20 3 y 2020-02-13 1 z 2020-01-21 1 I have defined my quarters as a list of strings so I thought I could use .withColumn + when col('date') in quarter range but get an error saying I cannot convert column to boolean.
You can use `quarter` function to extract it as an integer. from pyspark.sql.functions import * df1=spark.createDataFrame([("x","2020-07-20"),("y","2020-02-13"),("z","2020-01-21")], ["name", "date"]) df1.show() +----+----------+ |name| date| +----+----------+ | x|2020-07-20| | y|2020-02-13| | z|2020-01-21| +----+----------+ df1.withColumn("quarter", quarter(col("date"))).show() +----+----------+-------+ |name| date|quarter| +----+----------+-------+ | x|2020-07-20| 3| | y|2020-02-13| 1| | z|2020-01-21| 1| +----+----------+-------+
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python 3.x, apache spark, apache spark sql" }
Set mywallpaper in android after pressed button I made my own wallpaper and I don't know how to set this when the user clicked over button “SET WALLPAPER” I wrote: <uses-permission android:name="android.permission.SET_WALLPAPER" /> <uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" /> But not the code, I need your help.
this is my solution .... launch with Intent the MyWallPaperService Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER); intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(getApplicationContext(), MyWallpaperService.class)); startActivity(intent); thanks!
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "android, wallpaper" }
Who invented the concepts of potential and kinetic energy? Who invented potential and kinetic energy ? Was it Newton ? Or someone else ? I have the impression Newton used those ideas but they already existed.
In a way, it goes back to Aristotle and his dual concepts of actuality and potentiality. My quick description of them is as follows: * **Potentiality:** Potentiality, or _dunamis_ , is the stored ability an object has to do something or be something. * **Actuality:** Actuality, or _entelecheia/energeia_ , is what an object is doing or is at a point in time. Now, these had broader definitions than the ones we use to day for potential and kinetic energy. For example, according to Aristotle, the potentiality of an object included all the forms it could take (e.g. clay could become a sculpture). These are clearly not the same things as today's notions of kinetic and potential energy, but they were the precursors to our modern ideas.
stackexchange-hsm
{ "answer_score": 5, "question_score": 6, "tags": "physics" }
jquery uncheck dynamic checkbox I am using load() to import some html into my page which includes some checkboxes. I'd like to have a refresh button which clears any checked checkboxes but I have been unable to get this working. Please let me know what else I can try. This selector does find all checkboxes which are 'checked' but none of the functions uncheck the checkbox. $('#reset_button').on('click',function() { $(':checkbox:checked').each(function() { //alert($(this).val())}); $(this).prop('checked',false); $(this).attr('checked',false); $(this).val('off'); $(this).removeAttr('checked'); }) } ); Conclusion note, I had to remove a class from the parent element which was styling the checkbox. the functions provided below were updating the status of the checkbox to 'unchecked' but item was not being redrawn due to styling
Here is the single line code that uncheck all the checked checkboxes. _(This example illustrates both check and uncheck all checkboxes using jquery)_ **Set`prop` of the checkbox to `false`** $("input:checkbox").prop('checked', false);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, checkbox, dynamic" }
What is the meaning of "one of those shilling in the slot affairs"? In _A Taste Of Honey_ by Shelagh Delaney I found this: > (She wanders around the room searching for fire.) "Where!" she says. She can never see anything till she falls over it. Now where's it got to? I know I saw it here somewhere . . . **one of those shilling in the slot affairs** ; the landlady pointed it out to me as part of the furniture and fittings. Is it a metaphor? Does it just mean that it is something that costs money or is there a special meaning? On the Internet I could find different variations where instead of word _shilling_ were used _coins_ , _penny_ , _nickle_. Another example from the Internet: > This park stretches over 1,000sqkm from Torquay to Princetown and boasts numerous picnic and barbeque spots. Some are **coin-in-the-slot affairs** , others are push button and free of charge, while still others are the old-fashioned kind: strictly BYO fuel.
Need a bit more context really, but I would take it to mean 'purely mechanical'. Edit: a gas fire, of the metered type that means you put a shilling in the slot and get enough gas to heat the room for a certain time.
stackexchange-english
{ "answer_score": 2, "question_score": 2, "tags": "meaning, sentence" }
What does 含饴弄孙 mean? What does mean? What's its origin, what sort of contexts is it usually used in and also how popular an idiom is it? It does not seem to appear in any regular Chinese-English dictionary I've found, and the Chinese idiom guides seem pretty cryptic about this (to me anyway).
It is a popular idiom that describes the leisure life of elderly people. : keep something in mouth : syrup / candy / suger : play with : grandson So this idiom means to play with grandchildren with candy in mouth. You can also check its Chinese explanations at : hán yí nòng sūn ·“” · The links in my answer point to an online Chinese English dictionary, which has usage examples that extracted from China Central Television (CCTV) news. You can see the most fresh examples of the words you are looking for.
stackexchange-chinese
{ "answer_score": 4, "question_score": 5, "tags": "idioms" }
How can one compute the PRESS diagnostic? If an answer is illustrated with `R` code, it would be even more gratefully accepted.
For linear regression model, given the hat matrix $$ H = X (X'X)^{-1} X' $$ and residuals $e_i$, PRESS can be calculated as (see also here): $$ \mathrm{PRESS} = \sum_i \left( \frac{e_i}{1-h_{ii}}\right)^2$$ This can be easily translated to the simple function: PRESS <- function(linear.model) { pr <- residuals(linear.model)/(1 - lm.influence(linear.model)$hat) sum(pr^2) }
stackexchange-stats
{ "answer_score": 6, "question_score": 2, "tags": "r, regression, model selection" }
Launch c# executable when files dragged to the desktop icon I have created a small c# windows application in which it converts the txt, jpg,doc,, ppt and excel files to pdf files. I have created a setup file for this application and while installing the setup file desktop shortcut icon will get created. Now let me explain my requirement. Drag a set of files on the application icon and it should launch the application with list of files dragged on the desktop icon. Is there some properties or code which i need to add.
you just need to use the args from main, which will be the files: Drag and Drop onto Desktop Icon seen here.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c#, windows, winforms, setup project" }
Switching between breakpoints How to switch between breakpoints in normal mode not in run mode in c# using keyboard shortcut See, if I keep a break point on top and bottom of the coded page, its difficult to scroll up and down as the code is very lengthy, so I need to know the shortcut to switch over breakpoints.
you can use `Ctrl` \+ `Alt` \+ `B` it open a break point window and you can navigate !enter image description here
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "c#, visual studio" }
Use an object after it has been released? I am going through Cocoa Programming for Mac OS X by Aaron Hillegrass and have come to something I do not understand. On page 150-151 he creates an object, releases it, and then uses it again. For example: - (void) someMethod { NSMutableArray *array = [[NSMutableArray alloc] init]; NSString *str = [[NSString alloc] initWithString:"This is a string."]; [array addObject:str]; [str release]; int x = [array indexOfObjectIdenticalTo:str]; NSLog(@"the index of %@ in the array is %d", str, x); } How does this work if the object has been released? Is the object still valid until the method is finished or set to `nil`?
Adding it to the array will increase the reference count, so the explicit release will leave the reference count as 1. It's not good practice (you shouldn't release something until you're done referencing it), but in this case it's safe.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "objective c, cocoa" }
LOESS residual output in R When I extract residuals from a LOESS regression the output is in multiple columns instead of just 2- the line number and the result. ![LOESS regression output]( Once you export this to excel it will spit it out with all sorts of errors or requiring shifting some lines over a few columns and always reducing everything to 2 columns which takes forever. Is there a way to adjust the output format in R?![LOESS residual out in excel](
Your R-output is a vector, with the integers indicating the data point (i.e. first, second, ...). In other words: no, you don't have multiple columns; this is an artefact when opening/reading it into Excel. When you export it, simply use `write.csv` or alike and you will get a friendly, single-column file (or two-column, if you have and keep the row names). cars.lo <- loess(dist ~ speed, cars) resids <- residuals(cars.lo) write.csv(resids, "loRes.csv") This example has no row names, hence is a single column, with a column variable name ("x"). You should have no trouble reading that into Excel (other spreadsheet software is available).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "r, interpretation, excel, loess" }
Reducing dimensions by considering ex-ante instead of ex-post symmetry Let $\mathbf x = (x_1,\ldots,x_n) \in \mathbb R^n$. Consider the following problem: \begin{align} \max_{\mathbf x}f(\mathbf x). \end{align} Presume that $\mathbf{\bar x} = \underbrace{(\bar x,\ldots,\bar x)}_{n \text{ times}}$ is the unique maximizer of $f$, i.e. \begin{align} \mathbf{\bar x} = \arg\max_{\mathbf x}f(\mathbf x). \end{align} Let $F(x) = f(x,\ldots,x)$. I was wondering if the following statement is true: \begin{align} \bar x = \arg\max_{x \in \mathbb R}F(x). \end{align}
Short answer: **Yes!** **Proposition.** Let $n\in\mathbb N, f: \mathbb R^n \rightarrow \mathbb R$ and $\mathbf{\bar x} = (\bar x, \ldots, \bar x)\in\mathbb R^n$ such that $f(\mathbf{\bar x}) > f(\mathbf y)$ for all $\mathbf{\bar x} \neq \mathbf y$ in $\mathbb R^n$. Let $F: \mathbb R \rightarrow \mathbb R: x \mapsto f(x,\ldots,x)$. Then $F(\bar x) > F(y)$ for all $\bar x \neq y \in \mathbb R$. _Proof._ Since we have $f(\mathbf{\bar x}) > f(\mathbf y)$ for all $\mathbf{\bar x} \neq \mathbf y\in \mathbb R^n$, we have $f(\mathbf{\bar x}) > f(\mathbf y)$ in particular for all $\mathbf y = (y, \ldots, y) \in \mathbb R^n$ (where $y\neq \bar x)$. By definition it follows that for all $\mathbf y = (y, \ldots, y) \in \mathbb R^n$ ($y\neq \bar x$): $\; F(y) := f(y,\ldots, y) = f(\mathbf y) < f(\mathbf {\bar x}) = f(\bar x,\ldots, \bar x) = F(\bar x)$ and thus $\bar x$ is a unique maximizer of $F$. $\quad\square$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "optimization" }
Are all tastes just a combination of sour, sweet, bitter, etc.? For example, can the taste of pineapple be isolated to just a certain amount of "salty-taste-triggering-molecules" and "sweet-taste-triggering-molecules" etc.? Can our current understanding of the gustatory system predict the taste of a new substance (for example we could predict it tastes like chocolate) just based on the amount and ratios of these molecules?
Interesting question. > The brain perceives taste or flavor as a combination of input from taste buds, the olfactory system, and even pain receptors (spicy foods). Other food contents, such as metal, spice, fat, pH, and even dissolved gas content seem to contribute. While there are 5 types of taste receptor, there are some 2000 olfactory bulbs encoded by 1000s of gene. As such, it is not possible to predict how something will taste in a simplistic 5-taste combo. However, this is an area of active research, such that structural models are used to develop taste enhancers, artificial sweeteners etc. Sources: * < * < * <
stackexchange-biology
{ "answer_score": 2, "question_score": 2, "tags": "human biology, brain, human physiology, taste, gustation" }
Resolve Undefined namespace Mailer CakePHP 3.0.3 I'm trying to create a **Email** Reusable provided by CakePHP 3 but even the the following documentation but got the following error: use Cake\Mailer\Mailer; **Error:** > Undefined namespace Mailer > > Referenced namespace is not found. I created the file in the same directory specified in the documentation **NOTE:** I am using **CakePHP 3.0.3** Link to the documentation
Mailers are only available as of CakePHP 3.1, which is currently in beta phase. Maybe the docs were updated a little too early. * **< * **< * **<
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php, cakephp, cakephp 3.0" }
How to ad local currency symbol - ios in app purchase How can I add the local cyrrency symbol to the Buy-Button from < [buyButton setTitle:[@"Buy Game Levels Pack " stringByAppendingString:productPrice] forState:UIControlStateNormal];
Code like the following will work: SKProduct *product = ebp.validProduct; // epb is the EBPurchase object NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; [numberFormatter setLocale:product.priceLocale]; NSString *formattedPrice = [numberFormatter stringFromNumber:product.price]; `formattedPrice` will have the appropriate currency formatting. You should also use the `localizedTitle` and `localizedDescription` from `product` for the product's title and description. This is all obtained from the data you setup in iTunes Connect.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 1, "tags": "iphone, ios, in app purchase" }
Does spheres of dimension n≥2 admit ­symmetric flat connections? I need reference where they talk about to prove that spheres of dimension n≥2 don't admit ­­­­symmetric flat connections.
Manifolds which admit symmetric flat connections are known as affine manifolds. A standard result on these spaces is that the fundamental group of a compact affine manifold must be infinite. For a reference, see Corollary 1.14 of the following lectures. <
stackexchange-mathoverflow_net_7z
{ "answer_score": 1, "question_score": 0, "tags": "dg.differential geometry" }
Prove that a definition of $\mathcal{I}$ does not satisfy the exchange property For a graph $G=(V,E)$ ($V$ set of vertices and $E$ set of edges ), $\mathcal{I}$ is defined as all of the subsets $E´\subseteq E$ where the components of $(V,E´)$ that are connected are simple paths. I want to show that $(E,\mathcal{I})$ does not satisfy the exchange property of a matroid. I have tried to find an example by drawing two graphs, that is, two graphs with all of the vertices $V$ and where each graph has a set of edges and the edges that are connected are simple paths (no cycles). And I tried to make one graph have more edges than the other and find an example where we can NOT add an edge that is in the graph with more edges (but not in the graph with less edges) to the graph with less edges. I always find an edge that can be added. But I can not find such an example and I am stuck. Maybe there is a simpler way to prove it?
Take two paths $1234,5678$. Assume that there are no edges between their endpoints (so that you can not enlarge this independent set of 6 edges) but there exists a Hamiltonian path, say 13657428. You get two inclusion-maximal subsets of different size, thus it is not a matroid.
stackexchange-mathoverflow_net_7z
{ "answer_score": 0, "question_score": 0, "tags": "co.combinatorics, matroid theory" }
Autocomplete in PyCharm for Python compiled extensions When writing Python code using compiled extensions (the OpenCV Python bindings, for example), PyCharm doesn't seem to be aware of their availability. The imports are marked with a grey underline, saying "unresolved reference" as a tooltip, and autocomplete doesn't work, either. (Except for the function names already used in the code.) This isn't caused by wrong module paths, the code runs without error when started. Also, after I import the modules in a Python shell, autocomplete starts working as expected. Is there a solution for that or is this an architectural limitation for compiled extensions? Are there any other IDEs that manage to cope with this problem?
> The imports are marked with a grey underline, saying "unresolved reference" as a tooltip This most probably means that PyCharm can't see the module you import. In editing mode, PyCharm relies on availability of Python sources of imported modules. If a module is not written in Python but is a C extension module, PyCharm generates a 'skeleton' that contains function prototypes, and uses it for completion. In shell mode, PyCharm uses live imported objects for completion, with slightly different results. Make sure that your OpenCV installation is visible for the Python interpreter you chose for the project (File / Settings / Python interpreter). If the interpreter is correct, try removing and re-adding it (this is time-consuming a bit, sorry). If nothing helps, file a bug.
stackexchange-stackoverflow
{ "answer_score": 19, "question_score": 32, "tags": "python, autocomplete, pycharm" }
Accepted practice for an ES6 module imported just for side-effects? I like to keep my code modular, so I put this kind of code in a separate file (`overrides/extra.js`): import Ember from 'ember'; Ember.RSVP.configure('onerror', function(error) { .... }); export default null; This has only the side effect of configuring `Ember.RSVP` but does not export anything of value. I would then import this in `app.js`: import dummy from './overrides/extra'; Is this accepted practice?
Yes this is _accepted_ if your module doesn't need to export any data, but there's no need to export anything from a module if it's not required: import Ember from 'ember'; Ember.RSVP.configure('onerror', function(error) { .... }); **app.js:** import './overrides/extra';
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "javascript, ember.js, ecmascript 6" }
htaccess regex to grab additional field I have the following regex although it only picks one variable and puts that in user like user contains user/url, how would I modify this to grab the url variable seperately in $2. RewriteCond %{HTTP_HOST} ^(^.*)\.example.com$ [NC] RewriteRule ^(.+/?[^/]*)$ [P,NC,QSA,L] I need this to translate to
Your regex to capture 2 values from `RewriteCond` and `RewriteRule` doesn't seem correct. You may use: RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$ [NC] RewriteRule ^([^/]+)(?:/([^/]+))?/?$ [P,NC,QSA,L] I assume you have `mod_proxy` setup since you're using `P` flag.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "regex, .htaccess" }
Notation in a Dirichlet Character What is the meaning of the sign in the notation for these Dirichlet characters? In the context of specific cases building up to a general proof of the Theorem Primes in Progressions there are several depictions of characters: In the case of $\pmod 3$, there is the symbol $\chi_{- 3}(n)$. Whereas in the case of $\pmod 8$, there are $\chi_{- 8}(n)$ and $\chi_{8}(n)$. In the latter instances, the values of $+ 1$ and $- 1$ attributed to $n \equiv 3$ and to $n \equiv 7$ are interchanged. Thanks
$\chi_{-8}(n)$, $\chi_8(n)$ have another notation: $$\left(\frac{-8} {n}\right), \left(\frac{8} {n}\right)$$ This is Jacobi symbol, and notice that they are equivalent to $$\left(\frac{-2} {n}\right), \left(\frac{2} {n}\right),$$ and well-known formulas $$\left(\frac {-1} n\right)=(-1)^{\frac{n-1}{2}},\left(\frac {2} n\right)=(-1)^{\frac{n^2-1}{8}}.$$
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "number theory" }
How can I get Eclipse to launch Ant in one keypress? I changed the keybinding for `Run Ant Build` to `F10` when `Editing Javascript Source` and also tried `In Windows`. In both cases F10 opens the file menu. If I press `F11` while the ant build.xml is highlighted, it runs. If I press `F11` any other time Eclipse opens up the Debug Configuration dialog. If I try `Ctrl` \+ `F11` it tells me there are no launch configurations. I basically have an Ant build that concats and minifies all the js files in my project. I would like for it to run in lieu of compile while I am editing that project and to be ignored otherwise.
Can't you add a builder to the project and make the step to process the .js files part of the build action? Go to the project properties an choose builders. Click 'New...', choose the Ant Builder and configure it. This way Eclipse will invoke the Ant script when building the project and you don't need to perform that step manually.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, eclipse, ant, keyboard shortcuts" }
Which decision tree algorithm does scikit-learn use by default? There are a couple of algorithms to build decision trees such as CART (Classification and Regression Trees), ID3 (Iterative Dichotomiser 3) etc Which decision tree algorithm does scikit-learn use by default? When I look at some decision-tree python scripts, it magically produces the results with `fit` and `predict` functions. Does scikit-learn cleverly choose the best decision-tree algo based on the data?
It doesn't automatically do so. If we look at the sklearn.tree.DecisionTreeClassifier page, we can see that the default criteria is gini impurity. There is also an option to use entropy instead for the criterion. Note that CART uses gini impurity and ID3 uses entropy as splitting criteria.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "scikit learn, decision tree" }
Predicate without using ; I have this two types of facts. vowel(a). vowel(e). consonant(b). consonant(c). Now i need to implement a predicate letter/1. The most obvious way would be: letter(X):-vowel(X); consonant(X). But I need to define this predicate without using ; operator. Any ideas?
Just define two separate rules for `letter(X)`: letter(X) :- vowel(X). letter(X) :- consonant(X). If the first rule doesn't apply (i.e. `vowel(X)` is not true), then the second rule will be checked as well. In other words, if either `vowel(X)` or `consonant(X)` evaluate to true, then so will `letter(X)`. In effect, having multiple rules for a predicate acts as a logical or.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "prolog" }
allFilms.map is not a function I want to get a JSON from a films API, I get the datas in the variable "data", but my array "allFilms" still empty even after the datas are loaded... (see the code below), Why my array is still empty please ? const [allFilms, setAllFilms] = useState([]); const [pending, setPending] = useState(true); const [activePage, setActivePage] = useState(1) const url = ` useEffect(() => { loadAllFilms(); }, []); async function loadAllFilms() { try { const data = await axios.get(url); console.log("data ", data); **<--- THIS CONSOLE.LOG GOT THE DATA** setAllFilms(data); console.log("allfilms ", allFilms); **<--- THIS CONSOLE.LOG IS EMPTY** setPending(false); } catch (error) { console.error(error); } };
From your code, we only can guess that the error is due to your response type. If it's a JSON array you should try: const data = await axios.get(url); setAllFilms(data.json);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "reactjs" }
How should I do clear screen on ocaml toplevel? I am using ocaml toplevel with ledit (ledit -l 100 ocaml) on Ubuntu 14.04. Since there is no way to do clear screen, all the time, I keep dwelling at the bottom of the screen. I would like to know if there is a way to do clear screen at toplevel? Thanks in advance. Regards.
You could try: # Sys.command "clear";; However, it is normal to dwell at the bottom of the screen. The command line has worked this way for at least 30 years :-)
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "ocaml, ledit" }
Copies of $c_0$ in $C[0,1]$ and disjoint sequences Let $M$ be a subspace of $C[0,1]$ isomorphic to $c_0$. QUESTION: Is it possible to find a normalized disjoint sequence $(f_n)$ in $C[0,1]$ such that the distance of $f_n$ to $M$ tends to $0$ as $n$ goes to $\infty$? Arguments in favor: 1. If $1\leq p<\infty$, then the result is true for subspaces of $L_p(0,1)$ isomorphic to $\ell_p$. 2. If we consider the continuous linear projection $P$ on $C[0,1]$ onto $M$, then it was proved by N. Ghoussoub and W.B. Johnson [Math. Z. 194, 153-171 (1987); Theorem I.3] that $P$ is an isomorphism on the closed subspace $[g_n]$ generated by some normalized disjoint sequence $(g_n)$. With respect to 2, if I were able to show that $[g_n]\cap M$ is infinite dimensional or $[g_n]+M$ is not closed, then it would be easy to get a positive answer.
Take sequences of clopen sets $M_i$, $N_i$, s.t. any two of the $N_i$ have non empty intersection but any three have empty intersection, and the $M_i$ are pairwise disjoint and disjoint from the $N_i$. Let $f_i$ be the characteristic function of $M_i \cup N_i$. This gives a counterexample in $C(\Delta)$, $\Delta$ a Cantor set. Doing it in $C[0,1]$ is similar but not as nice to describe.
stackexchange-mathoverflow_net_7z
{ "answer_score": 4, "question_score": 3, "tags": "fa.functional analysis, banach spaces, banach lattices" }
Perl Mime Problem I m newbie at perl.I'm trying to use Mime::Lite.I looked their site and i try to sending mail this way #!/usr/bin/perl use MIME::Lite; $msg = MIME::Lite->new( From =>'[email protected]', To =>'[email protected]', Cc =>'[email protected], [email protected]', Subject =>'Helloooooo, nurse!', Data =>"AAA" ); $msg->send; But mail did not come to my mail adress.What should i do?
What platform? On a well-configured Linux/UNIX box this usually works as is, but if you're using Windows, you probably need to tell it how to send the mail. The following should do the trick: #!/usr/bin/perl use strict; use warnings; my $msg = MIME::Lite->new( From => '[email protected]', To => '[email protected]', Cc => '[email protected],[email protected]', Subject => 'Hello, World!', Data => 'Test.', ); $msg->send(smtp => 'smtp.example.com'); where `smtp.example.com` is the SMTP server that your internet provider tells you to use.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "perl" }
How do I break a moving objects speed up into its X and Y velocity given a fixed speed/angle? Math escapes me today. How do I find the X speed and the Y speed of an object if it is going at a defined speed (say, 5 pixels/second) at a 45 degree angle?
So always 5 pixels/sec and always 45 degrees? The general case is velx=cos(a)*vel; vely=sin(a)*vel; a is angle, usually in radians, so convert from degrees, and the signs (positive/negative) will depend on your coordinate system. Crazy fact from the 1980s: In the old days, we used lookup tables for sin and cos! * * * Edited: Made my axes more conventional thanks to comment below. x is positive to your right. y is positive up. 45 degrees is to the northeast. If you have something else, let me know.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 0, "tags": "math, geometry" }
prevent googlebot from indexing file types in robots.txt and .htaccess There are many Stack Overflow questions on how to prevent google bot from indexing, for instance, `txt` files. There's this: `robots.txt` User-agent: Googlebot Disallow: /*.txt$ `.htaccess` <Files ~ "\.txt$"> Header set X-Robots-Tag "noindex, nofollow" </Files> However, what is the syntax for both of these when trying to prevent two types of files from being indexed? In my case - `txt` and `doc`.
In your robots.txt file: User-agent: Googlebot Disallow: /*.txt$ Disallow: /*.doc$ More details at Google Webmasters: Create a robots.txt file * * * In your .htaccess file: <FilesMatch "\.(txt|doc)$"> Header set X-Robots-Tag "noindex, nofollow" </FilesMatch> More details here: <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "apache, .htaccess, robots.txt, googlebot" }
Notification is not being called in Reachability I have used **Andrew's** modified Reachability class. -(void)viewDidLoad [[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification object:nil]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil]; When data is downloading I turn `AirPort` off. But `checkNetworkStatus` is not being called. Am I missing something. Please help me. This problem driving me nuts. Thanks in advance.
put it in this sequence in ur view did load First register then post that notification [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil]; [[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification object:nil];
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 5, "tags": "iphone, ios4, reachability" }
How to make HTML written by users on a site, not conflict with the site's stylesheets? I have a website that allows a user to create blog posts. There are some backlisted tags but most standard HTML tags are acceptable. However, I'm having issues with how the pages get displayed. I keep the HTML wrapped in its own div. I would ultimately like to keep the HTML from the user separate from the main sites stylesheets so it can avoid inheriting styles and screwing up the layout of the originating site where the HTML is being displayed. So in the end, is there anything I can apply to a div so its contents are quarantined from the rest of the site? Thanks!
You could use a reset stylesheet to reset the properties for that specific `DIV` and it’s children. And on the other side, you’ll probably need a CSS parser to adjust the user’s stylesheet for that specific `DIV`.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "html, css, blogs, conflict, sanitization" }
Cannot save files in Kdenlive snap, why not? For some reason, Kdenlive (snap version) is not saving files. The program things it is saving, but nothing is actually written to the disk. I've enabled removable drive access permissions, but that hasn't changed anything. It won't even save anything in the `~/Snap/kdenlive` folder!
I get the same problem. `kdenlive` (snap version) does not save file in `.kdenlive` format; but the project is saved in a other way. If you go to the `kdenlive` folder and show the hidden data, you can see file like this `.xdp_321.MAXUN0`, 321 is the file name you have saved before. Open this file with `kdenlive`, then you will get your saved project back.
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 1, "tags": "permissions, filesystem, security, snap, kdenlive" }
How do I change the position of HTML inserted during a Wordpress Action I'm pretty new to PHP development. I'm trying to build a WordPress plugin for experience. I'm using: function spg_insert_comment_form() { if ( ! is_admin() ) { print 'Test Form Position'; } } add_action( 'comment_form', 'spg_insert_comment_form' ); To insert additional html into the contact form. Eventually, I will add a form that submits with the comment. The problem is (or at least the only one I see) is that it's inserting my html after the submit button. Is there a hook that would allow me to place my code before the submit button or should I take another approach such as kicking off JavaScript that inserts my form. **Edit:** While waiting for a reply I was able to successfully solve the problem using PHP to call a JavaScript function. It works great but I'm trying to learn development best practices as well. Is this approach considered hackish?
Check out all possible actions for comment_form, like: * comment_form_before * comment_form_top * comment_form * comment_form_after <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, wordpress" }
Filling hash by reference in a procedure I'm trying to call a procedure, which is filling a hash by reference. The reference to the hash is given as a parameter. The procedure fills the hash, but when I return, the hash is empty. Please see the code below. What is wrong? $hash_ref; genHash ($hash_ref); #hash is empty sub genHash { my ($hash_ref)=(@_); #cut details; filling hash in a loop like this: $hash_ref->{$lid} = $sid; #hash is generetad , filled and i can dump it }
You might want to initialize hashref first, my $hash_ref = {}; as autovivification happens inside function to another lexical variable. (Not so good) alternative is to use scalars inside `@_` array which are directly aliased to original variables, $_[0]{$lid} = $sid; And btw, consider `use strict; use warnings;` to all your scripts.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "perl, hash, reference" }
Why didn't Voldemort delay his return until after Harry Potter had died? During 1st Wizarding War, Voldemort came to know about The Prophecy. He tried to challenge it (although he unknowingly supported it) and he not just failed, but lost his body too. Then, what was the point of challenging it, again? He could have simply waited until Harry died naturally (or, killed by someone... probably Death Eaters). After this, he would have confidence due to The Prophecy (which I don't think changes.. Think record spheres). Nobody would be able to stop him, then..
# Why should he wait? He has literally nothing to lose. Right now, he is bodyless, his soul bound to the world of the living only by his Horcruxes. He has nothing else to do than to try to get his body back. If he manages to make his comeback and is defeated _again_ , he is back to square one, bodyless and Horcrux-bound. But he did not lose anything. So the worst thing that can happen to him is having to create a new body for himself. **If he can return once, he can return twice.**
stackexchange-scifi
{ "answer_score": 10, "question_score": 8, "tags": "harry potter, voldemort" }
Types of risk for stock investing Question: We suppose that the Toyota is traded in Tokyo in Japanese yen and represented by the price process $(S_t)$ t≥0, and in New York in US dollars and represented by the price process $(U_t)$ t≥0. What are the sources of risk faced by an American investor who has bought the Toyota stock in New York at the price Ut? My attempt: Market Risk - Toyota share pricing falling Systemic Risk - Collapse of entire financial system Liquidity risk - Not being able to exit position Just wanted to check that there is _not_ any FX risk here, as the US investor has bought $ donimated stock, so it is irrelevant that Toyota is also traded in Japanese markets in Yen.
> Just wanted to check that there is not any FX risk here, as the US investor has bought $ donimated stock, so it is irrelevant that Toyota is also traded in Japanese markets in Yen. An American investor stills has currency risk. A simple way of thinking about it might be to consider what would happen if Toyota share price went up 1% but USD declined by 1% vs JPY. The US ADR (American Depository Receipt--this is what is listed in the US and what the American investor buys in your example) will not move the same way as it's Tokyo traded counterpart would because of the currency fluctuation baked into the ADR. On the flip side, if the American investor bought the ADR and the USD appreciated vs JPY the American investor could outperform the Japanese listed stock. EDIT: After posting an answer I did a quick search of SE and saw that this question has already been asked and answered here as well: <
stackexchange-quant
{ "answer_score": 4, "question_score": 3, "tags": "risk management" }
Using relative paths in imports parameter of GDB repository configuration? According to the GDB documentation, it seems like it should be possible to use relative paths in the imports parameter of a GDB repository configuration. But I cannot make it work! Does anyone know how relative paths are resolved?
GraphDB will check the value of these two parameters: owlim:defaultNS " ; owlim:imports "myFile1.ttl;myfile2.ttl" ; Please make sure that the parameters both have the same length; otherwise, the database will not know what the default prefix for each file is. The database will search the files in the $GDB_HOME/bin path. **Edit on 24/04/2020:** GraphDB uses the home directory of the process, which by default will match $GDB_HOME/bin. Still, in the general case, this is not always true so the correct way of converting the relative path into absolute is to check the home directory of the process with `sudo lsof -p <pid> | grep cwd`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "graphdb" }
Convert a number to its string representation I'm developing a simple web application where in I need to display number a to my users in string format. Example: 12 - One Two or Twelve -20 - minus Two zero or minus twenty Either way is fine. I need this to be done in PHP. Any help will be appreciated.
for the first option (spell out digits), strtr is your friend $words = array( '-' => 'minus ', '1' => 'one ', '2' => 'two ', etc.... ); echo strtr(-123, $words);
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 4, "tags": "php, string" }
How to store string from an array of strings in to a variable in C #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { char movie[15]; char movielist[25][30]={"thalaiva","aruvi","sarkar","visvasam","veeram","mersal","bigil","kaithi","mahanadhi","papanasam","vishwaroopam","padayappa","thadam","indian","petta","kaala","psycho","comali","bahubali","saaho","enthiran","vettai","asuraguru","penguin","cocktai"}; movie=movielist[rand()%25]; printf("%s",movie); } I want the variable movie to store any random string from the array movielist! The code above gives me error. main.c:8:7: error: assignment to expression with array type movie=movielist[rand()%25];
Use char pointer instead of char array: char *movie; // instead of char movie[15]; ... movie = movielist[rand() % 25]; If you use `movie[15]` as you did, you can't assign it to individual item in the `movielist` as assignment operator does not work with array.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "arrays, c, string" }
Restrict Swagger UI access - user login I am using Swagger UI for interactive REST endpoints representation. However, Swagger UI can be accessed by everyone who knows its URL. Is there any standard way to restrict Swagger UI access with user login?
If you're using nginx you could add basic HTTP Authentication. Then anytime anyone goes to your docs url or sub-domain they'll get a pop-up user/password dialog before being able to access swagger-ui. Full instructions for creating your user/password combinations (assuming Ubuntu): sudo apt-get install apache2-utils sudo htpasswd -c /etc/nginx/.htpasswd exampleuser The tool will prompt you for a password. Then update your nginx file to have something like this for the docs route: location /docs { auth_basic "Restricted Content"; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass } Then reload nginx: sudo /etc/init.d/nginx reload
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "rest, authentication, swagger, swagger ui" }
Can I add row in handsontable by "insert" key.? I want to add a row in handsontable by "insert" key. is it possible to add row by a key.
Yes, you can. What you need to do is first capture the "insert" key event. You then call on your handsontable instance and use the `alter ('insert_row', index, amount)` where index is the position you want (set it to 0 to add to the top, for example), and amount is how many empty rows. That should be it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "jquery, handsontable" }
firebase observeSingleEvent deprecated in swift What do I use to make a single event observe? I've tried searching the internet and can't find anything that talks about it being deprecated. And I say it's deprecated because the method is crossed out when I type it in xcode. Should I just do regular observe, then remove it right after?
is it I am still using it . try using Following code . which pod version of firebase Are you using and Xcode version ? let databaseRef = Database.database().reference() databaseRef.child("Users").observeSingleEvent(of: DataEventType.value, with: { (snapshot) in if snapshot.hasChild(strrr){ print("true rooms exist") databaseRef.child("Users").child(strrr).child("Requests").child(emailIdCurrent).setValue("False") }else{ print("false room doesn't exist") } })
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ios, swift, firebase" }
Problems with encoding I'm using MySQL 5.1 and Susbsonic 3.0.0.3. Database and all tables are in cp1251. I have problems with saving russian symbols. After saving it looks like "?????". How i can setup subsonic to save symbols in cp1251? P.S. With reading everything is ok.
I've solved problem. I set parameter init-connect init-connect=SET NAMES cp1251 But it is not good solution to this problem!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "subsonic, subsonic3" }
Determine the maximum area of a norman window with a perimeter of $800$ I need help with the following question > Determine the dimensions of the window with the maximum area, if the perimeter of the window is $800$cm. I have made a diagram of the window that was given to us. Please excuse my bad paint skills `:)` !enter image description here I have done following work $$ A_c = \frac{\pi r^2}{2} \\\ A_r = lw \\\ P = 2l + w + \pi w$$ Rearranging the perimeter equation for length $$\begin{align} &800 = 2l + w + \pi w \\\ &\frac{800-2w-\pi w}{2} = l \\\ &\frac{400-w-\pi w}{2} = l \end{align}$$ Subbing $l$ into the Area equation $$\begin{align} &A(x) = lw + \frac{\pi w^2}{2} \\\ &A(x) = \left(\frac{400-w-\pi w}{2}\right)(w) + \frac{\pi w^2}{2}\\\ &A(x) = 400w-w^2\\\ &A'(x) = 400-2w\\\ &w = 200 \end{align}$$ The answer is supposed to be $86.2$ = $r$ and $h$ = $178.2$. Please point me the correct direction, I think I am making a really silly mistake with this one. Thanks!
Between $\frac{800-2w-\pi w}{2} = l \\\ \text { and } \frac{400-w-\pi w}{2} = l $ you didn't divide $\pi w$ or $l$ by $2$ when you divided the first two terms by $2$
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "calculus" }
Passing a parameter in event binding to component I am trying a angular project where i need to display n buttons and on click of each button it should display the button number. Is there a way to pass any static value in event binding which can be used in component for decision making. <button (click)="clicked('want to pass a value here')">Click </button> <h1>The button number you entered is: {{buttonNumber}}</h1> the values can be: 1, 2... n which will be used for decision making in controller class.
The code you have will work. You need to create a function in your component (in you case called click) and handle the $event that is passed in. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'example', template: ` <h1>The button number you entered is: {{buttonNumber}}</h1> <button (click)="clicked('want to pass a value here')">Click</button> ` }) export class ExampleComponent implements OnInit { constructor() { } ngOnInit() { } clicked(yourText) { // yourText is the argument from the template console.log(yourText) } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "angular, typescript" }
Create two nodes from webform submission I have webform with many fields. And I need to create two nodes after webform submission. First node would have some values from the webform. And second node would have other values from the same webform. How can I do this? (rules? hooks?) Would be using Webform Default Fields or Webform report the right solution?
I would recommend Rules. Here's a link. Using webform rules to create node after webform submission Hope that helps.
stackexchange-drupal
{ "answer_score": 1, "question_score": 0, "tags": "nodes, webforms" }
Calling WebService with Service Reference I am trying to call a web service that I have made. I have published it to a website, and added it to my solution as a Service Reference. All the calls are there, all the classes are there too. But when I try to call it, I get an invalid class. **Exception** > Cannot convert from 'GoS.GoSubmitWS.consent' to 'GoS.GoS.GoGetWS.consent' **Code** GoSubmitWS.consent consent = Database.DBConsent.GetConsentInfo(mjE.mj_message); if (consent == null) return; GoSubmitWS.GoSubmit_WebServiceClient wsClient = new GoSubmitWS.GoSubmit_WebServiceClient(); wsClient.ConsentInformation(Settings.Entity, mjE.mj_message, consent); Thanks for any help.
I managed to solve the issue by going through the generated service reference file and removing the namespace references in GoS.GoSubmitWS.consent went to GoSubmitWS.consent.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, web services, service reference" }
How do I make object vertices snap to each other in InkScape? Take the following image as an example: ![enter image description here]( I made it by first drawing one hexagram, then copying it, and moving it until the two centre vertices on the top and bottom horizontal looked to be in the same place. Then I drew the circle, and moved it until its centre looked to be aligned with the leftmost vertex. I would much prefer if I could have dragged the second hexagram until its vertices snapped to those of the first, and dragged the circle until its centre snapped to that side vertex. How do I do this?
You need to activate snapping. For drawing the hexagons, you probably want _snap to grid_ as an aid. Then, for aligning the two hexagons, you need node snapping. When dragging, drag by clicking next to the node you want to snap. In this case, for example, click near the top-right node, and drag until it drops near the top left node of the other hexagon. For the circle, you have to activate snapping on center of rotation. The use of guides and guide snapping may also come in handy.
stackexchange-superuser
{ "answer_score": 0, "question_score": 1, "tags": "inkscape, drawing, cad" }
MigraDoc - Width Percentage I am converting a current ITextSharp PDF Export to MigraDoc. it is a very table heavy PDF and a lot of use is made of `Table.WidthPercentage` which sets the width of `Table`. I am trying to replicate this in MigraDoc but so far have come up with nothing. I can probably do something manually but want to see if there was a better way of doing this? EDIT Now knowing that the MigraDoc Column widths are Absolute I am looking to apply the Width manually. In this particular instance I have a table that exists within a cell (as an element) of another table. I am therefore looking to capture the Column.Width of the parent table but it just keeps coming back empty? Is this not automatically set / calculated or am I looking in the wrong place?
Tables in MigraDoc have absolute dimensions. You know the width of your pages and can calculate absolute widths from percentages when needed.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, migradoc" }
gedit missing spell check database Spell check is installed and enabled in gedit, but the dictionary seems to be missing. When I enable autocheck spelling every word is highlighted as incorrect (and yes, some of them are spelled correctly). I'm running a fairly fresh copy of Debian Squeeze and I'm not sure if it's a distro issue or otherwise. I can't seem to find any hints as to what the issue might be through Google. Any help would be great.
It turns out I was missing the aspell package. In my case.. sudo apt-get install aspell-en or more generally... sudo apt-get install aspell-lang
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "spell check, gedit, debian squeeze" }
Add preceding zeros to all lines in a file I have a simple text file containing some random number on every line. I wish to add preceding zeros for numbers which are less in digits. Is there a way to do this on command line (UNIX) Input File: 235 25 1 963258 45 1356924 Output file: 0000235 0000025 0000001 0963258 0000045 1356924
Using `awk` \- `printf`: $ cat testfile 235 25 1 963258 45 1356924 $ awk '{printf("%07d\n", $1)}' testfile # %07d to pad 0s. 0000235 0000025 0000001 0963258 0000045 1356924
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "shell, unix, command line, sh, padding" }
Como criar um Constructor quando há if/else e variáveis externas? Tenho diversas variáveis como esta, que chamam um Elemento do HTML sempre com o mesmo nome: var $inputFromA = $(".inputFromA"); São pelo menos umas 10: `inputFromA`, `inputFromB`, `inputFromC`… Todas estas variáveis também chamam exatamente a mesma função: $inputFromA.on("input", function () { var val = $(this).prop("value"); if (val < min) { val = min; } else if (val > to) { val = to; } instance.update({ from: val }); }); É possível criar uma função construtora ou classe constante para que eu possa apenas declarar o nome da variável e chamar apenas a classe/função? Imagino que seria algo como: class InputFrom () {} var inputFromA = new InputFrom; A minha dificuldade se deve a quantidade de parâmetros que tal função deverá ter. Alguém poderia me dar uma força com isso?
Você pode relacionar essa função a uma constante ou uma variavel, e depois retornar o resultado dessa função: let ChamaFuncao = $inputFromA.on("input", function () { var val = $(this).prop("value"); if (val < min) { val = min; } else if (val > to) { val = to; } instance.update({ from: val }); return ChamaFuncao; }); depois daqui é só chamar a função sempre que quiser usar ela. aqui tem um link explicando bem sobre return: <
stackexchange-pt_stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "jquery, funções, construtor" }
How do ZK-STARKs, ZK-SNARKs, and Bulletproofs compare in size and speed for range proofs? How do ZK-STARKs, ZK-SNARKs and Bulletproofs compare in size and speed for range proofs? The general behavior is depicted in this chart. But do those numbers scale linearly to the proof and verification times listed on dalek-cryptography's bulletproofs page, that has a 64-bit range proof taking 7.3ms and verification taking 1ms? That is, would generating and verifying a ZK-STARK of a 64-bit range proof take microseconds?
The paper in this address provides some more precise evaluations of various ZK proof techniques, including zk-STARKs, zk-SNARKs and Bullet proofs. The have evaluation for a proof of membership for a Merkle tree with different number of leaves.
stackexchange-crypto
{ "answer_score": 0, "question_score": 4, "tags": "zero knowledge proofs" }
What happened to Comodo Defense+? I just updated Comodo to version 7, and there is only the Firewall now. Defense+ seems to have been discontinued as I can no longer find it. What happened to it?
Never mind. They simply renamed it to HIPS for whatever reason.
stackexchange-superuser
{ "answer_score": 0, "question_score": 1, "tags": "firewall, comodo firewall" }
Scala Number type pattern matching I have a field of type Number, can someone tell me why the following code doesn't work and how to elegantly fix it. val n:Number = 10.0 n match { case d:Double=>println(d) } error: pattern type is incompatible with expected type
Scala's `Double` is not the same as `java.lang.Double`, which is a sub-class of `java.lang.Number`, so it can never possibly match. It _can_ if you match against `java.lang.Double` val n: Number = 10.0 n match { case d: java.lang.Double => println(d) case _ => println("Not a Double") } I wouldn't say there is anything elegant about this, though, and it's hard to make any further suggestions without knowing what you want to do with it.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "scala" }
Excel-VBA Set range to add comments of changing each time I use my code to auto add comments for each time edit cell content. I would like to apply the code in range B2:E1000, but my code apply to all cells. So how can I set the range? Thanks in advance. Private Sub Worksheet_Change(ByVal Target As Range) Dim c As Range Dim ws As Worksheet ActiveSheet.Cells.RowHeight = 25 For Each c In Target If c.Comment Is Nothing And c.Value <> "" Then With c.AddComment .Visible = False .Text Application.UserName & "-" & Date & " " & c.Value .Shape.TextFrame.AutoSize = True End With ElseIf Not c.Comment Is Nothing And c.Value <> "" Then c.Comment.Text Application.UserName & "-" & Date & " " & c.Value & vbNewLine & c.Comment.Text End If Next End sub
You can use the Intersect Statement for this: Set isect = Application.Intersect(Range("B2:E1000"), Target) Your code would the look like this: Private Sub Worksheet_Change(ByVal Target As Range) Dim c As Range Dim ws As Worksheet ActiveSheet.Cells.RowHeight = 25 Set isect = Application.Intersect(Range("B2:E1000"), Target) If Not isect Is Nothing Then For Each c In Target If c.Comment Is Nothing And c.Value <> "" Then With c.AddComment .Visible = False .Text Application.UserName & "-" & Date & " " & c.Value .Shape.TextFrame.AutoSize = True End With ElseIf Not c.Comment Is Nothing And c.Value <> "" Then c.Comment.Text Application.UserName & "-" & Date & " " & c.Value & vbNewLine & c.Comment.Text End If Next end if End sub
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "excel, vba" }
Excesivelly long single words forcing html table to stretch I'm going to jump straight to the point with giving you the example fiddle, the problem will make itself clear. Instructions: click on the paragraph in order to change its textual content (via javascript) and then input something a bit longer (like 150+ chars) but as a single word. For example, replace the initial content with a text like `LONGTEXTLONGTEXTLONGTEXTLONGTEXTLONGTEXTLONGTEXT`... etc and you'll see the table stretches in a very strange way, although I've set max width and height for my paragraph and made overflow scrollable. I'd like to know what's causing that and what would be the best way to prevent it. Thanks in advance! <
The paragraph needs one more thing: `word-break: break-all`. <p id="description_changer" class="clickEdit" style="max-width: 100%; max-height: 100px; overflow-y: scroll; word-break: break-all;"> Click to dynamically replace me with a long single word content </p>
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "css, html table" }
What is the best way to add extra data to a jquery ajax post (in addition to a serialized form)? I have the following code: $.post('/Calendar/Add', $("#calendarForm").serialize(), function (data) { }); and i want to add another piece of data in addition to all of the items in the #calendarForm. so lets say i want to append an additional key value pair to the querystring: personId=223 I would rather not add extra hidden inputs into the calendarForm as that is what i am doing now and its kind of messy. Is there any easy way to add an additional piece of data besides all of the value in the calendarForm when i call this post ? I tried something like this: $.post('/Calendar/Add', $("#calendarForm").serialize() + "&personId=223", function (data) { }); but that didn't seem to work?
Try using `serializeArray` var data = $('#myFormName').serializeArray(); data.push({name: 'myParamName', value: 'MyParamValue'}); **Update1:** You can use following code in `$.post`: $.post('/Calendar/Add', data, function (data) {}); For more information have look at this.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jquery, ajax, forms, post" }
Mysql min function on a column and an integer I've got a table which contains a column named size. I want with a min function to find the min value of size and a set of integer. For example : Size can be : 5, 10, 15 And I want to find the min result in a set like : MIN(size,1) Min method does not seem to have several parameters... I've tried something like: SELECT min(1, size) FROM myTable SELECT min(SELECT 1,size FROM myTable) FROM myTable There is error for each of these syntax. I precise that I can't do the comparison in my code because the sql is generated and can be something more complex like: SELECT min(SELECT size FROM table1, SELECT size FROM table2, 10) FROM table3 Any idea ?
You can use `least` to find the minimum across columns/expressions and `min` to find the minimum across rows. SELECT min(least(1, size)) FROM myTable Or this would probably be more efficient actually SELECT least(1,min(size)) FROM myTable
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "mysql, aggregate" }
В PHPMyAdmin запрос обрабатывается, а в PHP нет, почему? $sql = "select place_id, name, address, longitude, latitude from place where latitude !=0 and latitude is not null"; $result = mysql_query($sql) || die (mysql_error()); $cnt = mysql_num_rows ($result); На строчке `$cnt = mysql_num_rows ($result);` выдает ошибку: > `Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in Z:\home\localhost\www\fsq\for_id.php on line 19` В `PhpMyAdmin` запрос выполняла, работает.
Думаю, запрос у вас отлично выполняется. Просто поставьте `or` вместо `||`. У вас в `$result` записывается (судя по предупреждению) значение `true`.
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "phpmyadmin, php, sql" }
cgi-binのサブディレクトリのcgiが動作しない Perl CGI cgi-bin/hello.cgi cgi-bin/folder/hello.cgi Forbidden You don't have permission to access /cgi-bin/0_search/hello.cgi on this server. folder cgi 755 hello.cgi #!/usr/bin/perl print "Content-type: text/html \n\n"; print "Hello"; Apache [vagrant@localhost 0_search]$ httpd -v Server version: Apache/2.4.6 (CentOS) Server built: May 12 2016 10:27:23 [vagrant@localhost 0_search]$ CentOS7
SELinux productionSELinux cgi-bin/var/www/cgi-bin # ls -Z /var/www/cgi-bin/folder/ httpd_sys_script_exec_t # chcon system_u:object_r:httpd_sys_script_exec_t /var/www/cgi-bin -R # semanage fcontext -a -t httpd_sys_script_exec_t "/var/www/cgi-bin(/.*)?" cgi-bin httpd_sys_script_exec_t SELinux SELinuxcgi()() ↓ < > httpd_unconfined_script_exec_t > SELinux httpd SELinux SELinux
stackexchange-ja_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "apache, perl" }
Mimicing browser behavior I am fetching htmldump of a web page. But I am not getting content which is loaded by Javascript at run time. What is the best way to mimic browser's behavior and extract the htmldump which is exactly what we see on the browser. We are using Java and people have used selenium earlier but it seems to have speed issue.
You could try HtmlUnit. It's a headless browser with javascript support, so it should be able to do what you want.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, html, selenium, browser, dom events" }
Preferred kind of array for storing iPhone favorite items? I am using the following array to add an object that was previously created to the favorite array: `NSMutableArray *favorites = [NSMutableArray addObject:[myList objectAtIndex:1]];` However, this code keeps crashing at runtime. I think this is not the best way to implement an array that can save and delete items; is there a better way to implement this? Is there a way to automate this process without having to add an array for every cell selected from the table?
Just write (assuming favorites array have already been created): [favorites addObject:[myList objectAtIndex:1]]; To create new array you should use for example `+arrayWithObject:` NSMutableArray *favorites = [NSMutableArray arrayWithObject:[myList objectAtIndex:1]];
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "iphone, arrays" }
Can I write a test without any assert in it? I'd like to know if it is "ok" to write a test without any "assert" in it. So the test would fail only when an exception / error has occured. Eg: like a test which has a simple select query, to ensure that the database configuration is right. So when I change some db-configuration, I re-run this test and check if the configuration is right. ? Thanks!
It is perfectly valid to make sure a unit test runs without encountering an exception. As per Matt B's suggestion, be sure to document what the test is actually testing to be clear and precise.
stackexchange-stackoverflow
{ "answer_score": 20, "question_score": 17, "tags": "java, unit testing, junit, assert" }
Can I limit connections per second for certain UserAgents using UFW? GoogleBot is hitting my server hard - and even though I have set the CrawlRate in Webmaster Tools it is still hiking up the load on my server and slowing down Apache for the rest of the normal web traffic. Is it possible to limit / rate-limit connections per second / minute using UFW based on a user agent string? If not how can I do it for GoogleBot's IP ranges?
You cannot do this with ufw directly, but you need to add the right iptables rules to `/etc/ufw/before.rules`. I suggest you to learn iptables. As a (not optimized) starting point something like -A ufw-before-input -p tcp --syn -dport 80 -m recent --name LIMIT_BOTS --update --seconds 60 --hitcount 4 --rcheck -j DROP -A ufw-before-input -p tcp -dport 80 -m string --algo bm --string "NotWantedUserAgent" -m recent --name LIMIT_BOTS --set ACCEPT could work, where you of course need to replace `NotWantedUserAgent` with the correct one. This rules should limit the number of new connections per minute from a specific bot - I have not tested them and do not know if they really reduce the workload from a specific bot.
stackexchange-unix
{ "answer_score": 4, "question_score": 3, "tags": "ubuntu, firewall, limit, ufw" }
want to assign roles specific to email address with regex or any other solution for it [email protected] (for student) [email protected] (for teacher) I want to assign roles as a student if it includes year otherwise teacher during user registration. what would be the regex expression for this or any other optimal solution ?
Try the following regex const str1 = "[email protected]"; const str2 = "[email protected]"; const regex = /[0-9]{4}/; console.log('str1 has year -- ', regex.test(str1)); console.log('str2 has year -- ', regex.test(str2));
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "javascript, reactjs, regex, email, logic" }
"Find in page" vs "find on page" I'd like to find some thoughts and opinions related to this question. First of all, I noticed that there are two forms used in Web browsers' menus: MS Internet Explorer uses "Find on page" meanwhile Chrome uses "Find in page". What is the difference between these forms and why can they both be used? Normally, I'd say "find in the page" meaning "find in this text".
What constitutes "on" vs. what constitutes "in" is contextual and regional. Bostonians wait "on line", while Chicagoans wait "in line". George Carlin had a whole bit about "getting on the plane". "Fuck you, I am getting _in_ the plane! Let the daredevils get _on_." My intuition is that most native speakers would say "on" the page rather than "in", because a page is more like a platform than a container (whereas they would always "in the book").
stackexchange-english
{ "answer_score": 2, "question_score": 2, "tags": "grammar, verbs, prepositions, formality, internet" }
Kohana 3 validation for website address I am trying to figure out, how can I validate input field for website address. I have field where users needs to put youtube video address for example < . I need to check provided web address against this bit of address < , that it is identical. Is it possible to do with Validation rule regex ? If yes, what I need to write in regex array ? protected $_rules = array( 'video' => array( 'not_empty' => NULL, 'regex' => array(''), 'exact_length' =>array(42) ), );
Try this regex, it should work $pattern = '/^http:\/\/www.youtube.com\/watch\?v=(.+)$/';
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "kohana" }
Update User Role I'm developing an plugin that adds an new user role (client role, for instance). This role only extends the admin role for now. add_role( 'client', __('Client'), get_role('administrator')->capabilities ); Now i wan't to release an new version of the plugin that update the client capabilities and remove the `install_plugins` capability. Roles are persistent, so i can't just update my `add_role`. **My question is:** how can i manage an custom role, updating it's capabilities?
Off the top of my head, you should be able to do something like this: $role = get_role( 'client' ); if ( $role && $role->has_cap( 'install_plugins' ) ) { // Role not updated yet, so update it. $role->remove_cap( 'install_plugins' ); } `get_role()` returns a `WP_Role` object on success and `WP_Role::remove_cap()` calls `WP_Roles::remove_cap()`, which directly updates the option in the database. The `$role->has_cap()` check ensures that the code isn't run twice. Running this in a function hooked to `init` should suffice. Ideally you'd have a database version option for your plugin which you could use to run some code exactly once per plugin update. Otherwise your code is executed again every time someone manually adds the `install_plugins` capability to your role again. That's not necessarily bad, but it could be prevented :-) Code reference: * `get_role()`. * `WP_Role` * `WP_Roles`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, user roles, capabilities" }
Very nonstandard question: Is there any way to widen a tire by combining it with some other tire (cut and re-glue)? Brace yourself - this is not normal. I have an old 22" rim (37-501, 22x1-3/8) and all I can get is skinny tires for it. But I'm an idiot and I really want a wider tire on that rim. I want it so bad I am grasping at straws for ideas. So here's the thought: Get a new tire (22x1-3/8) Get a new BMX 22" tire (which is NOT gonna fit my rim) Cut the skinny one's beads off with about 1" of rubber above it. Cut the bead off the BMX tire very low. Glue BMX tread to old-school beads. Viola! a 2" wide tire for the old 22" rim. Yeah, I know this is nuts. But CAN it be done and become whole again? Maybe, just maybe, someone here knows if this has ever been done. Please let me know.
I don't think what what you are proposing to construct would not be anywhere near strong enough to function properly as a tire. Tires are not just molded rubber. They are contain a _casing_ of continuous fibers that enables then to withstand inflation pressures and lateral forces caused by cornering. < By gluing parts of two tires together you would not have a continuous casing running through the tire.
stackexchange-bicycles
{ "answer_score": 8, "question_score": 3, "tags": "tire, customization" }
Schedule notification using flutter_local_notifications I'm using `flutter_local_notifications` plug-in to send notifications to my users. But I need to schedule the notifications. So I use `zonedSchedule()` to do that. The problem is that `zonedSchedule()` requires TZDateTime, so I need to convert DateTime to TZDateTime. I saw this question, but it didn't work for me. I just need to get the `Location` of the user and pass to `TZDateTime.from(dateTime,location)`. How can I get this location? Thanks in advance.
I've just asked this question but I have the answer already. For those having trouble with the `Location`, you can just use `tz.getLocation(await FlutterNativeTimezone.getLocalTimezone())` to get the `location` parameter for `TZDateTime.from(dateTime,location)`. PS.: Remember to import: `import 'package:timezone/data/latest.dart' as tz;` and `import 'package:timezone/timezone.dart' as tz;`. Also, you have to inicialize `tz`: tz.initializeTimeZones(); tz.setLocalLocation(tz.getLocation(await FlutterNativeTimezone.getLocalTimezone())); That's it, I hope it's useful.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "flutter, dart, push notification, dart pub" }
Creating MultiSig from server I want to create a MultiSig address where user A sends the public key of its bitcoin address (gets saved in the database). User B gets notified that he must send his public key to create the 2-3 MultiSig address. The third address is provided by me as a mediator. My concern is that if the server is hacked, the hacker can change my source code (PHP) so that 2 of 3 public keys are in his possession. Any ideas on how I can secure this 2-3 MultiSig address creation scenario?
I think your worry is that the hacker will change the public key in the database to be the public key for one of their addresses, and get access to the private key that you own, which means they will have the ability to make 2/3 signatures, which is all that they need. This will only be a risk if you can't detect it and alert those who are funding the addresses to stop. As Matthieu said, the signatures on the old multisig address won't be valid anymore. If your service is queried for an address to send coins to, however, and it returns the new maliciously created address, then your users might be funding an address which can be spent by the hacker. So, I think your best bet would be to make sure that you can put your service into safe-mode if someone has hacked in.
stackexchange-bitcoin
{ "answer_score": 1, "question_score": 0, "tags": "multi signature" }
Scheduling boot using cron (Ubuntu Server 20.04) I wonder if it is possible to schedule a machine to boot up at a determined time using cron. Imagine I want my server to shut down at night and boot back up in the morning. I've rad many docs and questions but not a word on this, maybe there's another way of scheduling a boot?
1. Booting at a specific time is sometimes a BIOS option. Your Ubuntu OS has no way to read or change such BIOS options, if they exist on your system at all. 2. You can suspend (instead of poweroff) your system using cron. * How to suspend (including wakeup) using cron. * Some systems can indeed be started from poweroff using Wake-on-LAN. It's a BIOS feature, not all systems have it. 3. If you system is suspended instead of powered off, you can use a Wake On LAN (WOL) packet from another machine on your LAN to awaken the suspended machine. The suspended system must accept WOL packets. Obviously, the cron job must reside on the _sending_ system, since the receiver is suspended. * How to enable WOL * How to use other packets to wake the system
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 0, "tags": "boot, 20.04, cron, anacron" }
How to QMap()::begin() + int offset I have function in my filemodel which returns actual file name in specific position. ... QMap<QString, QFileInfo> fileInfoMap_; ... QString MFileModel::fileAt(int offset) const { return (fileInfoMap_.begin() + offset).key(); } ... Problem is, that this feature stop working in QT6. How can i repair it? I looking for documentation, without success. QMap.begin() returns QMap::const_iterator. There is no option to use "\+ int". Build retur error: ...mfilemodel.cpp:276: error: invalid operands to binary expression ('QMap<QString, QFileInfo>::const_iterator' and 'int')
This solved my problem. Maybe siple way exists. But this works too. QString MFileModel::fileAt(int offset) const { QMap<QString, QFileInfo>::const_iterator ci = fileInfoMap_.begin(); for (int i=0; i<offset; i++) { ci = ci.operator++(); } //return (fileInfoMap_.begin() + offset).key(); return ci.key(); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "qt6, qmap" }
How can I access Phalcon configuration data in an external library? Within my project, I've created a "core" directory which contains certain classes and methods called throughout the controllers. I've defined a configuration parameters in my bootstrap file like so: private function loadConfig () { // Bootstrap $configFile = __DIR__ . '/../config/config.json'; // Create the new object $config = json_decode ( file_get_contents ( $configFile ) ); // Store it in the Di container $this->di->setShared ( 'config', $config ); } I want to be able to access these configuration values in my "core" classes. What do I do?
There are several ways to get a reference to the service you registered with the Dependency Injector. However, to make sure you are getting the same instance of the service and not a newly generated one, then you need to use the getShared method: $this->getDI()->getShared('config'); Doing so ensures you are getting the highest performance possible, and minimizing memory footprint.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "php, phalcon" }
getting a subset of data to qplot I'm grabbing a rather large amount of data from MySQL database. It's around 150mb. !enter image description here I am then graphing some of the fields: > qplot(myValues$average_submitted_chrg_amt, myValues$average_Medicare_payment_amt, data=myValues, color=nppes_provider_country,xlim=c(0,10000),ylim=c(0,4000),alpha=0.01) Just to be cool I am including the graph: !enter image description here I'd like to regraph this taking a random sampling of rows from the SQL QUERY. **Is there a way to graph a subset of myValues?**
You can use `sample` to get what rows to include in your subset and use `[` to subset/extract these rows from your data. This will sample 5 numbers from 1 to 10 without replacement sample(10, 5) #[1] 5 7 8 3 10 If we sample again, we will likely get a different sample sample(10, 5) #[1] 10 2 6 1 9 To make the sampling reproducible we can set a seed (see `?set.seed`) set.seed(1) ; sample(10, 5) # [1] 3 4 5 7 2 set.seed(1) ; sample(10, 5) # [1] 3 4 5 7 2 Your plot - use example `mtcars` dataset. You use `sample` to sample the rows library(ggplot2) data(mtcars) set.seed(1) qplot(mpg, wt, data=mtcars[sample(nrow(mtcars), 20), ], geom="point") `mtcars[sample(nrow(mtcars), 20), ]` samples twenty rows from the dataset
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, sql, r, graph" }
Change sizes of buttons in UIImagePickerController I'm using a UIImagePickerController in my app to take video. My question is pretty straightforward: how can I make the buttons in the view larger, specifically the "use" button that appears after the video is done taking?
You need to add a custom overlay to your UIImagePickerController. Then use custom buttons instead of the original ones. Like so: UIImagePickerController *picker = [[UIImagePickerController alloc]init]; picker.delegate = self; //hide old buttons picker.showsCameraControls = NO; UIView *overlay = [[UIView alloc] init]; UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom]; newButton.frame = CGRectMake(20,40,70,40); [overlay addSubview:newButton]; picker.cameraOverlayView = overlay; You then add your new buttons to the overlay uiview. As for the new buttons actions, you would need to look at the apple docs to see the methods for the original buttons. (like for taking a photo you would use - [picker takePicture];) Hope this helps!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "ios, uiimagepickercontroller" }
What's it called when you switch the order of two words around? What's it called when you switch the order of two words around, completely changing their meaning? For example, _simply childish_ becomes _childishly simple_. Or _wonderfully sarcastic_ becomes _sarcastically wonderful_.
Antimetabole: > is the repetition of words in successive clauses, but in transposed grammatical order (e.g., "I know what I like, and I like what I know")
stackexchange-english
{ "answer_score": 7, "question_score": 1, "tags": "single word requests, word order" }
Background Color, ForegroundColor I'm Junior programmer I Wrote this Code in Console application static void Main(string[] args) { Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine("backgroundcolor is red"); Console.ForegroundColor = ConsoleColor.Green; Console.Write("ForegroundColor is Green"); Console.ReadKey(); } But I want to Write one console write line. So background color is red just with background color in console and Foreground Color is Green write in console application just with Foreground Color at a same time that each sentence effected with its class in one line.
What about this... static void Main(string[] args) { var originalColor = Console.BackgroundColor; Console.BackgroundColor = ConsoleColor.Red; Console.Write("The background color is red. "); Console.BackgroundColor = originalColor; Console.ForegroundColor = ConsoleColor.Green; Console.Write("The foreground color is green"); Console.ReadKey(); }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -1, "tags": "c#, console, background foreground" }
Move data from Splunk to Elastic Search I have a script in splunk which runs in regular intervals and puts data in the Splunk. Now i want to transfer this data to Elastic Search also. So the data gets input in both splunk and Elastic Search. Any ideas on how to do it?
Using Spring Data Elasticsearch in Java, and Spring Batch with Quartz Scheduler, you could set up a batch job that reads in data from the Splunk REST API, and writes the data into an Elasticsearch index.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "database, elasticsearch, transfer, splunk" }
Run Selection in VS code or ADS without cursor moving to the terminal afterwards I would like that the cursor stays in the script file after I run a code selection with F8. What setting should I change so the cursor does not move to the terminal?
Assuming that the PowerShell extension for Visual Studio Code or Azure Data Studio (ADS) is installed, add the following line to your `settings.json` file (before the closing `}`): "powershell.integratedConsole.focusConsoleOnExecute": false, Alternatively, use the settings GUI (press `Ctrl+,`): ![Settings GUI with relevant setting shown]( Note the GUI's convenient search feature: typing `powershell focus` was sufficient to locate the relevant setting.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "powershell, visual studio code" }
Diablo 3 - Magic Find In Groups > **Possible Duplicate:** > How does X% Chance of Finding Magical Items work for a party? So I'm running Izual on Normal with a friend, who's having trouble getting the Staff of Herding recipe from him. My question is, how does magic find work since each player in a group will get a different set of items when Izual dies? Since my friend needs the plans, should he be the one striking the killing blow? Or can I?
When played cooperatively items drop separately for each player. This means each player sees their own loot and not loot that has dropped for the other people in the group. When picked up and dropped on the ground or traded the items obviously become visible to the other players as well. **When playing in a group, the total Magic Find of the group will be divided equally amongst each player**. Here is an example given by Blizzard: > The group consists of four players. In total, their stats are 50% MF, +20% GF and 10% XP, each of these players will have a 12.5% ​​MF, 5% GF and 2.5% XP being in such a group. Who deals the killing blow doesn't matter.
stackexchange-gaming
{ "answer_score": 1, "question_score": -1, "tags": "diablo 3" }
Seo url doens't work with homepage in OpenCart 3 I've enabled the option (Use SEO URLs) in settings (Opencart 3). All links such as contact, about, etc are working, except the homepage! I have added this to the SEO URL page: * **Query:** common/home * **Keyword:** home But it still appears as: `index.php?route=common/home` How can I fix that?
I hope it will help you as Please make changes in catalog/controller/startup/seo_url.php if `(($data['route'] == 'product/product' && $key == 'product_id') || (($data['route'] == 'product/manufacturer/info' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id')) { to if (($data['route'] == 'product/product' && $key == 'product_id') || (($data['route'] == 'product/manufacturer/info' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id') || $data['route'] == 'common/home') {
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "seo, opencart, opencart 3" }
Best way to test & experiment with nginx, apache? What's the best way to experiment with local installations of web servers, like nginx and apache, in such a way that it's easy to discard and start a new instance of either? I'm new to both of these server technologies, and I'm doing a lot of tweaking to familiarize myself with each. As a consequence, I frequently mess up my rigs and find myself having to retrace my steps, or worse, uproot and re-install the darn things entirely. What's the best "sandbox"-type solution for this? virtual machines? local VPSs? a liveUSB image that I can easily overwrite and start over? Thanks!
Just use (a) separate config-file(s). In case of apache2 on linux, copy /etc/apache2/ to /etc/apache2b/, in /etc/apache2b/sites-available/default change <VirtualHost *:80> to something like <VirtualHost *:88> and start the 2nd apache with apache2 -f /etc/apache2b/apache2.conf
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "apache, nginx, virtual machine, vps, sandbox" }
How to turn of hibernate-validator DEBUG logger I add hibernate-validator(6.0.9.Final) to my spring (not spring boot) maven project and work perfectly, but cause lot of(~3000 row) DEBUG log. How to off this log? I tried these, but didn't work: logging.level.org.hibernate=info log4j.logger.org.hibernate=info
The log level of Hibernate Validator is (obviously) not DEBUG by default so you must have something in your application classpath setting the log level to DEBUG. Hibernate Validator is using JBoss Logging which uses log4j under the hood so `log4j.logger.org.hibernate.validator=info` in your log4j.properties should work. But considering it shouldn't have been set to DEBUG in the first place, I'm wondering if you have something in your classpath overriding your log configuration. I suspect either you or a dependency have enabled DEBUG logging for org.hibernate to see the queries or something similar and this is this setting you should find and remove.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "spring, hibernate, maven, logging, hibernate validator" }
When does the unit group of $\Bbb Z_n$ have prime order? There are cases when the multiplicative group $\mathbb{Z}_n^*$ is a cyclic group. But my question is, for what $n$ does $\mathbb{Z}_n^*$ have prime order? Or equivalently, for what $n$ is the Euler totient function of $n$ equal to a prime number?
$\phi(2^k)=2^{k-1}$ is even for $k>1$, $\phi(p^k)=(p-1)p^{k-1}$ is even for odd prime $p$ and $k\ge1$, and $\phi$ is multiplicative, so $\phi(n)$ is even for $n>2$. Therefore, $\phi(n)$ is $2$ or a multiple of $2$ (not prime) for $n>2$. $\phi(n)=2$ only for $n=3, 4$ or $6$.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "abstract algebra, number theory, modular arithmetic, totient function" }
How to use a character map in XSLT? I have this XSLT stylesheet: <xsl:stylesheet version="3.0" xmlns:xsl=" <xsl:character-map name="cm"> <xsl:output-character character="1" string="abc"/> <xsl:output-character character="2" string="def"/> <xsl:output-character character="3" string='ghi'/> </xsl:character-map> <xsl:template match="/"> 123abc <abc att="123abc"/> <xsl:value-of select="'123abc'"/> </xsl:template> </xsl:stylesheet> No matter how I tried, the character map did not seem to work. Could someone show me how to make it work? Did I miss something?
You have defined a character map, but you are not _using_ it. Try: <xsl:stylesheet version="3.0" xmlns:xsl=" <xsl:character-map name="cm"> <xsl:output-character character="1" string="abc"/> <xsl:output-character character="2" string="def"/> <xsl:output-character character="3" string='ghi'/> </xsl:character-map> <xsl:output use-character-maps="cm" /> <xsl:template match="/"> 123abc <abc att="123abc"/> <xsl:value-of select="'123abc'"/> </xsl:template> </xsl:stylesheet>
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "xml, xslt" }
Primordial flunctuation gave rise to cosmic structures? I'm not a physicist, not even a physics student. I'm just reading Lawrence Krauss's book _A Universe From Nothing_ and I got stuck understanding a concept. In his book, Lawrence says: > Quantum fluctuations, which otherwise would have been completely invisible, get frozen by inflation and emerge afterward as density fluctuations that produce everything we can see. I'm a bit confused here, didn't big bang already created all the raw materials needed to produce "everything we can see"? How can quantum fluctuation after inflation affect stars/galaxies/clusters formation?
I did not read this book, so I'm guessing. The fluctuations did not create any raw material for what we see. The material was there already. The fluctuations were just regions where the material was denser, so it started to gravitationally colapse to form clusters of galaxies. In this sense the fluctuations affected the galaxy formation. The inflation just increased these fluctuations to macroscopic size.
stackexchange-physics
{ "answer_score": 1, "question_score": 2, "tags": "big bang, cosmological inflation" }
How to redirect all the results from multiple findstr commands to same file using batchfile Hi I am using findstr command to filter a file based on string and redirecting that output to seperate file. findstr /C:"C=EODRevaluationProcess Temp table:TMP_EOD_REVAL_DATA" "C:\Users\Desktop\abc.txt" > C:\Users\Desktop\xyz.txt pause findstr /C:"sendSPPJMSMessage><Finished publishing [0] messages" "C:\Users\Desktop\abc.txt" > "C:\Users\Desktop\xyz.txt" pause findstr /C:"POS_HOURLY_DATA : actualTable : POS_HOURLY_DATA_" "C:\Users\Desktop\abc.txt" > "C:\Users\Desktop\xyz.txt" I want all the filtered lines to be saved in same file xyz. But only output of first findstr command is saving in xyz. Can anyone please suggest any idea Thank you.
You are redirecting the output to a file using the `>` operator which will create the file if it doesn't exist and replace its contents with the output. If you want to append to the file, rather than replacing its contents, you can use the `>>` operator.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "batch file" }
Set a background color conditionally in Flash Builder 4.6 I am trying to set the background color of a mx:TabNavigator with the following line of code... backgroundColor="{isDistrictFair == 'false'?'#EFF7F9':'#E9E3D2'}" I am getting the following error... > 1067: Implicit coercion of a value of type String to an unrelated type uint. Not sure which value the error refers to. isDistrictFair is a string var that contains either "true" or "false". I got the 2 color values I wanted by setting the TabNavigator background while in Design mode which creates the following line of codes... backgroundColor="#EFF7F9" and.. backgroundColor="#E9E3D2" So I thought I could get the background colors set conditionally, but can't figure out the proper syntax. Thanks, John
Pretty simple - rather than using the string hash notation for the color, use the 0x prefix for an integer: backgroundColor="{isDistricitFair == 'false' ? 0xEFF7F9 : 0xE9E3D2}"
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "flash builder, background color" }
li clickable but with rel - jquery I'm using jQuery prettyPhoto to display an overlay window. On my page I have an li with a link and image, I want the whole li to be clickable BUT the link is #, so it's rel doing the work. <a href="#inline-'.$i.'" rel="prettyPhoto[inline]">'.preg_replace($patterns,$replacements,$vimeo->title).'</a> Below is my jQuery, any ideas? $(function() { $('.clickable').css('cursor', 'pointer').click(function() { window.location = $(this).find("a").attr("href") + $(this).find("a").attr("rel"); return false; }); });
I recommend against trying to make the `<li>` clickable. If you can't wrap some element (like an `<li>` or a `<td>`) in an anchor, you can make the anchor fill the whole area of the element with CSS: example on jsFiddle. (You can probably find less rough ways to do that on ALA or such.) Then just intercept the click event on the link. Also, as Quentin said, don't repurpose `rel` or other attributes; you can use data attributes as a "clean" alternative.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "javascript, jquery" }
Print an integer tensor in binary I have a tensor of type `tf.int32` I would like to use `tf.Print` but I need the result to be in binary. Is this even possible? It is for debugging. Example: constant = tf.constant(5) #magic tf.Print(constant) # prints 101
You can use `tf.py_function`: x = tf.placeholder(tf.int32) bin_op = tf.py_function(lambda dec: bin(int(dec))[2:], [x], tf.string) bin_op.eval(feed_dict={x: 5}) # '101' But note that `tf.py_function` creates a node in the graph. So if you want to print many tensors, you _can_ wrap them with `tf.py_function` before `tf.Print`, but doing this in a loop may cause bloating.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "python, tensorflow, binary, type conversion, integer" }
get_posts() and filters I've added a custom filter function for `the_posts` filter in a plugin. add_filter('the_posts', 'posts_filter'); function posts_filter() { … } This works pretty well in the main loop, that means the posts are filtered in the way I defined in the `posts_filter` function. But I am calling `get_posts()` within an ajax request to get some posts. And there the filters aren't working. `query_posts()` or custom `wp_query` don't work too. So the question is: How can I get posts beside the main loop which are filtered by `the_posts` filter?
`the_posts` does work for all queries including the main query as well as custom queries but doesn't work when using `get_posts()`. This is because `get_posts()` automatically suppresses all the filters. If you want to use the filters even when using `get_posts`, you can pass an extra key `'suppress_filters' => false` in the array you pass as argument to `get_posts()`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "filters" }