INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Extract integers from std::string I'm writing simple OBJ loader and I encountered next problem - I have to extract integers from next `std::string`: f v0/vt0/vn0 v1/vt1/vn0 ... vk/vtk/vnk where `vk`, `vtk`, `vnk` are int values and there is no space between `/` and the values and only one space between groups. As the files can be quite large and this type of lines may appear more than 100000 times I need an efficient way to extract the integers from strings like this one. EDIT: As Jesse asked this is my current approach(I assume data is in the right format!): int p, t, n; const char* l = line.c_str() + 2; for (int vIndex = 0; l && sscanf(l, "%d/%d/%d", &p, &t, &n) == 3; ++vIndex) { //do something with vertex l = strchr(l, ' '); if (l) { l += 1; } }
Use `std::strtol`, this is quite neat in that it will return the end of the current parse, and you can continue from there. So let's say that you guarantee that you read three digits each time, something like the following sketch could work.. char *p = line.c_str() + 1; while (p) { long v0 = std::strtol(++p, &p, 0); // at the end, p points to '/' long v1 = std::strtol(++p, &p, 0); // at the end, p points to '/' long v2 = std::strtol(++p, &p, 0); // at the end, p points to ' ' // On the last one, p will be null... }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "c++, c++11" }
Java - get variable name from double array I have a Java array of type double with variable names used to store values as so: double [] countArray = {teaCount, hotMealCount, drinkWaterCount, phoneCallCount}; I am looking to print the names of the variables out by it's index. e.g. If I request `countArray[0]` it would return `teaCount` instead of the double that's stored.
If you want the names you need to store these String[] countArray = {"teaCount", "hotMealCount", "drinkWaterCount", "phoneCallCount"}; Though most likely you wanted a `Map<String, Double>` such as Map<String, Double> map = new LinkedHashMap<>(); map.put("teaCount", teaCount); map.put("hotMealCount", hotMealCount); map.put("drinkWaterCount", drinkWaterCount); map.put("phoneCallCount", phoneCallCount); This stores both the name and the value it has.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -1, "tags": "java, arrays" }
Remove “/ent/” subfolder with mod_rewrite Hello I used to publish my website from a subfolder but it's now moved to root. The problem is that I have a lot of links with the subfolder "/ent/" included in the url. Some urls also have index.php included, if someone could help to get rid of that to it would be great!. Example: ` Example: ` Thanks
Enable `mod_rewrite` and `.htaccess` through `httpd.conf` and then put this code in your `DOCUMENT_ROOT/.htaccess` file: Options +FollowSymLinks -MultiViews # Turn mod_rewrite on RewriteEngine On RewriteBase / RewriteRule ^ent/(.*)$ /$1 [L,NC,R=301]
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "regex, apache, .htaccess, mod rewrite" }
Check if path matches dynamic route string Suppose I have this pathnames: const pathnames = ['/test', '/test/40', '/hello/2/testing/4']; and then I have this array: const routes = [ { name: 'Test', path: '/test' }, { name: 'Test Edit', path: '/test/:id' }, { name: 'Hello', path: '/hello/:id/testing/:id2' }, ]; I need a function that I pass a string (which is the current path) and returns, after searching the array, the correct object. I thought of simply using a `.find()` but I can't match directly since some routes might be dynamic. Also, I can't use a `.includes()` either, for the same reason. I'm using React Router DOM so maybe there's an integrated way of doing it?
You could build a regular expression and replace parts with `:`. const pathnames = ['/test', '/test/40', '/hello/2/testing/4'], routes = [{ name: 'Test', path: '/test' }, { name: 'Test Edit', path: '/test/:id' }, { name: 'Hello', path: '/hello/:id/testing/:id2' }], escapeDots = s => Array.from(s, c => c === '.' ? '\\.' : c).join(''), result = pathnames.map(path => routes.find(o => new RegExp(`^${o.path .split('/') .map(s => s.startsWith(':') ? '[^\/]+': escapeDots(s)) .join('\/') }$`).test(path))); console.log(result);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript" }
Revert to the page's original CSS with jQuery I have a page with a 'printer friendly' button that uses jQuery's .css() method to remove some backgrounds and border from specific elements, and change the font size. I can set another .css() method to change everything back to the way it was, but is there any easy way to revert everything on the page to its original CSS (aside from refreshing the page)?
You should define your print friendly styles as selector rules in your main css file body.printfriendly .selector .rule { font-size:bigger; } And then you can add and remove the `printfriendly` class on the body tag to show or hide the rules. You can also use the `@media print` section to declare rules that only get applied when the user prints. @media print { .selector .rule { font-size:bigger; } }
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "jquery, css" }
How can I assign a value to x according to y I have this code that is very annoying to write but does the job, I was wondering if there was a function or class of some sort to help me. Here's my function: func add_health(): if wave in range(10,20): enemy_health = 2 elif wave in range(20,30): enemy_health = 3.5 elif wave in range(30,40): enemy_health = 5 elif wave in range(40,50): enemy_health = 6.5 elif wave in range(50,59): enemy_health = 8 elif wave in range(60,69): enemy_health = 9.5 else: enemy_health = 1
If your `wave` variable is an integer, this is simple1. If it is not, you should be able to cast it to an int for the same effect. Making it an input to the function makes this simple (since you can force the conversion). It looks like you increase the `enemy_health` value 1.5 per 10 wave (at least until 70, where you revert to 1). So simply divide `wave` by 10 and then multiple by 1.5, and add it to an offset. You may need some special handling for base cases (`wave` <10 or >=70). Without considering those edge cases, your function becomes func add_health(current_wave: int): # Parentheses probably unnecessary, but useful for clarity enemy_health = ((current_wave/10) * 1.5) + 0.5 1 Dividing two integers results in an integer, discarding any remainder. So 53/10 == 5
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "godot, gdscript" }
Appending to list in cells in newer versions of pandas This code works in `pandas` version 0.23.4 but throws an error in version 0.25.1 and newer. import numpy as np import pandas as pd df = pd.DataFrame({'a':[1,2,3], 'b': [[0,1], [5], [10]]}) df a b 0 1 [0, 1] 1 2 [5] 2 3 [10] # both lines below throw an error in newer versions df['b'] += [42] df.loc[df['a']==3, 'b'] += [73] df # desired output that works in 0.23.4 a b 0 1 [0, 1, 42] 1 2 [5, 42] 2 3 [10, 42, 73] How does append to list in cells work in later versions on pandas ?
Try df['b'].apply(lambda x: x.append(42)) df.loc[df['a']==3, 'b'].apply(lambda x: x.append(73)) (tested on pandas version 1.0.5)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, pandas" }
Ideals in quadratic integers I am studying for an algebra exam and have stumbled upon these two questions: 1. Show that $(2, \varepsilon)$ is not a principal ideal in $\mathbb{Z}[\sqrt{0}]$ 2. Show that $(2, \varepsilon)$ is a principal ideal in $\mathbb{Z}[\sqrt{-1}]$ $\varepsilon$ is not specified, but I suppose $\varepsilon = \sqrt{0}$ and $\varepsilon = \sqrt{-1}$ respectively. Here are my thoughts: 1. Isn’t $\mathbb{Z}[\sqrt{0}] = \mathbb{Z}$ and hence a PID? 2. I know that $\mathbb{Z}[\sqrt{-1}] = \mathbb{Z}[i]$ and that the Gaussian integers are a PID. How could I prove the statement without this fact? **Edit:** I have found this definition in the lecture notes: Let $A$ be a (commutative) ring, $d \in A$, and $\varepsilon$ a “square root” of $d$ that we add to $A$, then $A[\sqrt{d}] = \\{a + b\varepsilon, a, b \in A\\}$. ~~That’s why I think $\mathbb{Z}[\sqrt{0}] = \\{a + b\sqrt{0}, a, b \in \mathbb{Z}\\} = \mathbb{Z}$.~~
After sorting out the notational difficulties with Daniel Fisher, I am now able to answer my own question: 1. $\mathbb{Z}[\sqrt{0}]$: If $(2, \varepsilon)$ was a principal ideal, it would be $(\operatorname{GCD}(2, \varepsilon))$ with $\operatorname{GCD}(2, \varepsilon)$ being a non-unit. However, 2 and $\varepsilon$ are relatively prime in $\mathbb{Z}[\sqrt{0}]$ and hence $(2, \varepsilon)$ cannot be principal. 2. $\mathbb{Z}[\sqrt{-1}]$ = $\mathbb{Z}[i]$: Here, $(2, \varepsilon) = (2, i)$. $i$ is a unit in the Gaussian integers and hence $(2, i) = (1) = \mathbb{Z}[i]$ and a principal ideal.
stackexchange-math
{ "answer_score": 0, "question_score": 2, "tags": "abstract algebra, ideals" }
WiredTiger, GridFS and Mongodb uploading file and max file size Three questions about WiredTiger storage and MongoDB. 1. I need to store (binary) files in the DB that may exceed 16MB size, now I read on WiredTiger site that the maximum file size is 512MB, but on Mongodb insert method it says that the maximum size of all of the documents should be 16MB, so will I be able to store files that are larger then 16MB while using WiredTiger? 2. I need to use a complete file and not parts of it (like streaming parts of a video), is it possible to do with GridFS? 3. How can I insert and find files in the DB? I can't find a guide on how to do it with WiredTiger... Do I have to do it from the mongoshell or mongofiles? Is there a way to do it programmatically with node.js?
1) GridFS should be used for files larger than 16 MB: _GridFS is a specification for storing and retrieving files that exceed the BSON-document size limit of 16 MB._ EDIT: Check this answer for GridFS limits. 2) On insert query _GridFS divides a file into chunks_. _When you query GridFS for a file, the driver will reassemble the chunks as needed._ 3) Querying GridFS using WiredTiger or other engine (MMAPv1) is transparent for the user. Files can be queried using the driver methods, info here.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "node.js, mongodb, gridfs, wiredtiger" }
VBA: Optimal way to select Top Left cell of selection Trying to find the best way to select the top left cell from a selection. The current code looks too bulky to be the optimal way: Sub CAIShowHandle() Dim TopLeftColumn As String Dim TopLeftRow As String 'changing to only top left cell With Selection TopLeftRow = .Row TopLeftColumn = Col_Letter(.Column) End With Range(TopLeftColumn & TopLeftRow).Select End Sub Function Col_Letter(lngCol As Long) As String Dim vArr vArr = Split(Cells(1, lngCol).Address(True, False), "$") Col_Letter = vArr(0) End Function Is there a better way to write this?
All you need to do when you have a selection: Selection(1).Select However, be carefull using `.Select` as it can mostly be avoided. See this post on StackOverflow for more clarification on that subject.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "excel, vba" }
Задача по sql, как найти поставщиков и детали? Подскажите, как решить данную задачу? что-то не получается < Есть 4 таблицы: поставщиков, деталей, проектов и поставки(поставщик,деталь,проект,количество) Найти все пары "номер поставщика—номер детали", причем только такие, в которых данный поставщик не поставляет данную деталь. **P.S.** таблицы: поставщиков(s), деталей(p), проектов(j) и поставки(spj)
Для решения данной задачи необходимо воспользоваться оператором `EXISTS`, который принимает значение `TRUE`, если подзапрос содержит любое количество строк, иначе его значение равно `FALSE`. Для `NOT EXISTS` все наоборот. select * from s, p where not exists (select null from spj where spj.s = s.s and spj.p = p.p) Внутри подзапроса `EXISTS` можно не выбирать никаких столбцов. В _Oracle_ , например, это позволяет сократить время выполнения запроса.
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "sql" }
Find $\frac{x^2}{y^2}$ + $\frac{y^2}{x^2}$ If $\frac{x}{y}$ + $\frac{y}{x}$ = 3 Find $\frac{x^2}{y^2}$ + $\frac{y^2}{x^2}$ Any Ideas on how to begin ?
\begin{align*} \frac{x}{y} + \frac{y}{x} = 3 &\Longrightarrow \left(\frac{x}{y} + \frac{y}{x}\right)^2 = 9 \\\ &\Longrightarrow \frac{x^2}{y^2} + \frac{y^2}{x^2} = 9-2=7 \end{align*}
stackexchange-math
{ "answer_score": 7, "question_score": 2, "tags": "fractions" }
Where do offline synced google docs get stored on Mac OS X? If I turn on google docs/sheets/drive offline sync through chrome on os x and activate "Make Available Offline" for some doc, where is the doc stored locally on my machine? I am not talking about google back up and sync - I am talking specifically about activating offline docs sync through a browser (in this case chrome). This answer gives the answer for PC, Android, and Linux but not mac. I looked in all the typical Application Support folders as well as in Chrome Developer Tools --> Sources --> Filesystem and also Developer Tools --> Application --> IndexedDB but I cannot figure it out. IndexedDB --> GoogleDriveDs --> Offline shows an entry for offline synced files (and not others) but it doesn't help me find it locally on my disk. Thanks!
It is stored in: ~/Library/Application Support/Google/Chrome/Default/IndexedDB where "Default" might need to be substituted by your profile name.
stackexchange-apple
{ "answer_score": 3, "question_score": 2, "tags": "google chrome, google docs" }
Azure Data factory pipeline: How to display Custom Activity Progress in azure portal I have a time consuming custom activity running in a Azure data factory pipeline. It copies files from Blob to FTP server recursively. The entire activity take 3-4 hours based on the number of files in the folder. But when I am running the pipeline, it shows in progress 0%. How update pipeline progress from custom activity?
In short, I doubt you will be able to. The services are very discounted from each other. You might be better off writing out to the Azure generic activity log and monitoring directly from the custom activity method. This is an assumption though. Hope this helps.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "azure, azure data factory" }
How to make a 2D image which kills people who see it? There are numerous, ( _or at least one that I can think of_ ), horror films which - after watching a short film or video - or seeing a particular thing - the person would be cursed and (probably) die. Is it actually possible for a 2D image or video to kill the person who sees it? How would this have to work? * The person would have to die either immediately or later * They need to have died because of the image/video. By this I mean that the particular image need to have killed them. You can't count an image that could be replaced by another random image. _For example, any random text message or image on a cell phone which caused the person to crash and die while driving would not count_ ) * It should kill 60% or greater of the people who look at it * You must not post the image on this site or you won't get any upvotes - because we'd be dead.
**It's simply not possible.** The novel Snow Crash has the most plausible explanation as to how something like this would work. > "The book presents the Sumerian language as the firmware programming language for the brainstem, which is supposedly functioning as the BIOS for the human brain." > > This language is written in a 2D format that looks similar to the "snow" static on a old TV screen. It programs the brain through activating, in a binary fashion, fibers in the optic nerve. However, it's pure fiction. It also makes me realize that kids these days don't know about the TV snow... sigh. _Anyway._ The only way you're going to get a any kind of image to kill someone is if that image is made of a material outputting high levels of ionizing radiation. Of course, that has nothing to do with the image itself.
stackexchange-worldbuilding
{ "answer_score": 31, "question_score": 28, "tags": "weapons" }
Why won't background CSS color stay on hover? On this dev site, if you hover of "BRANDS" in main menu, it brings up a dropdown. Hover over any of them and the background _blinks_ red and then goes away. I added background CSS to the "li" and "a" elements of the main menu like this... .mega-dropdown-inner ul.level1 li.open:hover{ background: red !important; } .mega-dropdown-inner ul.level1 li a:hover{ background: red; } NOTE: I don't think I even need the "a" styling, but just tried it in case it helps. Any idea why the background color won't stay the whole time you are hovering?
Because of this rule .t3-megamenu .mega-nav > li a:hover, .t3-megamenu .dropdown-menu .mega-nav > li a:hover, .t3-megamenu .mega-nav > li a:focus, .t3-megamenu .dropdown-menu .mega-nav > li a:focus { background-color: #002d5c !important; } in your custom.css line 1031. It is overriding your rule
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "html, css" }
Sending a table by pentaho spoon email In Pentaho spoon, I'm inputting a table and adding some filters, constants, and calculated fields. My final step is to e-mail the remaining lines. The mail function sends a separate e-mail for each line - is it possible to send the entire table in the body of the e-mail.
You can't do it in one transformation, the email step for a transformation in Spoon is designed to operate for each input row. The easiest way would be to end the transformation generating a file with your data and create a job to run the transformation and continue the job sending an email (using the job action) taking that file and sending the data as an attachment. If you need to send the rows in the mail body and not as an attachment, this old thread offers different methods to achieve it: Send SQL query Result set to an email ID using Pentaho
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "pentaho, pentaho spoon" }
jquery not() and has() combined Im trying something like this: $(".off-canvas-list li").not(has("ul")).addClass("liChildless"); This doesn't work though, how shall i write this code to add a class of "liChildless" to all li tags that doesn't have a child ul?
$(".off-canvas-list li:not(:has('ul'))").addClass("liChildless"); **FIDDLE**
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "jquery, list, html lists" }
JQuery, javascript, Each function I have inputs hidden from `PHP` and I'm corventing it into `javascript` `array`. Now I need some function in `jQuery` like $(".data").attr('data-day'== day).each(function(){}); I need this solution, no others... Thanks!
Here's how you do it: $(".data[data-day='" + day + "']").each(function() { ... });
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "javascript, jquery" }
Why doesn't boost::fusion::as_set remove duplicates from a boost::fusion::vector? I have: auto my_vec2 = boost::fusion::make_vector(42,false,42); auto my_set2 = boost::fusion::as_set(my_vec2); and when I go to debug I was expecting my_set2 to only contain 42 and false, however it contained 42 twice. Why is this? If its a set surely the "keys" should be unique?
It’s your responsibility: > **Precondition:** There may be no duplicate key types. (from this doc)
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "c++, boost, boost fusion" }
What is the standard approach for setting up a Visual Studio 2010 solution for ASP.NET MVC 3 project I am currently working on a ASP.NET MVC 3 project and I am setting up the solution file on VS2010. I am not sure of what is the standard approach. I am using the following approach 1. Company.Dept.Data (contains the dbml file - Data Model) 2. Company.Dept.Business (Business logics) 3. Company.Dept.Web (contains ASP.NET MVC3 webapplication) The first two are class libraries and the last one is MVC3 web application. Anyother recommendations?
There is no single "standard" approach. It all depends on your project and what problems you are trying to solve with the software. Your proposed structure of having 2 class libraries and 1 web project is one way to go for sure. If you are going to do any kind of Dependency Injection using an Inversion of Control container, you might also want to consider having an "API" project for interfaces and an "Impl(ementation)" project for concrete classes that fulfill the interface contracts.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "visual studio 2010, asp.net mvc 3" }
Conflicting page numbering using \input{} Basically, i divided my document into several sections, each is in .tex file and combined them in a "main.tex" document with `\input{}` as follows: \documentclass[12pt,a4paper]{article} \begin{document} % --------------- \input{title} \newpage \tableofcontents \input{intro} \input{another} % ---------------- \end{document} intro.tex \begin{titlepage} \section{Introduction} blah blah blah \subsection{Bla Bla bla} more text goes here \subsubsection{Examples} additional text \end{titlepage} another.tex \begin{titlepage} \section{Introduction} blah blah blah \end{titlepage} ![The page of contents]( It can be seen that page numbering is not coherent. why is this happening ? I'm sorry if this is a duplicate but i've searched everywhere for a solution and couldn't find any.
This is unrelated to `\input`. the pagenumbering is being reset to 1 by the `titlepage` environment, you should simply delete that for your normal sections, also both your sections have the same title, "Introduction" which is rather confusing.
stackexchange-tex
{ "answer_score": 2, "question_score": 1, "tags": "page numbering" }
Plotting two arrays of different lengths So I have some data import pyfits import matplotlib.pyplot a = pyfits.getdata('data.fits') x = a['time'] y = a['flux'] I had a issue with some data where my arrays contained NaN values. To get rid of them, I did the following: x = x[numpy.logical_not(numpy.isnan(x))] y = y[numpy.logical_not(numpy.isnan(y))] Which removes all NaN values from the arrays `x` and `y`. The problem is that `x` and `y` did not contain the same amount of NaN values. so: len(y) = 4275 whereas: len(x) = 4313 I'd like to be able to do this: pyplot.plot(x,y) but there is a problem with trying to plot arrays of different dimensions. Is there a way that I can do this?
How are you getting your data plots? I would assume on import you would have x or y be 0 such that each x has an appropriate y?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python, arrays, matplotlib" }
Is there a way to enter back tick (backtick) on SO when using iPad or iPhone? There are times when I only can use iPad to access SO, and the back tick ` is needed to quote the literals... but it seems on iPad, there is no way to enter a back tick on the keyboard? Can it be somehow entered?
Assuming you're using the US keyboard layout, tap the `.?123` key, then tap and hold the `'` key: a popup will appear where you can tap the ``` key. If I remember correctly, this only works in iOS 4 and later: if you're still running iPhone OS 3.2, you're out of luck and you really should just upgrade already.
stackexchange-meta
{ "answer_score": 83, "question_score": 61, "tags": "support, ipad, backtick" }
Glassfish 3.1.2 - Difference Between default-config and server-config What is the difference between default-config and server-config? If I want to adjust a thread pool size for example, do I need to do it in both places? If just one, which one?
It appears that the default-config is used by Glassfish as a template to create other configs, so anything you actually want to configure on a server should go in the server-config. Also see Glassfish 3 has two configurations
stackexchange-stackoverflow
{ "answer_score": 20, "question_score": 21, "tags": "configuration, glassfish 3" }
Transfer byte to char in Java - in CMD If I transfer `byte` to `char` in Java, I have following problem: In Netbeans is all O.K., but if I run program from Windows cmd I have a problem with charset. I don't know why. What to do? Code: char tmp = (byte) charFromByteInt; // it's byte in int variable ![](
Guessed on your output image it's a charset problem. following snippet return the same byte values for your input string. String testString = "TEST for stackoverflow"; byte[] bytes = testString.getBytes(StandardCharsets.UTF_8); System.out.println("bytes = " + Arrays.toString(bytes)); bytes = testString.getBytes(StandardCharsets.ISO_8859_1); System.out.println("bytes = " + Arrays.toString(bytes)); **output** bytes = [84, 69, 83, 84, 32, 102, 111, 114, 32, 115, 116, 97, 99, 107, \ 111, 118, 101, 114, 102, 108, 111, 119] As your output in the console generates more characters then in the input string, you should check the source (from where you take the `byte` / `int` values) for the output.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "java, cmd, char, byte" }
Convert HTML to a proper plain text? is there any way I can convert HTML into proper plain text? I tried everything from raw to sanitize and even the Mail gem with it's text_part method which is supposed to do exactly that but doesn't work for me. My best shot so far was `strip_tags(strip_links(resource.body))` but `<p>`, `<ul>` etc. were not correctly converted. This is more or less what I have in HTML: Hello This is some text. Blah blah blah. Address: John Doe 10 ABC Street Whatever City New Features - Feature A - Feature B - Feature C Check this out: Best, Admin which converts to something like Hello This is some text. Blah blah blah. Address: John Doe 10 ABC Street Whatever City New Features Feature A Feature B Feature C Check this out: Best, Admin Any idea?
Found the solution here: < Works like a charm!
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 13, "tags": "ruby on rails, ruby on rails 3, html to text" }
Extracting integers (of varying length) before specific string in R I am trying to extract integers of varying length from a data frame column ($description) that precedes a known string. For example, I wish to extract the integers that appear before the string "yard" in the following (each line represents a separate entry in the dataframe column): (3:18) B.Green-Ellis left end to NE 28 for -1 yards (A.Ross). (1:07) (No Huddle Shotgun) B.Green-Ellis right guard to NYG 27 for 4 yards (C.Blackburn). (14:00) B.Green-Ellis right end pushed ob at NYG 33 for 17 yards (K.Phillips). What makes it problematic is that the integer can vary in length (i.e. 4 or 17), but it can also be negative. I really have tried everything I can think of, and have been searching all day for a related thread!
A very simple solution would be s1 <- "(3:18) B.Green-Ellis left end to NE 28 for -1 yards (A.Ross)." ss1 <- strsplit(s1, split = " ")[[1]] as.numeric(ss1[grep("yards", ss1) -1]) now you just have to put this in a loop and apply to every row, i.e s1 <- "(3:18) B.Green-Ellis left end to NE 28 for -1 yards (A.Ross)." s2 <- "(1:07) (No Huddle Shotgun) B.Green-Ellis right guard to NYG 27 for 4 yards (C.Blackburn)." s3 <- "(14:00) B.Green-Ellis right end pushed ob at NYG 33 for 17 yards (K.Phillips)." df <- rbind(s1,s2,s3) splits <- strsplit(df[, 1], split = " ") sapply(splits, function(z) z[grep("yards", z) - 1]) you can also do this in one step, as @joshua suggested!
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "r" }
Why does this return 'never' type? I found something really interesting. type q = number & string; As you can see, on hovering over `q`, I see it is of type `'never'`. Why is this so?
The idea is that `never` means that the variable will never happen/occur, so when you declare a variable to be an intersection (&) of both `number` and `string`, TypeScript will try to find types that are both `number` and `string` at the same time... Which will **never** happen, as the two types do not intersect. I guess an equivalent analog is that you are trying to find something that is both a left hand and a right hand, which will never happen.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "javascript, typescript" }
Is it necessary to use lowercase for every Element and attribute , properties in css and xhtml ? ## 4.2. Element and attribute names must be in lower case XHTML documents must use lower case for all HTML element and attribute names. This difference is necessary because XML is case-sensitive e.g. <li> and <LI> are different tags. Source : < But is it also necessary for attributes, properties, values, class and ID for elements. Upper case and came case should not be used. What is the benefit of use lowercase for every thing?
> What is the benefit of use lowercase for every thing? There are a few good reasons: * simplifies implementation; you'll only have to look for one variant to match a tag, not all its case-sensitive variants, for example * easier to type, if needed; humans appreciate things that save them effort * one consistent way to do everything * lower cognitive overhead about whether this tag should be capitalized or not
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "css, xhtml, w3c" }
Reopen meta question? I don't think I actually ever wanted to vote to reopen a question posted on meta until today. I have had a -2 in my reputation history and wondered where it came from. Went to meta and found this question which was somehow helpful. The first sentence of the close reason > This question is unlikely to help any future visitors; is not true as it has helped me and possibly 3 other people who voted up the question. So I need a 3K rep points here on meta to cast a re-open vote but I'd like to know if any of you agree that the question shouldn't be closed as _too localized(which in fact is not a valid close reason any longer)._
I've reopened the question and closed it again as a duplicate of the relevant FAQ.
stackexchange-meta
{ "answer_score": 6, "question_score": 5, "tags": "discussion, status completed, specific question, meta, reopen closed" }
Suppress SSIS Warnings for unused output column Is there a way to suppress warning messages of this type in SSIS? The output column "A" (584) on output "Lookup Match Output" (563) and component "Lookup" (561) is not subsequently used in the Data Flow task. Removing this unused output column can increase Data Flow task performance.
You can't, take a look at MS Connect
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ssis" }
What are invalid names for a directory under Linux? I was wondering what kinds of names are invalid for a directory under Linux, so I tried some names but I couldn't find any! Even `~` works fine! Does Linux have any restrictions for naming a directory at all?
Under Linux, a directory name cannot contain: * `/` (forward slash) * The `NULL` character (`\0`) Anything else is allowed, which of course can cause lots of issues with shell scripts that do not properly handle whitespace (single spaces or even newlines). Note that this applies to UNIX, the POSIX standard, and to Linux. In the Single UNIX specification, you'll find, for the definition of a filename: > A name consisting of 1 to `{NAME_MAX}` bytes used to name a file. The characters composing the name may be selected from the set of all character values excluding the slash character and the null byte. The filenames dot and dot-dot have special meaning (…).
stackexchange-superuser
{ "answer_score": 4, "question_score": -1, "tags": "linux" }
Adding <form> tag in a column of wp_list_table I have a html table that is built in a class that extends WP_List_Table. How can I wrap a column with `<form></form>` tag? +-----+-----+--------+ | Foo | Bar | Action | +-----+-----+--------+ | 1 | 2 | Click | +-----+-----+--------+ | 2 | 3 | Click | +-----+-----+--------+ | 3 | 4 | Click | +-----+-----+--------+ How can I wrap Click inside a `<form></form>` tag?
You cannot. A form can contain an entire table or be contained within a single table cell. It cannot contain part of a table.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, wordpress, forms, html table" }
Android - Access PROCESS_INCOMING_CALLS permission programmatically There's no permission in `Manifest` class for the `android.permission.PROCESS_INCOMING_CALLS` permission. I need it for runtime asking for permissions.
> There's no permission in Manifest class for the android.permission.PROCESS_INCOMING_CALLS permission. That is because Android does not have such a permission, as you can tell by looking at Android's own manifest and looking at the various `<permission>` elements.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, android permissions" }
Did the Peverell brothers attend Hogwarts? Related to my own question: Who came first; The Four Founders or the Peverell Brothers? The current answer is that Hogwarts was founded in 993 AD and the oldest Peverell (Ignotus) was born in 1214 AD. So as such, **is there any evidence the brothers attended Hogwarts?**
# We don't know. There is **no** canon info on this (at least that I could find). I would assume that they went to _some_ wizarding school, **probably** Hogwarts, as * The Gaunts live in Britian * The Gaunts are descended from the Peverells (probably the middle brother) so * We can assume that the Peverells lived in Britian. Also, Ignotus's grave was in Godric's Hallow, so that's additional proof that they were British.
stackexchange-scifi
{ "answer_score": 2, "question_score": 10, "tags": "harry potter" }
Odds Ratio for log linear models ![enter image description here]( I need to determine the odds ratio for membership in the Nazi Party for a rural Protestant teacher versus a rural teacher with no religious affiliation in Germany, I am familiar with determining odds ratio from a contingency table, however given that I can't access the data to do this and need to do it from the coefficient estimates I am lost as to how to do this, if anyone could point me in the right direction that would extremely helpful.
In my lay perspective, categorical analysis always automatically determines the baseline(reference group). Here (loglinear model) we compare the coefficient between two groups, membership-Protestant-rural and rural. So it is intuitive to see the value of rural is 0 (baseline), and so we find the offset, which is $$religionProtestent:membershipYes = 1.46613$$ Therefore, the log odd should be 1.46613 and the odd should be $exp(1.46613)=4.332436$ You may double check. Hope it helps.
stackexchange-stats
{ "answer_score": 2, "question_score": 1, "tags": "odds ratio" }
Minecraft 1.8 does not open custom made worlds correctly or not at all I have made a few custom worlds in Minecraft 1.5 and 1.8 but they don't open or don't show any blocks/collisions (Basically, I end up falling down an endless void). I tried everything like adding ram and re-downloading Minecraft. What am I doing wrong and how to fix this?
The reason your 1.5 world becomes void is because 1.8 does not have a converter into the new name-based format. It only can read them, not convert. **Note: If you have already opened your worlds in 1.8, you CANNOT retrieve it unless you have a backup.** * * * Firstly, see if you can open them in 1.5 (the version you last used). If that works, try opening it in 1.7. Save and quit after it loads. Now, your world is ready to be open in 1.8, as 1.7 has automatically prepared your world for the new name-based format (when you loaded it). * * * One more thing: It may be wise to turn on cheats on your world by changing `allowCommands:0` to `allowCommands:1` in your level.dat file (so that you can fly and not continuously fall into the void as your spawn point will most likely be void as it was in a generated chunk that 1.8 converted into air due to unknown values; numbers instead of names)
stackexchange-gaming
{ "answer_score": 5, "question_score": 0, "tags": "minecraft java edition" }
Lenovo X220T bluescreen with problems shutting down We have several Lenovo X220T with Windows 8 x64 which are occasionally causing `DRIVER_POWER_STATE_FAILURE (0x0000009f)` bugcheck/bluescreens. The systems are using OEM drivers for most everything and the issue does not seem to be related to any one individual use case. Upon shutdown, the system hangs at the "Shutting Down" spinner. Plugging in or removing any device does not cause an appropriate plug event to occur on the machine, and the device is not usable.
After examining the memory dump, it was determined that the Lenovo OEM Broadcom Bluetooth driver (`btwampfl.sys`) was taking the PnP lock and never releasing it. Updating the Bluetooth adapter to the latest Windows Update drivers resolved the issue. Full stack trace below: Call Site ----------------------------------- nt!KiSwapContext+0x76 nt!KiCommitThreadWait+0x23c nt!KeDelayExecutionThread+0x1d3 btwampfl+0xa5c6 btwampfl+0xa1f7 bthport!BthHandleRemoveDevice+0xdf bthport!BthHandlePnp+0xea bthport!BthDispatchPnp+0x68 nt!IopSynchronousCall+0xc7 nt!IopRemoveDevice+0x100 nt!PnpRemoveLockedDeviceNode+0x22d nt!PnpDeleteLockedDeviceNode+0x78 nt!PnpDeleteLockedDeviceNodes+0xa1 nt!PnpDelayedRemoveWorker+0x80 nt!ExpWorkerThread+0x142 nt!PspSystemThreadStartup+0x59 nt!KiStartSystemThread+0x16
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "windows 8, bsod" }
create mysql database with one line in bash Is it possible to create an empty database with one line of command in bash? My newbie attempts have failed: `mysql -uroot $(create database mydatabase;)` I end up having to * `mysql -uroot` * `create database mydatabase;` * `exit;`
@Nitrodist's answer will work, but it's over-engineering the problem. MySQL's command-line client supports the very handy `-e` switch, like so: mysql -uroot -e "create database 'foo'" You can of course substitute any valid SQL into there.
stackexchange-superuser
{ "answer_score": 40, "question_score": 28, "tags": "command line, bash, mysql, database" }
Apache Drill check structure of files in directory I'm working with Apache Drill from java code. Drill have ability to query directory with a bunch of files as one table. But if files in directory have different structure query will fail. I understand that it's not very common use case query directory with files of different structure, but is there any build in function or query which allow me to check that all files in directory have same structure before making any real queries to directory? I understand that I can do simple select * from path.to.directory limit 1; and catch exception, but I'm searching for Drill built in function. I search in documentation, but did not find anything.
There does not seem to be an out of the box feature for checking the data store before use it. This is not surprising for me. For example, if you consider relational databases, you do not explicitly check the connection to a database or check if it is data is not corrupted every time you execute a select. However, if you really need this, you may consider coding an ad-hoc check on the files or writing a custom drill function for that as described here.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, apache drill" }
String length in pixels in Java Is there a way to calculate the length of a string in pixels, given a certain `java.awt.Font` object, that does not use any GUI components?
> that does not use any GUI components? It depends on what you mean here. I'm assuming you mean you want to do it without receiving a `HeadlessException`. The best way is with a `BufferedImage`. AFAIK, this won't throw a `HeadlessException`: Font font = ... ; BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); FontMetrics fm = img.getGraphics().getFontMetrics(font); int width = fm.stringWidth("Your string"); Other than using something like this, I don't think you can. You need a graphics context in order to create a `FontMetrics` and give you font size information.
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 13, "tags": "java, string, fonts, awt, fontmetrics" }
Parse a plist in android and display data in the list view I am beginner in android, my requirement is to parse a plist file and display its result in the list view. List view contains an icon image, Name of the icon and an image button which shows price to buy that icon. I am struggling from few days on this, can anybody let me know the solution? Thanks in advance, Tejaswi Marakini
As plist contains xml, you should use xml parser for that. User SAX or Pull parser. Use custom list adapter to show the content in ListView Have a look on these examples < <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "android, parsing, plist" }
Is $Cov(A,BA)$ equal to $Var(A)E(B)$ when $A$ is a vector and $B$ is a matrix? I have a square matrix $B_{nxn}$ and a vector $A_{nx1}$ where $B$ and $A$ are independent with each other. I solved $Cov(A,BA)$ and obtained $Var(A)E(B)$ as follows, $Cov(A,BA)=E(A^2)E(B)-E(A)(E(A)E(R))$ $=[E(A^2)-(E(A))^2]E(B)$ $=Var(A)E(B)$ $Var(A)$ will result in a scalar value. But, $B$ is a matrix. So, the result just not justify enough for $Cov(A,BA)$ which is a scalar value. Please be kind enough to provide any instruction on the mistake I have made. If $Var(A)E(B)$ is not correct, how can $Cov(A,BA)$ be solved and what is the answer for that?
Since we are dealing with vectors and matrices, we must be careful with operations like squares and so on. The calculation would go like this I think: \begin{eqnarray*}Cov(A,BA)&=&E[(A-E[A])(BA-E[BA])^T]\\\ &=&E[(A-E[A])(B(A-E[A]))^T]\\\ &=&E[(A-E[A])(A-E[A])^TB^T]\\\ &=&Cov(A)E[B]^T\end{eqnarray*} Here $Cov(A)$ is the covariance matrix of the vector $A$, which corresponds to $Var(A)$. So the result is basically what you expected, but we need to respect matrix rules.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "matrices, covariance" }
Looping through variables to make many boxplots I am using from the package OlinkAnalyze and I am trying to make box plots. install.packages("OlinkAnalyze") library(OlinkAnalyze) df = npx_data1 the code for the boxplot is: plot <- df %>% na.omit() %>% # removing missing values which exists for Site olink_boxplot(variable = "Site", olinkid_list = c("OID01216", "OID01217"), number_of_proteins_per_plot = 2) plot[[1]] It takes values from the `olinkID` column. What I would like, is to loop through the column, choosing the next two `olinkID` at a time, to make boxplots, renaming the plot each time (e.g.plot 1 with `OID01216` and `OID01217` and plot 2 with `OID01218` `OID01219`
I used a while loop. install.packages("OlinkAnalyze") library(OlinkAnalyze) df = npx_data1 i <- 1 ids <- as.data.frame(unique(df$OlinkID)) while(i <= nrow(ids)){ print(i) x <- i+1 temp <- ids[i:x,] plotx <- df %>% na.omit() %>% # olink_boxplot(variable = "Site", olinkid_list = c(paste(c(ids[i,],ids[x,]))), number_of_proteins_per_plot = 2) plottemp <- assign(paste0("plot_",ids[i,],"_",ids[i,]),plotx) i <- i+2 }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r, loops" }
Unique numbering for two lines of equations How can you place the numbering of the equation as in the image? (I have observed that in Cauchy problems, it appears this way) Thanks. ![enter image description here](
There are _many_ ways to achieve your formatting objective. The amsmath package provides several math environments for just this purpose. Which environment to use will depend importantly on how "EQ. 1" and "EQ. 2" are structured. If there's a common alignment point (such as an `=` symbol), a `split` or `aligned` environment should be considered. If no such alignment is needed, a `gathered` environment may be the way to go. ![enter image description here]( \documentclass{article} % or some other suitable document class \usepackage{amsmath} % for split and gathered environments \counterwithin{equation}{section} % just for this example \begin{document} \stepcounter{section} % just for this example \begin{equation} \begin{split} a &= b+c \\ d &= e+f \end{split} \end{equation} \begin{equation} \begin{gathered} u = xx + vv \\ xx = yyy + zzzz \end{gathered} \end{equation} \end{document}
stackexchange-tex
{ "answer_score": 4, "question_score": 1, "tags": "align, eqnarray" }
eslint Parsing error: ecmaVersion must be 3, 5, 6, or 7 I'm using the eslint 3.18.0 and node 7.7.4. I'm setting the ecmaVersion to 8 (per the documentation), but getting this error: Parsing error: ecmaVersion must be 3, 5, 6, or 7. Is ecmaVersion 8 not supported? If it is why am I getting this parsing error? Here's the full .eslintrc.json: { "env": { "node": true, "mocha": true }, "parserOptions": { "ecmaVersion": 8, "sourceType": "module" }, "extends": "eslint:recommended", "rules": { "semi": ["error", "always"], "quotes": ["error", "single"] } }
ESLint currently supports versions 3, 5, 6 (es2015), 7(es2016) and 8(es2017). If you are having trouble enabling es2017, verify that your ESLint installation is up to date. es2017 was added to ESLint as of v3.6.0 that was released on Sep 23, 2016. Verify global/local version (whichever you are using).
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 20, "tags": "node.js, eslint" }
Does 64-bit Windows use KERNEL64? I was looking at some libraries with dumpbin and I noticed that all the 64-bit versions were linked to KERNEL32. Is there no KERNEL64 on 64-bit Windows? If not, why? All my operating systems are 32-bit so I can't just look. A google search brings up nothing worthwhile so I suspect that there is no KERNEL64 but I'm still curious as to why this is. EDIT: I found this later which is pretty useful. MSDN guide to x64.aspx)
It's always called `kernel32.dll`, even on 64-bit windows. This is for the same compatibility reasons that `system32` contains 64-bit binaries, while `syswow64` contains 32-bit binaries.
stackexchange-stackoverflow
{ "answer_score": 30, "question_score": 27, "tags": "windows, dll, 64 bit, systems programming" }
SockPathMode - what is it? I have a plist installed on my system with the following in it: <dict> <key>SockPathMode</key> <integer>438</integer> `man launchd.plist` tells me: SockPathMode <integer> This optional key specifies the mode of the socket. I haven't been able to find a list of modes and I haven't heard of 438 different modes either! If anyone can shed some light on what this key and value is really about I'd be very grateful.
The integer in the key _SockPathMode_ is the decimal presentation of the octal POSIX permissions of the UNIX socket. Converter: 438 > 0666 > file permissions: rw-rw-rw- (owner, group and anyone is allowed to read and write from/to the socket.
stackexchange-apple
{ "answer_score": 7, "question_score": 3, "tags": "macos, network, launchd" }
while loop goes infinite when used shift operations in conditon operatios This loop runs infinitely though the value if shift operations becomes zero. Not sure why. Need clarifications. size_t size_of_byte() { unsigned int size = 0, i = 1; while((i << size) > 0) { size++; } printf("The size of a byte is %u",size); return size; }
Looking for a betteer link, this is from C++, but the behaviour is the same. < > if the value of the right operand is negative or is greater or equal to the number of bits in the promoted left operand, the behavior is undefined. The compiler can assume you will never shift more than the width of that integer, consequently, the result will never be 0, so the check is not necessary. This is a perfectly legal optimization, you're relying on UB.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c, while loop, bit shift" }
Swift equivalent to ObjC Module Initializers First of all I'm trying to execute code in my app (only from my Swift Framework!) when it is loaded into memory. Normally I would use this ObjC Method to execute Code when my Framework is loaded into Memory. **Is there something equivalent to this in Swift?** static void __attribute__((constructor)) initialize(void){ NSLog(@"==== Code Injection in Action===="); /* My Code */ } What I have found: Apple Developer Page regarding this (but it's also only explained in ObjC) Other Page about Code Injection in general **Any Ideas?**
Currently, Swift does not have this functionality. You can either just define an initialization function for your framework and ask your clients to call it before using any other APIs, or you can just mix in an Objective-C file into the project.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "objective c, swift, code injection, dylib" }
How can i use serializable transactions on Java EE 6? I am learning the new annotations for transaction management, like `@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)`, but i could not find out how to create a transaction with **SERIALIZABLE isolation**. Is this possible on a per-method basis or i have to set it on the connection for the whole application?
Generally transaction isolation level is set on `Connection`, per application. However, e.g. in Spring on Weblogic server, you can set isolation level per transaction. See here, point 9.8.1.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jakarta ee, java ee 6, ejb 3.1" }
Different ways of evaluating $\int_{0}^{\pi/2}\frac{\cos(x)}{\sin(x)+\cos(x)}dx$ My friend showed me this integral (and a neat way he evaluated it) and I am interested in seeing a few ways of evaluating it, especially if they are "often" used tricks. I can't quite recall his way, but it had something to do with an identity for phase shifting sine or cosine, like noting that $\cos(x+\pi/2)=-\sin(x)$ we get: $$ I=\int_{0}^{\pi/2}\frac{\cos(x)}{\sin(x)+\cos(x)}dx=\int_{\pi/2}^{\pi}\frac{-\sin(x)}{-\sin(x)+\cos(x)}dx\\\ $$ Except for as I have tried, my signs don't work out well. The end result was finding $$ 2I=\int_{0}^{\pi/2}dx\Rightarrow I=\pi/4 $$ Any help is appreciated! Thanks.
Let \begin{equation} I=\int_0^{\pi/2}\frac{\cos x}{\sin x+\cos x}\ dx \end{equation} and \begin{equation} J=\int_0^{\pi/2}\frac{\sin x}{\sin x+\cos x}\ dx \end{equation} then \begin{equation} I+J=\frac{\pi}{2}\tag1 \end{equation} and \begin{align} I-J&=\int_0^{\pi/2}\frac{\cos x-\sin x}{\sin x+\cos x}\ dx\\\\[10pt] &=\int_0^{\pi/2}\frac{1}{\sin x+\cos x}\ d(\sin x+\cos x)\\\\[10pt] &=0\tag2 \end{align} Hence, $$I=J=\frac\pi4$$by linear combinations $(1)$ and $(2)$.
stackexchange-math
{ "answer_score": 3, "question_score": 4, "tags": "calculus, integration, trigonometry" }
Report Query for multiple subqueries Getting multiple records from table with subquery joins SELECT COUNT(*) AS total_count, (SELECT chat_box.user_id, chat_box.message, members.id, members.display_name FROM chat_box INNER JOIN members ON chat_box.user_id = members.id ORDER BY chat_id DESC LIMIT 1), (SELECT COUNT(DISTINCT user_id) FROM chat_box) AS users_count FROM chat_box This is what I have so far, I want to get the `members.display_name` from the inner join where the `chat_box.user_id = members.id` as an output along aside the `chat_box.message` and save `members.display_name` and `chat_box.message` to a variable. Any help is appreciated.
It is not exactly clear what you are trying to do, but it seems like you could use something like this: select u.user_id, u.message, u.id, u.display_name, cb1.total_count, cb1.users_count from ( SELECT cb.user_id , cb.message, m.id, m.display_name FROM chat_box cb INNER JOIN members m ON cb.user_id = m.id ) u CROSS JOIN ( select COUNT(*) AS total_count, COUNT(DISTINCT user_id) AS users_count FROM chat_box ) cb1
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mysql, join, inner join" }
how to remove \" from string in java? String mp ="\"sameer\\\"raj\""; I want `sameerraj` as out put i tried following but no luck. mp = mp.replace("\"", ""); mp=mp.replaceAll("\\\\", ""); please help me out.
If you want to replace it using `regex`,then you can use `replaceAll` In order to replace `"`,you need to use `\` to escape it,so it will be `replaceAll("\"", "")` In order to replace `\`,you need to use `\` to escape itself,but since `\` is a special character in regex,you need to use `\` to escape it again,so need to use 4 `\` in total,which is `replaceAll("\\\\", "")` System.out.println(mp.replaceAll("\\\\", "").replaceAll("\"", "")); output: sameerraj
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java" }
$P(z)$ be a monic polynomial with complex co-efficients of degree $n$ such that $|P(z)| \le 1, \forall |z| \le 1$ ; then is $P(z)=z^n$? Let $P(z)$ be a monic polynomial with complex co-efficients of degree $n$. Since by Cauchy integral formula bound, $n!=P^{(n)} (0) \le n! Sup_{|z|=1} |P(z)|$ , so $Sup_{|z|=1} |P(z)| \ge 1$ . So by Maximal modulus principle, $Sup _{|z| \le 1} |P(z)|=Sup_{|z|=1} |P(z)| \ge 1$. Now if $|P(z)| \le 1, \forall |z| \le 1$, then is it true that $P(z)=z^n$ ?
Yes. If $f(z) = \sum_{k=0}^n a_k z^k$, we have $$ 1 \ge \frac{1}{2\pi} \int_{0}^{2\pi} |f(e^{i\theta})|^2\; d\theta = \sum_{k=0}^n |a_k|^2$$ But $a_n = 1$, so all other $a_k$ must be $0$.
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "abstract algebra, complex analysis, polynomials, holomorphic functions, entire functions" }
a trouble of copying array in C++ I am copying an array in C++, here is the code: int arr1[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int *source = arr1; size_t sz = sizeof(arr1) / sizeof(*arr1); // number of elements int *dest = new int[sz]; // uninitialized elements while (source != arr1 + sz) *dest++ = *source++; // copy element and increment pointers int *p = dest; while (p != dest + sz) { cout << *p++ << endl; } after running the code above-mentioned, I got: 714124054 51734 9647968 9639960 0 0 0 0 0 0 what's the trouble?
The array is copied properly, though, by incrementing `dest` you are losing the actual beginning. You need to keep a copy of `dest` to loop after it. Also don't forget to free the memory after you have allocated it. Finally, in C++ you'll probably want to use `std::vector` instead of arrays that does all this in a transparent way while trading a minimum amount of performance. int arr1[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int *source = arr1; size_t sz = sizeof(arr1) / sizeof(*arr1); // number of elements int *dest = new int[sz]; // uninitialized elements int *d = dest; while (source != arr1 + sz) *d++ = *source++; // copy element and increment pointers int *p = dest; while (p != dest + sz) { cout << *p++ << endl; } [...] delete[] dest;
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "c++" }
Java dynamic programming “Climbing Stairs”, do not understand the logic Question is: You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? And I saw a java code which is correct, but I don't understand the logic. Can anyone explain it to me? What's a,b,c stand of? public int climbStairs(int n) { if (n<2) return 1; int a = 1; int b = 1; int c = 1; for (int i=2; i<=n; i++){ c = b; b = a + b; a = c; } return b; }
The recursive formula is f(n) = f(n-1) + f(n-2) f(0) = f(1) = 1 * * * Translated to `a, b, c` in the code if (n<2) return 1; int a = 1; int b = 1; int c = 1; The above defines `f(0) = f(1) = 1` and below calculates `f(n) = f(n-1) + f(n-2)` for `n >= 2` for (int i=2; i<=n; i++){ c = b; // f(i-1) is temporary saved in c b = a + b; // f(i-2) + f(i-1) is saved in b a = c; // f(i-1) is saved in a for the next iteration }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, algorithm, dynamic programming, fibonacci" }
Attempting to fully understand Readln in Delphi? Ok, i just want to make sure i fully understand Readln in delphi, does it only read the line of code above it? for example `Var name, surname: String; `Write('Enter your name:');` readln(name);` Does it only apply to the write('Enter your name:'); Thank you for any clarification!
Readln has nothing to do with "the line of code above it." It reads data from an input source, and stores it into the file in question. If all you give it is a variable, it will read from the keyboard. If you also give it a file handle, it will read from that file instead.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "delphi" }
Vim match with lookaround assertions? In javascript, we can replace all standalone single `i` with `i0`: str = 'if (i < 10 && i1 > 0) { life++; i-- }' str.replace(/(?<=\W)i(?=\W)/g, 'i0') // => if (i0 < 10 && i1 > 0) { life++; i0-- } How to make this happen in vim?
1. No, you cannot do that in JavaScript (yet). Look-behind is a very recent feature; apparently only Chrome supports it for now? 2. Your regex is broken anyway: It doesn't match `i` at the beginning or end of a string. 3. The correct regex doesn't require look-ahead/-behind anyway: `/\bi\b/` (`\b` being a word boundary) 4. That was for JavaScript; in vim it's `\<i\>` (`\<` = beginning of word, `\>` = end of word) 5. That said, vim does support look-ahead/-behind: `\W\@<=i\W\@=` (or alternatively `\W\zsi\ze\W`)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -1, "tags": "regex, vim, regex lookarounds" }
.NET Regular Expression: Get paragraphs I'm trying to get paragraphs from a string in C# with Regular Expressions. By paragraphs; I mean string blocks ending with double or more \r\n. (NOT HTML paragraphs <p>)... Here is a sample text: > For example this is a paragraph with a carriage return here > and a new line here. > > At this point, second paragraph starts. A paragraph ends if double or more \r\n is matched or > if reached at the end of the string ($). I tried the pattern: Regex regex = new Regex(@"(.*)(?:(\r\n){2,}|\r{2,}|\n{2,}|$)", RegexOptions.Multiline); but this does not work. It matches every line ending with a single \r\n. What I need is to get all characters including single carriage returns and newline chars till reached a double \r\n.
`.*` is being greedy and consuming as much as it can. Your second set of `()` has a `$` so the expression that is being used is `(.*)(?)`. In order to make the `.*` not be greedy, follow it with a `?`. When you specify RegexOptions.Multiline, .NET will split the input on line breaks. Use RegexOptions.Singleline to make it treat the entire input as one. Regex regex = new Regex(@"(.*?)(?:(\r\n){2,}|\r{2,}|\n{2,}|$)", RegexOptions.Singleline);
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c#, regex, paragraphs" }
How to get UIView given a CGPoint? I am trying to find a way to get a particular `UIView` given a `CGPoint`. Briefly, I want to do a hit test. For example, I have a `UIView` which has many subviews whose sizes are smaller than the parent `UIView`. What I want to do is, when a `touchMoved` event happens, to check the other subviews around the touched subview. For that purpose, it would be nice to be able to convert a `CGPoint` to a subview `UIView`. I'm new to Objective-C. Is there good way to do it? Any suggestion would be really helpful. :)
There is a hitTest:withEvent: selector on UIView. This returns the deepest subview in the view hierarchy that contains that point. Try calling this on your topmost view.
stackexchange-stackoverflow
{ "answer_score": 22, "question_score": 17, "tags": "objective c, ios, uiview, touch, hittest" }
Jquery passing form values in array to a new page I have a dynamic form where I populate values. Once the values are entered, I am able to retrieve them into a jquery array in that same page. $('#btnSubmit').click(function() { var myData = []; var rows = $('#customFields').find('tr'); rows.find('td input').each(function() { myData.push($(this).val()); }); alert(myData); }); However, I want this data to be sent to a new page (let's say processinvoice.asp) with the data hidden so that I can go through the array and write the values into a database and finally display a page saying that it has all be done successfully. I am not sure how I can pass the array into the new page. Can anyone please give me a hand? Thanks Saj
Use a hidden form (use CSS to hide a form). Once you have built the `myData` array, set a field in the form with the serialized value of the array. Use jQuery's `submit` on that hidden form to send that array value to that form's `action` page.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, asp classic" }
Using both XNA and WinForm I want to create a physic bodies redactor with XNA and BEPU. I need to create a "window" with XNA, that will be actual working space, and another with form controls like buttons, lists etc. to select options like add shape, create constraint... It also can be like 3dmax layout or Photoshop.
Take a look at this tutorial: < From the description: > This sample shows you how to use an XNA Framework GraphicsDevice object to display 3D graphics inside a WinForms application.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, winforms, xna, window" }
Adjacency list определение root node в mssql Все привет! Имеется такая таблица _________________ | ID | PARENT_ID| +----+----------+ |111 | 444 | |222 | 111 | |333 | 222 | |555 | 666 | +----+----------+ Из таблицы видно, что имеется 2 root node - 444 и 666. В таблице отсутствуют `id` у которых `parent` равен `NULL`, или `0`, или сам себе и т.д. В таблице более 100000 записей. **ВОПРОС:** Как наиболее оптимально определить все root node?
SELECT t1.parent_id FROM table t1 LEFT JOIN table t2 ON t2.id = t1.parent_id WHERE t2.id IS NULL или там SELECT t1.parent_id FROM table t1 WHERE NOT EXISTS (SELECT 1 FROM table t2 WHERE t2.id = t1.parent_id ) или ещё как... Что эффективнее на ВАШИХ структуре и наполнении - предсказать не берусь.
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, sql server" }
Issue in using Preg_replace I want to replace "ing" from the right side of the word, but the code below is also replacing other characters. $temp = "gameing"; //incorrect spellings for test// $temp = preg_replace('/(\w)ing\b/','',$temp); echo $temp; Is giving output `"gam"`, instead of `game`.
If you need the character before "ing", you can put it into replacement: <?php $temp = "gameing"; $temp = preg_replace('/(\w)ing\b/','$1',$temp); //-> game echo $temp;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, preg replace" }
git-svn with file-based access to repository I get the following error when I try to git clone an SVN repository: $ git svn clone "file:////stevenagefs/Projects/6500-6999/6792/DesignSVNRepos" "DesignGit" -T trunk -b branches -t tags -r 0:HEAD Couldn't open a repository: Unable to open an ra_local session to URL: Unable to open repository 'file:///stevenagefs/Projects/6500-6999/6792/DesignSVNRepos' at C:\Apps\Git/libexec/git-core\git-svn line 2210 Is there something I'm doing wrong or is it not possible to use git-svn like this? Note that I know that file-based access to SVN repositories is considered harmful, but that's all I have.
You are allowed file-access, but only if the client is compiled with file-access support (`ra_local`), which `git-svn` does not seem to be. If you really want file-access you will need to build your own `git-svn` client.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "git, git svn" }
¿Qué diferencia hay entre "curro", "trabajo" y "empleo"? > Yo acabo de llegar a casa del empleo. > > Yo acabo de llegar a casa del curro. > > Yo acabo de llegar a casa del trabajo. ¿Se usa `curro` también en Latinoamérica o es ya es obsoleto?
El uso de "curro", en la Argentina no es obsoleto (también se usa el diminutivo "currito"). Normalmente se utiliza si el trabajo es marginal, ilegal o en la frontera de la ilegalidad. También es posible utilizarlo para trabajos temporales en una forma intercambiable con "changa". Finalmente, puede ser utilizado si el trabajo, a pesar de ser formal/legal, es considerado como plata fácil por el trabajador. En este sentido, el "curro" (o robo) sería cobrar ese dinero por hacer muy poco. "Empleo" no se utiliza en Argentina como un lugar físico pero sí para otros usos, en particular el desempleo o los índices de empleo según franjas etarias.
stackexchange-spanish
{ "answer_score": 2, "question_score": 5, "tags": "gramática, uso de palabras, diferencias regionales" }
Nodejs persist a sqlite in-memory database I'm using the nodejs sqlite library (< How can i persist an in-memory database to disk? Since in the c/c++ implementation there are the backup api how can i persist in nodejs with this library? (or with another library/mechanism)
Using the backup API is the only way. And Node.js does not implement this API. Just use a normal, on-disk database. You can make it as unsafe as an in-memory database with PRAGMA synchronous = OFF.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "node.js, sqlite, persist, in memory" }
Passing a constant value to a function I am trying to pass a float32_t * const value to a function argument and I am getting exception errors. I have tried a lot of things but still receiving errors. My function is: float32_t Distance(float32_t *const argDistance); where **float32_t** is: `typedef float float32_t;` I am trying to access this function like this: float32_t* const tempTipDistance = 0; but it tends to throw an exception: SEH exception with code 0xc0000005 thrown in the test body. Any suggestions on how to pass a value to this function?
You are sending in a pointer containing a `0` memory address, which is an invalid address to access. If you want to send in a pointer to the value `0.0` use: float32_t value = 0.0; float32_t* const tempTipDistance = &value;
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "c, pointers, floating point, constants, parameter passing" }
Can I enable "Import pictures and videos" in Windows 10 AutoPlay? In Windows 7, when you plugged in an external camera, then you could select an AutoPlay setting entitled "Import pictures and videos": ![enter image description here]( which launched a rather simple (but effective) tool to import, rotate and (optionally) delete your photos: ![enter image description here]( In Windows 10, Microsoft decided not to make the "Import pictures and videos" option available in AutoPlay and, instead, offer the built in Windows 10 "photos" app. However you can right-click on a portable device from Windows Explorer and select "Import pictures and videos" that way. **My question is:** Is there any way to make the "Import photos and videos" wizard appear as an option in the Windows 10 AutoPlay settings? I'm lazy and don't want to keep having to do it from the Windows Explorer.
In June 2020, this Super User page is at the top of the Google search results for "restore import pictures and videos autoplay option in windows 10". I just followed this procedure in Windows 10 feature version 2004 and this still works: To add "Import Pictures and Videos (Windows)" to the Windows 10 AutoPlay options list for devices like digital cameras: Run As Administrator these three commands in a batch file or run them individually in an elevated Command Prompt window: cd "C:\Program Files (x86)\Windows Photo Viewer" regsvr32 PhotoAcq.dll regsvr32 PhotoViewer.dll Source: <
stackexchange-superuser
{ "answer_score": 0, "question_score": 2, "tags": "windows 7, windows 10, video, camera, autoplay" }
How to create a separate file for aliases in .cshrc? I've tons of aliases in the _.cshrc_ file. For example: alias some_alias 'cd /some folder' It's possible to have these aliases in a separate file ? This file is becoming huge.
As far as I am aware, none of the `csh` family of shells provides a mechanism for the `alias` subcommand to read aliases from a file, but of course you can use the `source` command in your `.cshrc` file to read additional input from an arbitrary file. For example, **.cshrc** # ... source ~/.aliases.csh **.aliases.csh** alias some_alias 'cd /some folder' alias another_alias 'frob -x' # ...
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "csh" }
setting bash variables while executing scripts My sample script looks like #!/bin/bash VAR="foo" if [ $VAR etc etc then etc ... Is there any way to call the script changing the value of $VAR without writing the script? I would imagine something like $ bash script.sh -v VAR="bar" (sorry for the invention)
To set an environment variable for an invocation of a program, just add the assignment to the line before you call the script: VAR=bar ./script.sh Note that this won't override what is set in the script; so within the script, you will need to check if it's already set before setting it to a default value. If you want this variable to be set for several invocations, then you can define it in your shell, and export it so that it will be in the environment of child processes: $ export VAR=bar $ ./script.sh
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "bash" }
Why don't I need to include library.cpp in the header? I have a question about libraries. When I write a library I have 2 files: `library.h` and `library.cpp`. The first one contains the prototypes of the functions and the second one contains the definitions. Well, in `library.cpp` I include `#include "library.h"`, so they are connected in one way, but what happens with the header? Why don't I have to write `#include "library.cpp"` in the header? When I use the library in the main file, I write `#include "library.h"`, which includes the prototypes, but how does the compiler know where the definitions are?
Explained briefly: (1) Your `library.cpp` file is sent to the preprocessor. (2) The preprocessor reads the line `#include "library.h"` and goes and finds the file `library.h`. (3) The contents of `library.h` are literally copied into the `library.cpp` file. (4) The `library.cpp` file is compiled and linked with the main file. Thus, all of the "prototypes" in the header are copied into the top of the implementation file. `.cpp` files are compiled and linked. The header files themselves are _not_ compiled -- their contents are copied into the `.cpp` files.
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 4, "tags": "c++, header, libraries" }
How to set varchar on installschemas I would like to add a new column inside the magento2 database. Write now i add a `\Magento\Framework\DB\Ddl\Table::TYPE_TEXT` as the column type. here is my code if(!$installer->getConnection()->tableColumnExists('review_detail', 'email')) { $definition = [ 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, 'size' => 255, ['nullable' => true, 'length' => 255], 'comment' => 'User Email' ]; $installer->getConnection()->addColumn( 'review_detail', 'email', $definition ); } right now, when i do my `php bin/magento setup:upgrade` the new column are set as text(65535). I'm using MySQL as database. How i can set the new column as VARCHAR(255)? i've looked on several website and everything i see is to use TYPE_TEXT with a size under 255 to setup a VARCHAR.
Try using it like, if(!$installer->getConnection()->tableColumnExists('review_detail', 'email')) { $definition = [ 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, 'size' => 255, 'nullable' => true, 'length' => 255, 'comment' => 'User Email' ]; $installer->getConnection()->addColumn( 'review_detail', 'email', $definition ); }
stackexchange-magento
{ "answer_score": 1, "question_score": 1, "tags": "magento 2.1, module, database" }
Clarification on the -h Flag for Makecert.exe When using Microsoft's Makecert.exe to generate a certificate (and key), there is the option to allegedly "specify the maximum height of the tree below that certificate", using the -h flag (see MSDN). As an experiment, I created a certificate with "-h 0", assuming this to mean that this certificate in turn could not be used to generate another (adding to the chain). I then went on to attempt creating a subsequent certificate, and to my surprise all went well. I can't find anything further explaining the usage of the flag on MSDN or anywhere else. Can one of you please enlighten me?
I did some further investigation and realized that this constraint is taken into account at the time of _resolving_ the certificate chain of trust, not at the time of creating a new link. From RFC 5280: > The pathLenConstraint field [...]. In this case, it gives the > maximum number of non-self-issued intermediate certificates that may > follow this certificate in a valid certification path. [...] A pathLenConstraint > of zero indicates that no non-self-issued intermediate CA certificates may > follow in a valid certification path. [...] Where pathLenConstraint does > not appear, no limit is imposed. See also TechNet - Understanding Constraints.
stackexchange-security
{ "answer_score": 2, "question_score": 3, "tags": "certificates, windows" }
MySQL tables are markes as crashed after repair I've used myhotcopy to backup my MySQL databases. I had to recovery everything after a system crash, so I moved the files into the MySQL directory. Now, every 1-2h the server seems to do an auto repair for some tables or anything like this. If I manually start a repair, the table will be marked as crashed after that. Anyone knows, why this happens and how I can fix this?
I would mysqldump everything, move the db and innodb files somewhere safe, and reload from the dumps. Will likely take less time.. Could the mysqlhotcopy job the files originate from ever have run out of file descriptors/driven mysqld out of the same while dumping unattended? That is an extremely great way to get a subtly corrupt backup, mostly working, of a mysql installation. Mysqldump is similarly vulnerable by the way; any spurious errors when dumping should never be ignored as they often point to exactly that problem.
stackexchange-serverfault
{ "answer_score": 2, "question_score": 0, "tags": "linux, mysql" }
What does the <> operator mean What does the operator **< >** mean/do in the following code? class Functor f => Foldable f where fold :: Monoid m => f m -> m foldMap :: Monoid m => (a -> m) -> f a -> m instance Foldable [] where fold = foldr (<>) mempty Can anyone tell me?
It's an operator from Data.Monoid: (<>) = mappend‌​ You can often Hoogle or Hayoo for such operators.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 4, "tags": "haskell, operators, functor" }
Tagging Records in a Continuous Form In a continuous subform, I display records based on a **DISTINCT** query. Because it's distinct, each row does **not** include a record ID. Does anyone know of a way to add a checkbox (or similar), so that a user can select any of the records, which will then be used to create new records via code? I prefer to use a subform to a list, as it features lots of column sorting and filtering functions. MTIA
FYI, I decided to use the Windows **ListView** OCX control, as it offers the ability to add a checkbox for each row.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ms access, tagging" }
Excel if or query on multiple options I'm looking for a way to either pass or fail a set of tests based on different pass/fail/blocked criteria. Here's my table: ![enter image description here]( I would like to add a Pass/Fail or Blocked result in the 'result goes here' cell, so I guess i'll need multiple if/or statements. For a pass outcome, the criteria is that 'Critical fail' and 'Blocked' are =0, and 'Passed' is > 0. For a fail result Critical fail must be > 0 (regardless of other values) For a blocked result Blocked must be > 0 (regardless of other values) So I am guessing in need an if statement with a couple of OR statements and the 'Passed' query has an AND query within itself. Any help would be greatly appreciated
As you mentioned you need to use several IF statements: IF(B5>0,"Blocked",IF(B3>0,"Critical",IF(AND(B3=0,B5=0,B1>0),"Critical Fail",NA()))) Where * B1 > "passed" value * B3 > "critical fail" value * B5 > "blocked" value
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "excel, excel formula" }
Always Encrypted: How to insert or update encrypted columns? I have configured 'Always Encrypted' on one of the columns of a table of my SQL Server database. I am able to select and view data from client SSMS after passing the 'Column Encryption Setting = Enabled' option. But when I am trying to insert data into the table, following error comes: > Msg 206, Level 16, State 2, Line 1 Operand type clash: varchar is incompatible with varchar(8000) encrypted with (encryption_type = 'RANDOMIZED', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto1', column_encryption_key_database_name = 'TEST') collation_name = 'SQL_Latin1_General_CP1_CI_AS' I am querying simple insert TSQL statement here. What changes should I need to make for it to work? Also, what changes need to be made to the application or application code if, we want to update or insert the encrypted column via application?
You need to use variables for the values, so that SSMS can parameterize the query against the API that it is using. Something like: DECLARE @fname varchar(30) = 'Kula' DECLARE @ename varchar(30) = 'Kalle' DECLARE @pnr varchar(11) = '752312-4545' DECLARE @age tinyint = 45 insert into dbo.Personer2 (Förnamn, Efternamn, Personnummer, Ålder) VALUES (@fname, @ename, @pnr, @age) SELECT * FROM Personer2
stackexchange-dba
{ "answer_score": 3, "question_score": 4, "tags": "sql server, t sql, sql server 2016, encryption, always encrypted" }
How to convert number (int or float64) to string in Golang How do I convert any given number which can be a int or float64 to string ? Using strconv.FormatFloat or FormatInt I have to specify that the given number is a float or integer. In my case it is unknown what I get. Behaviour: When I get a `5` it should be converted into `"5"` and not `"5.00"` When I get a `1.23` it should be converted into `"1.23"` and not `"1"`
You may use `fmt.Sprint` `fmt.Sprint` returns string format of any variable passed to it **Sample** package main import ( "fmt" ) func main() { f := fmt.Sprint(5.03) i := fmt.Sprint(5) fmt.Println("float:",f,"\nint:",i) } play link
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 6, "tags": "string, go, casting, integer" }
Add to a list based on previous value I am trying to group this list together Example input M1 = [['a', 14], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]] Output [['a',14,7,16],['b',3,15],['c',22,1,5]] Meaning group all the 'a' value together same goes for 'b', 'c' and so on
To get a list of lists (like your questions asks for) you can do something like this: M1 = [['a', 14,15], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]] output = {} for l in M1: if l[0] in output.keys(): output[l[0]].append(l[1:][0]) else: output[l[0]] = l[1:] # Output is now a dictionary. You can stop here if you're fine with a dictionary, or continue on from here listOfLists = [] for k, v in output.items(): listOfLists.append([k, *v]) And then the results: >>> print(output) # {'a': [14, 15, 7, 16], 'b': [3, 15], 'c': [22, 1, 5]} >>> print(listOfLists) # [['a', 14, 15, 7, 16], ['b', 3, 15], ['c', 22, 1, 5]]
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 2, "tags": "python, list" }
R: how to display the first n characters from a string of words I have the following string: Getty <- "Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal." I want to display the first 10 characters. So I began by splitting the string into individual characters: split <- strsplit(Getty, split="") split I get all the individual characters as this point. Then I make a substring of the first 10 characters. first.10 <- substr(split, start=1, stop=10) first.10 And here is the output: "c(\"F\", \"o\"" I am not understanding why this prints out? I thought it would just print out something like: "F" "o" "u" "r" "s" Is there a way I can alter my code to print what I have above? Thank you everyone!
The other answers didn't eliminate the spaces as you did in your example, so I'll add this: strsplit(substr(gsub("\\s+", "", Getty), 1, 10), '')[[1]] #[1] "F" "o" "u" "r" "s" "c" "o" "r" "e" "a"
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 8, "tags": "r, string, substr, strsplit" }
Java Freemarker macro with optional css classes I'm trying to do a macro on freemarker, but I'm having problems to implement css class as parameter. My object have some default css classes and I would like to add optional classes. <#macro Button href extra...> <a href="${href}" class="ui-button" <#list extra?keys as attr> ${attr}="${extra[attr]?html}" </#list> >Anchor Button</a> </#macro> 1) <@Button href="link.html"></@Button> 2) <@Button href="link.html" id="button1" class="marginrightnone"></@Button> The line 2) only is rendering the "id" parameter. If I delete class="ui-button" of the macro, then it renders correctly. What I could to do to render two or more class parameters???
You need to construct a string containing all the class parameters and use that as the value of a single HTML `class` attribute in the template. You can't have an arbitrary number of `class` attribute/value pairs and still be legal HTML. The simplest that would be basically what you have now would be to create a local with the `"ui-button"` value in it. As you iterate over `extra?keys` check for a `"class"` key and if found, append it to the local class (along with a leading space). The template would use that constructed value: <a href="${href}" classes="${local_classes}"
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, freemarker" }
Why LDAP inetOrgPerson class has preferredLanguage attribute but no timezone attribute? I'm using OpenDJ and I was surprised to discover that inetOrgPerson object class contains no built-in attribute to specify the preferred timezone, only preferred language. Any ideas why such basic field as timezone is missing and how to add it? May be there is another auxiliary object class that can contain this information? I scanned the whole OpenDJ installation but didn't find something that could fit, except some Solaris classes. I'd like to save the complexities of extending the schema, so as a simplified solution I consider reusing one of the unused inetOrgPerson attributes for storing timezone information. Do you think it is a good idea?
As you have discovered yourself, there is no standard attribute to store a timezone associated with a user. This is not an OpenDJ only issue, it's an LDAP-wide standard issue. The only one that I know of is attached to NIS+ schema and I'm not even sure it's defined as being generic enough. The proper way to do this would be to define a new attribute and an auxiliary objectclass to contain that attribute. With OpenDJ, you could also define an "ENUM" syntax to restrict the values to proper timezones. You could for your own application decide to "abuse" another attribute to store the timezone. But this may create confusion to other applications that will connect to the server in the future. I would not recommend it. Kind regards, Ludovic
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ldap, schema, opendj" }
Ember apps translation I need to translate my Ember.js application. I've seen Ember-i18n, but I don't really like it approach. Writing something like {{t user.edit.title}} isn't very readable. I'd like better something more similar to the good old gettext, with `.po` files and so. Maybe something like this: {{_}}Edit user{{/_}} Is there any option I could use?
You might be able to use a combination of i18next and a handlebars helper. Ember.Handlebars.helper('__', function(options) { var result = i18n.t(options.fn(this)); return result; }); {{#__}}Text to translate{{/__}} Not entirely sure if that works, can't test it right now.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ember.js" }
How to parse string with links into html links Say I have a string below: const input = `This is a link: this is another link: How would I parse that string and output another string that looks as follows in js: const output = `This is a link: <a href=" this is another link: <a href="
Here is a one liner: const input = `This is a link: this is another link: let output = input.replace(/(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*))/g, (x)=>'<a href="'+x+'">'+x+'</a>'); console.log(output);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "javascript, node.js" }
How to export word document to PDF and have selectable text I'm using Microsoft Word from Microsoft Office Professional Plus 2010. I exported a 32 page document that has objects in it (files, images, as well as normal text) as a PDF. In the exported PDF the text is not selectable. I want to export it to a PDF and at least have the text be selectable (mostly for copy/paste purposes). If there would be any way for me to attach the files to it as well that would be awesome. Note: I have a cover page, a table of contents and I am using styles throughout the document as well as Consolas and Calibri font.
By default Microsoft Word renders a document to PDF with selectable text. Make sure you are going Word Ribbion -> Save As -> PDF or XPS - > Publish. I think what you are doing at the moment is printing to the Adobe PDF virtual printer which will render the document to PDF as an "image" which will not allow copy and paste of text.
stackexchange-superuser
{ "answer_score": 4, "question_score": 4, "tags": "microsoft word, pdf, microsoft word 2010" }
Git: how to rebase onto previous commit I'm working on branch C which is based on branch B, then branch A: `A---B---C` Is there any commands that can make branch C directly based on branch A like this: `A---B \ --C` I have tried `git rebase A` but it does not work.
git rebase --onto A B C Explanation: In rebase command, you can define: 1. Branch to rebase (by default = HEAD) 2. The upstream branch of branch-to-rebase 3. Target Branch to rebase to (by default = upstream branch) and the command is git rebase --onto TargetBranchToRebaseTo UpstreamBranch BranchToRebase In fact you can almost an exact example in `git help rebase`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "git" }
Markov property and memoryless property Let X be N~(0,1). Show that: $$ \mathcal{P} (X > t + \frac{a}{t} | X>t) \underbrace{\longmapsto}_{t \longmapsto \infty} e^{-a} $$ I used firstly the memoryless property and then the markov inequality: $$ \mathcal{P} (X > t + \frac{a}{t} | X>t) = P(X > \frac{a}{t}) $$ by Markov and applying the exponential function since increasing and continuos: $$ \mathcal{P}(e^X > e^{\frac{a}{t}}) \leq \frac{E(e^x)}{e^{\frac{a}{t}}} = \frac{e^{\frac{1}{2}}}{e^{\frac{a}{t}}} $$ Thus, it's not the result that I needed when t goes to infinity. Can anyone spot my mistake?
Exactly, it suffices to verify the assertion by definition. Let $\Phi(x)$ be the c.d.f. of standard normal distribution. $$ \begin{align} P(X > t + \frac at | X > t) &= \frac{P(X > t + \frac at, X > t)}{P(X > t)} \\\ &=\frac{P(X > t + \frac at)}{P(X > t)} \\\ &= \frac{1 - \Phi(t + a/t) }{1 - \Phi(t)} \quad\text{ apply L'Hôpital's rule}\\\ &\to \frac{-\Phi^\prime(t+a/t)(1 -a/t^2)}{-\Phi^\prime(t)} \\\ &\to \frac{e^{-\frac12(t+a/t)^2}}{e^{-\frac12t^2}} \\\ &\to e^{-a} \end{align} $$
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "probability theory, conditional probability, markov process" }
Partitioning a List of Vectors into pairs of subsequent Vectors If I have a list like: ll <- list(c(1,2),c(2,3),c(3,4),c(4,5)) How can I split it in: list(list(c(1,2),c(2,3)),list(c(2,3),c(3,4)),list(c(3,4),c(4,5))) In Mathematica, I have the function Partition, where I can do: Partition[ll, 2] but I didn't find a equivalent in `R`.
You can try `Map` r2 <- Map(list, ll[-length(ll)], ll[-1]) r1 <- list(list(c(1,2),c(2,3)),list(c(2,3),c(3,4)),list(c(3,4),c(4,5))) identical(r1, r2) #[1] TRUE
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "r" }
How does TTL affect my internet connection? Each day I run pings to test latencies, but TTL is different every day, sometimes higher, sometimes lower. How does this affect my connection? Reply from 209.131.36.159: bytes=32 time=106ms TTL=52 Reply from 209.131.36.159: bytes=32 time=93ms TTL=52 Reply from 209.131.36.159: bytes=32 time=63ms TTL=52 Reply from 209.131.36.159: bytes=32 time=73ms TTL=52
Each IP packet you send out has a TTL field, which is set to some initial value (in most cases this will be 64). Each time a packet passes a router, the TTL field is decremented by one. Should the TTL field ever reach 0, the packet is dropped to avoid packets circling around forever. Now, internet routing is dynamic, in most cases, there are multiple paths to a given destination, and depending on the number of routers along each path, you'll end up with a different TTL, so varying TTLs are perfectly normal.
stackexchange-superuser
{ "answer_score": 3, "question_score": 0, "tags": "networking, ping, latency" }
Add Foreign Key in SQL by My-SQL Workbench gives Error 1064 I want to add a Foreign Key to a table called "address". ALTER TABLE `students1`.`address` ADD CONSTRAINT `id_country` FOREIGN KEY () REFERENCES `students1`.`country` () ON DELETE NO ACTION ON UPDATE NO ACTION; This request was automatically generated by MySQLWorkbench. But get this error ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') REFERENCES `students1`.`country` () ON DELETE NO ACTION ON UPDATE NO ACT' at line 3 How fix this?
i don't know if your **both** tables have the same column `id_country`. But the syntax in that case is: ALTER TABLE `students1`.`address` ADD CONSTRAINT FOREIGN KEY (`id_country`) REFERENCES `students1`.`country`(`id_country`) ON DELETE NO ACTION ON UPDATE NO ACTION;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "mysql, sql, foreign keys, mysql workbench" }
Add an animation to a Show/Hide Checked Box I use this javascrpit code to show/hide a div when a specific checkbox is checked $(function() { $('input[name=choice1]').on('click init-choice1', function() { $('#delivery').toggle($('#store').prop('checked')); }).trigger('init-choice1'); }); How can I add an animation to my _delivery_ div when the _choice1_ checkbox is checked ? Here an actual exemple of what result I have without animation : < Thanks in advance, ~Quentin
You can do, for example: $( document ).ready(function(){ $(function() { $('input[name=choice1]').on('click init-choice1', function() { if ($('#store').prop('checked')) $('#delivery').fadeIn(); else $('#delivery').fadeOut(); }).trigger('init-choice1'); }); }) or instead of the "if ..." simply: $('#delivery').fadeToggle(); This will show a little flicker at the beginnig so you youd have to add this style rule to prevent it: .two { display: none } Replace fadeIn/fadeOut with slideUp/slideDown for a different animation our use jQuery's animate() function to animate whatever CSS rule you want.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "javascript" }
How to modify ajax response before jsTree creation? How can I modify ajax response before jsTree creation? I would like to access each node ID and add prefix to it. On jsTree page the only clue is this: the function will receive two arguments - the node being loaded & a function". I need to do that before the tree is actually created, to avoid duplicate ID in the document. "json_data" : { "ajax" : { "type": "GET", "url" : "tree.json" }, "data" : function(node, func){ //how to use that? }} I have expected to get JSON data here, modify it and return? But this will explode.
I have successfully manipulated data using the success callback in the instantiation of the jsTree. In my case, I am parsing XML data returned as JSON from a .NET webmethod. It should work for your case in a similar manner. "ajax": { "type": "GET" "url": "tree.json", "success": function (x) { //manipulate string x to change id's here return x; }, ... Another method is to use the "complete" callback function to manipulate the jsTree in its final form. I don't recommend it in your case of duplicate id's, however.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "jstree" }
Box dimension, graphs and sum of functions Let $f,g:[0,1]\to{\mathbb R}$ be two continuous functions, Is it true that $dim_B(graph(f+g))\le \max\\{\dim_B(graph(f)),dim_B(graph(g))\\}$? It is well known (in Falconer book is an exercise) that this is even an equality if both dimensions are not equal. I am specially interested in the case that both dimensions are the same. It is trivial that, in this last case, $f+g$ can be zero (just take $g=-f$) or any Lipschitz function. So my more specific question is the next: If $f,g:[0,1]\to{\mathbb R}$ are continuous functions whose graphs have Box-dimension $s$, ¿Is $dim_B(graph(f+g))\le s$? Also interested, if possible, in lower and upper box-dimension.
Your first question appears as lemma 3.4 of my paper "The prevalent dimension of graphs". The proof states that this is a simple consequence of the inequality $$R_{f+g}[a,b] \leq R_f[a,b] + R_g[a,b] \leq 2\max\\{R_f[a,b],R_g[a,b]\\},$$ where $R_{f}[a,b] = \sup\\{|f(x) - f(y)|:a<x,y<b\\}$.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "real analysis, fractals, dimension theory analysis" }
How to determine if the current window is the active window? How can I tell if my window is the current active window? My current guess is to do GetForegroundWindow and compare the HWND with that of my window. Is there a better method than that? I'm using Win32 API / MFC.
Yes, that's the only way that I'm aware of. But you have to handle the fact that GFW can return NULL. Typically, this happens when another desktop (e.g. the screen saver desktop) is active. Note that use of a saver password can affect whether a different desktop is used (this is windows version-dependent and I can't remember the details of how different versions work). Also this code won't work properly in debug mode under Visual Studio, because you will get VS's window handle. Other than that everything's peachy :-)
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 10, "tags": "c++, windows, winapi, mfc" }
How re-order activities in android? I have a simple problem. In my app I have 3 activities A,B,C. Activity A is the main activity.On some action on activity A it takes to activity B and then after some action it goes to activity C. When I am at activity C, I pressed home button and the home screen came. Now when I click on the app icon again it starts activity C again. But I want the activity A should be coming as I have to ask the password. I want all the activities should be finished when I press home button and when I click app icon again the login activity i.e activity A should be coming. Can anybody give me some solution?
If your firing intent to go from one activity to another like this -----> Intent intent = new Intent(this, B.class); startActivity(intent); then add this thing to your code then all thing will get fine ----> addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) like this -----> Intent intent = new Intent(this, B.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivty(intent); NOTE---> here (this) means your A activity.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "android, authentication, android activity, homescreen" }
invoiced one company, got check from other company? how to rectify I've just asked the client how they want to deal with this, but... I invoiced one company (client is affiliated with several related organizations... didn't respond to my request to make sure I was invoicing right company/address) and got a check from another company (with different address). Suggestions on how to rectify so my records make sense?
**Talk to your accountant to get guidance with your problem.** If you don't have one, it is advisable to employ one. While accounting software indeed doesn't care, many tax authorities may. A country tag would be helpful. In many jurisdictions there are strict rules to follow when it comes to invoices. Invoicing one company and getting money from another (non invoiced) company may raise red flags (potential suspicion of money laundering or off the books work / contracts) or be seen as a separate income, requiring a separate invoice for that company. If the company sending the money is a parent or sister company there may be less issues but eyebrows most likely will be raised when your books are audited.
stackexchange-workplace
{ "answer_score": 5, "question_score": 0, "tags": "united states, freelancing, california, invoices" }