INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Add legend to sns.regplot and sns.lmplot I am new at seaborn and want to add a legend to this plot, I found unfortunalty nothing in this way. sns.lmplot(x="x", y="y4", data=data, order=2, scatter_kws={"s":5}, line_kws={"color": "red"}, ci=95) sns.regplot(x="x", y="y4", data=data, scatter_kws={"s":5}, line_kws={"color": "green"}, ) plt.show(); ![enter image description here]( I want following as a legend: blue points as `data`, green line as `y`, red line as `y^` How can I solve this?
I don't know how you generated the scatter plot. Probably using `plt.scatter`. But here is how you can change the legend for the `lmplot` and `regplot` as l = sns.lmplot(x="x", y="y4", data=data, order=2, scatter_kws={"s":5}, line_kws={"color": "red"}, ci=95) r = sns.regplot(x="x", y="y4", data=data, scatter_kws={"s":5}, line_kws={"color": "green"}, ) labels = ['y^', 'y'] l._legend.texts[0].set_text(labels[0]) r._legend.texts[0].set_text(labels[1]) Here, `l` and `r` return the plot instance and then you use the `_legend` to access the respective legends and `set_text` to rename the text of your choice.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, matplotlib, seaborn" }
Help me to prove that $|BA|\leq|B||A|$ holds Given the norm $|A|= \sqrt{tr(A^*A)}$, where $tr$ is the trace of a linear operator, help to prove that $|BA| \leq |B||A|$ holds.
Cauchy-Schwarz gives: $$ \begin{split} |BA|^2&=\mathrm{trace}((BA)^*(AB))=\sum_{i,j}|(BA)_{ij}|^2=\sum_{ij}\left|\sum_k b_{ik}a_{kj}\right|^2 \leq\sum_{ij}\left(\sum_k|b_{ik}|^2\sum_k|a_{kj}|^2\right) \\\&= \sum_{i,k}|b_{ik}|^2\sum_{j,k}|a_{jk}|^2=|B|^2|A|^2. \end{split} $$
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "linear algebra" }
What's the female equivalent of "suitor"? I'm looking for a word which could satisfy the usage of "suitor", except it would be used to indicate female "suitors": E.g.: > She had a host of suitors eagerly awaiting her favour... Now, I want a word that could fit in this sentence, except it would be about females: > _He_ had a bevy of ?????? eagerly awaiting _his_ favour...
I think one day the word for this will be _suitor_ , just as now _actresses_ are sometimes simply called _actors_. Until then, it seems that _female suitor_ is the most common phrase. This example is from a _New York Times_ book review of _An Available Man_: > He picks it up to hear the clamorous, intrusive voice of **a female suitor** , attempting to break in on his grief. But he’d rather iron the blouses of his deceased wife, Bee, “as a way of reconnecting with her when she was so irrevocably gone” than date any of the women now scurrying in his direction. Bee, on her deathbed, had predicted this fate: “Look at you. They’ll be crawling out of the woodwork.”
stackexchange-english
{ "answer_score": 19, "question_score": 23, "tags": "single word requests, nouns" }
Should my GLSL Shader object/wrapper encapsulate loading/setting a VertexArrayObject? I am working on a 2D game in C++, with a simple rendering layer over OpenGL. I have a wrapper for GLSL shaders and shader programs, these wrappers encapsulate shader objects into C++ classes and automatically handle loading/compiling/linking and using shader programs. VertexArrayObjects, it seems to me, are basically a collection of configuration settings to use with a particular ShaderProgram. My question is: Should I encapsulate VAO's within my ShaderProgram objects, or within the Sprite objects? Does a VAO change on a per-shader basis or do I need a new VAO for every type of drawable object? If the latter, do I need one VAO to draw all Sprites (each containing 4 vertices, a position/orientation etc), or one VAO per sprite object in the game?
No, you shouldn't attach the VAO to a Shader Program. The VAO has to be linked with a Vertex Buffer, which makes it somewhat not shareable. You can only share it to the same extent you would share a Vertex Buffer. Whereas a Shader Program is highly shareable (you may be able to render all objets with the same program). The purpose of the VAO is to reduce some API overhead when setting a Vertex Buffer and Vertex Format, so you can think of it as a container for a Vertex Buffer and its state. It is up to you how you want to lay it out on code, but my suggestion would be having 3 distinct classes: `VertexBuffer`, `VertexFormat` and `VAO`. Give a unique VAO to each mesh/model and then attach shared VertexBuffers and VertexFormats to them.
stackexchange-gamedev
{ "answer_score": 3, "question_score": 4, "tags": "opengl, c++, 2d, vao" }
Cut string from beginning of file and append to filename in Bash I want to cut a certain length of string from the start of my file and append it to my filename. Is there a one-liner that can do this for a whole directory of files? For example, I have the file 1.txt, with the following contents: `123456abcdefg12345678...` I want to rename the file to 1_123456.txt, and edit the contents to: `abcdefg12345678....` I have created a bash script to solve this problem, like so: for f in ./*; do a = $(head -c 8 $f) cut -c 9- > $f mv {,$a_}$f done But this doesn't do what it's supposed to do- the problem seems to be in the mv line. I would also appreciate it if a one-liner could also do the trick.
$ echo 123456abcdefg12345678 > 1.txt $ tail -c +7 1.txt > 1_$(head -c +6 1.txt).txt ; rm 1.txt . $ cat 1_123456.txt abcdefg12345678
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "bash" }
Get Non Indented string from Json Object I have a json object in c++. I am using json_cpp library. I want to get the string from the Json::Value object. I am using it like below. Json::Value obj; .... .... .... string str = obj.toStyledString(); This returns the string in the pretty print format. But I want the string without any indentation. How can I do that as there are no other functions provided in the class?
You could use `Json::FastWriter` it does not have any indentation and formatting since it outputs everything on a single line. it is normally not suitable for 'human' consumption. std::string toUnStyledString(const Json::Value& value) { Json::FastWriter writer; return writer.write( value ); } The function `toStyledString` also simply uses a `Json::StyledWriter` if you look into the definition of `Json::Value::toStyledString`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++, json" }
What are tax implications of being long and short stock at the same time? Let's assume that I am expecting a dip in a stock that I own. In such cases the usual strategy is to sell stock and buy back at a later date during the dip. However, this would trigger a taxable event and 1. reset my entry date that would have helped me to qualify for long term capital gains; AND 2. I would deleverage my position by paying taxes to IRS early (i.e. if I wanted to reenter later at the same price then I would be able to buy less shares compared to when I did not sell anything) **Instead, could I simply short the stock while still maintaining my long position and cover the short on the dip?** This seems like a better strategy unless I am missing some tax rules?
Entering a short position that offsets an existing long position is called _shorting against the box_. Since 1997, the US tax code has considered this as a _constructive sale_ of the long position, triggering a taxable capital gain if the long position has appreciated. > The purpose of the constructive sale rule is to prevent investors from locking in investment gains without paying capital gains and to limit their ability to transfer gains from one tax period to another.
stackexchange-money
{ "answer_score": 3, "question_score": 1, "tags": "united states, taxes, stocks, capital gains tax" }
Who is "The community team"? The answer stated: > The community team periodically looks at the work load... For me it's not clear who is **" community team"** for each particular SE site.
### It's not clear who is "community team" for each particular SE site. The current members of the community Team are listed here in this answer. I don't think they have specific responsibilities for particular sites. JNat is responsible for scheduling elections across all sites.
stackexchange-meta
{ "answer_score": 2, "question_score": 1, "tags": "support, election, community" }
Good open source Mac OSX App for code study? I'm rewriting my Mac OSX App (which is full of spaghetti code), but before I do so, I'd like to take some time and study an existing Mac OSX App. Is there something good available on github.com or elsewhere where I can learn good coding conventions? Specifically I'm looking for Mac app that makes use for CoreData, NSOutlineView, Bindings, etc. Thanks
Some places to start with: * Sample Code from the Apple Developer Website * Looking up the source code from an open-source program. Here's a list of open source programs from opensourcemac.org and another from Mac.AppStorm. Adium, Cyberduck, Vienna, Transmission are some solid apps I've used (though, not sure they make use of all of the features you've mentioned).
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 2, "tags": "macos, cocoa" }
How to highlight everything between a set of braces in Visual Studio I know there is always the old fashioned way of holding down the left mouse button and dragging down, but for instance is there a method similar to (and of course this doesn't actually do it but it **should** in my opinion) holding down left mouse button and pressing `CTRL`+`]`? What I'm trying to do is highlight many lines of code with the press of a button or 1 click.
If you put the cursor on on the left or right had side of a curly brace you can use `CTRL`+`SHIFT`+`]` to select all code in the block. It will also select the curly braces. This work using the opening or closing curly brace. I have tested this and it works with MSVS 2013 and MSVS 2015 As an added bonus if you use `CTRL`+`SHIFT`+`]` on an opening or closing parentheses it will select all code between and including the parentheses.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c++, visual studio" }
How can I compute the difference in Y-axis values between data sets with similar X-values I am new to _Mathematica_ , so this might be a very basic question; however, I cannot find a solution to this and it is taking me very long. For my research I am probing the photoluminescence response of a organic film with and without an external magnetic field, and also take a background measurement with and without the field. This generates large data files, with equal x values (wavelengths) and different y values (intensity) with dimensions `{3648, 2}`. I would like to `ListPlot` the difference between the data, but when I do something like this: Signal = WithMagnet - WithoutMagnet I end up with a vertical line at x=0. Can anyone here help me how to plot the difference in y-values while keeping the x-axis the same as in the individual files? Hope someone can help me with this! Cheers
Use `Part` to subtract intensity and `Transpose` to align with the wavelength data: wavelength = Range[350, 750, (400/3647)]; withMagnet = Transpose[{wavelength, RandomReal[1, 3648]}]; withoutMagnet = Transpose[{wavelength, RandomReal[1, 3648]}]; (*The above code just simulates your imported data*) diff = Transpose[{withoutMagnet[[All, 1]], withMagnet[[All, 2]] - withoutMagnet[[All, 2]]}]; ListLinePlot[diff, PlotRange -> All, Mesh -> All] ![enter image description here](
stackexchange-mathematica
{ "answer_score": 3, "question_score": 0, "tags": "plotting, matrix" }
Saving the PuTTY session logging I am using PuTTY for logging in to Solaris/Linux servers. Under Sessions → Logging, we see 'Session Logging' settings. I am not able to save the settings for permanent use. Isn't such feature available or am I wrong somewhere? PS: I want to save the log file path, 'All session output' as a 'forever setting'.
It works fine for me, but it's a little tricky :) * First open the PuTTY configuration. * Select the session (right part of the window, _Saved Sessions_ ) * Click `Load` (now you have loaded _Host Name_ , _Port_ and _Connection type_ ) * Then click _Logging_ (under _Session_ on the left) * Change whatever settings you want * Go back to _Session_ window and click the _Save_ button Now you have settings for this session set (every time you load session it will be logged).
stackexchange-stackoverflow
{ "answer_score": 26, "question_score": 26, "tags": "putty" }
python pandas DataFrame - assign a list to multiple cells I have a DataFrame like name col1 col2 a aa 123 a bb 123 b aa 234 and a list [1, 2, 3] I want to replace the col2 of every row with col1 = 'aa' with the list like name col1 col2 a aa [1, 2, 3] a bb 123 b aa [1, 2, 3] I tried something like df.loc[df[col1] == 'aa', col2] = [1, 2, 3] but it gives me the error: ValueError: could not broadcast input array from shape (xx,) into shape (yy,) How should I get around this?
import pandas as pd df = pd.DataFrame({"name":["a","a","b"],"col1":["aa","bb","aa"],"col2":[123,123,234]}) l = [1,2,3] df["col2"] = df.apply(lambda x: l if x.col1 == "aa" else x.col2, axis =1) df
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 7, "tags": "python, pandas, dataframe, valueerror" }
Как вставить изображение иконки по центру ячейки в библиотеке phpexcel? Когда я выполняю такой код: foreach ($statuses as $status) { $statusDrawing = new PHPExcel_Worksheet_Drawing(); $statusDrawing->setName($status['id']); $statusDrawing->setDescription($status['description']); $statusDrawing->setPath(APP_PATH . 'modules/experiment/_img/status/' . $status['id'] . '.png'); $statusDrawing->setWorksheet($firstWorksheet); $statusDrawing->setCoordinates('B' . $startRow); $statusDrawing->setOffsetX($offsetX); $offsetX += 15; } То картинка по мере увеличения строк уходит за пределы строк, к которой они были привязаны. По координатам X все нормально. Размер картинки `14x14px`. Размер строки примерно `10px`. Подгоном и уменьшением размера картинок проблема не решается.
Проблема актуальна не только для позиции Y, но и для позиции X. Толчком к решению стало правильное расположение по ординате X. Итак, в код я не заглядывал, но полагаю что моя идея верна: Библиотека использует размеры строки и ячейки по умолчанию. Для того, чтобы корректно указать позицию элемента, надо всем предшествующим ячейкам задать размеры, тогда позиция определяется корректно. В моем случае, мне необходимо было добавить следующий код: //необходимая операция дл вычисления вертикального положения ячейки $firstWorksheet->getRowDimension($startRow)->setRowHeight(12); П.С.: Вот поэтому по оси X подсчиталось правильно, так как я для каждого столбца задвал размеры. Для тех, кто любит все оптимизировать, придется поднять картинки в максимально приближенную ячейку к левому верхнему углу, так как после картинок не стоит уже задавать размеры ячейкам так строго. Буду считать свой ответ верным наличием более трех лайков.
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "phpexcel, php, excel" }
Notification icons template for Android? Is there any tutorial about how to design a good icon to put in the status bar as a notification in an Android App? Ideally I'm looking for a template or an icon that I can easily modify. I'm not a designer. I need smiley faces status bar icons.
You can download icons from the buzzbox sdk resources page: < there is also a photoshop file you can download and modify. There is also one simple status bar template icon in the official template pack from Android <
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "android, icons, notifications" }
Hosting Ghost blog without NginX or Apache I've decided to take the plunge and make my next blog in Ghost 0.4.1 rather than Wordpress. My client has a VERY small amount of traffic, and it is easy to say that they will never need to be load balanced across multiple servers. **My question is:** Ghost can be configured to listen to a certain port, so can I use it as my web server listening to port 80? Is there a problem to doing this? **Followup Question:** Every example shows hosting it with Apache or NginX, is there a security or performance reason for this? Thanks in advance!
You definitely can run Ghost on port 80 but it is recommended to run Ghost on port 2368 and proxy requests through Apache or Nginx. You can checkout this article for an example of how to install Ghost and run it on port 80. But I would highly recommend reading through this article and proxying requests through Nginx. With Ghost running on port 2368 you can use a low privileged user to start Ghost and therefore will not have to use a higher privileged user to start Ghost.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "node.js, apache, nginx, ghost blog" }
How prevent to auto change view of a folder icons in windows 7 In my windows 7 i want to set all folders view to **list**. So i opened explorer and went to > Tools -> Folder Options -> View and pressed **Reset Folders** button and ok button. After reset i went back to current folder and changed it's view to **list**. After that i went back to > Tools -> Folder Options -> View and this time i pressed **Apply To Folders** button and ok button. Ok, now i have all my folders in list mode view. I have some folders in my desktop and and want to change their icons view to **Medium icons** and here is my problem. when i change their view to Medium icons, it changes back to list automatically! How can i keep those folders in Medium icons view? Thanks in advance
This worked for me. Highlight the folder(s)--right click on a highlighted folder--open properties--click the customize tab--select optimize this folder for pictures--click apply this template to all subfolders--click apply. Hope this works for you.
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "windows 7, icons" }
Can't sign in to the Apache Tomcat Version 8.5.75 I have previously installed some older Apache Tomcat. I have already removed they completely(how to remove it) and reinstall the Apache Tomcat 8.5 . Now when I try to type ` and try to log in , It doesn't give me to login even I give the correct username and password. this is my 'tomcat-users.xml' <tomcat-users xmlns=" xmlns:xsi=" xsi:schemaLocation=" tomcat-users.xsd" version="1.0"> <user username="admin" password="admin" roles="manager-gui" /> LogIn image help me to fix it
I changed port number from 8080 t0 8081 and it worked. Go to apache tomcat installation directory and find conf directory in my pc it is ` C:\Program Files\Apache Software Foundation\Tomcat 10.0\conf` Now open the server.xml and change the port number to 8081 and save. <Connector port="8081" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> Now restart the apache tomcat server.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "authentication, tomcat" }
why 'Windows.UI.Xaml.Markup.XamlParseException' happens when XAML is valid An exception of type 'Windows.UI.Xaml.Markup.XamlParseException' occurred in myproj.UWP.McgInterop.dll but was not handled in user code Additional information: The text associated with this error code could not be found. Cannot find a Resource with the Name/Key category [Line: 0 Position: 0]
You are setting the resource key either from `Page.Resources`/`App.Resources` or Standard `Resources` that has a spelling mistake. Check where you are setting the resources and make sure the spelling is correct. Unfortunately XAML Designer does not show squiggly error when the spelling of resource is incorrect
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "xaml, xamarin, uwp, xamarin.uwp" }
The probability of at least two A box with 15 spare parts for a type of machine contains 10 in good condition and 5 defective. Three parts are drawn randomly without replacement. ¿What is the probability that there are at least two in good condition?
In order to get at least two spare parts in good condition, one must pick two or three spare parts in good condition. The probability of first selecting two parts in good condition, and then one in bad condition, equals: $$\frac{10}{15} \cdot \frac{9}{14} \cdot \frac{5}{13}$$ Since there are three ways to select the spare part in bad condition (on the first, on the second and on the third turn), the total probability equals: $$\frac{5}{15} \cdot \frac{10}{14} \cdot \frac{9}{13} + \frac{10}{15} \cdot \frac{5}{14} \cdot \frac{9}{13} + \frac{10}{15} \cdot \frac{9}{14} \cdot \frac{5}{13} = \frac{1350}{2730}$$ The probability of selecting three spare parts in good condition equals: $$\frac{10}{15} \cdot \frac{9}{14} \cdot \frac{8}{13} = \frac{720}{2730}$$ Adding this all up, we get: $$\frac{1350}{2730} + \frac{720}{2730} = \frac{2070}{2730} \approx 0.758$$
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "probability, probability theory" }
Converting a Bitmap image to a matrix In C#, I need to convert an image that I have already converted to Bitmap in to a matrix of the size of the image's width and height that consists of the uint8 of the Bitmap data. In another word placing the Bitmap data inside of a matrix and converting them to uint8, so I can do the calculations that I am intended to do on the matrix rows and column.
Try something like this: public Color[][] GetBitMapColorMatrix(string bitmapFilePath) { bitmapFilePath = @"C:\9673780.jpg"; Bitmap b1 = new Bitmap(bitmapFilePath); int hight = b1.Height; int width = b1.Width; Color[][] colorMatrix = new Color[width][]; for (int i = 0; i < width; i++) { colorMatrix[i] = new Color[hight]; for (int j = 0; j < hight; j++) { colorMatrix[i][j] = b1.GetPixel(i, j); } } return colorMatrix; }
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 6, "tags": "c#, matrix, bitmap" }
operator keyword in Xcode I'm facing a problem in Xcode with the `operator` keyword. I have this in a header file (.h) but Xcode recognizes it as a keyword due to operator overloding in C++, even though I'm setting the file type as a default C header and not C++ header. The code I'm trying to compile is all written in C and the line of code i'm having problem is like this struct foo { int a; int b; ... char operator[80]; } I'm stuck with this a while now. The reason for the operator to be used as a variable name is not in scope now becouse this is a cross plataform code that I can't change and is compilable in many other plataforms for low-level devices. Any help will be appreciated.
How about if you used the pre-processor: #define operator _operator ? Put the above in a header file that is read in before your header.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "iphone, xcode, operator keyword, c99, keyword" }
Azure Databricks Cluster Questions I am new to azure and am trying to understand the below things. It would be helpful if anyone can share their knowledge on this. 1. Can the table be created in Cluster A be accessed in Cluster B if Cluster A is down? 2. What is the connection between the cluster and the data in the tables? ![enter image description here](
You need to have running process (cluster) to be able to access metastore, and read data, because data is stored in the customer's location, not directly accessible from the control plane that runs UI. When you wrote data into table, then this data should be available in other cluster in following conditions: * the both clusters are using the same metastore * user has correct permissions (could be enforced via Table ACLs)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "databricks, azure databricks" }
ServiceStack AutoQuery ordering I am using AutoQuery which makes writing services very simple. One of my queries needs to order descending by value X and then ascending by value Y. It appears that in AutoQuery you can order everything ascending or descending but not a combination. To get around this I added custom properties to indicate my states something like this: // Custom fields to determine sort order public bool? IsState1 { get; set; } public bool? IsState2 { get; set; } This does work however I was wondering if it was possible to do this natively.
AutoQuery lets you specify multiple Order By's where you can sort in reverse order by prepending a `-` before the field name, e.g: ?orderBy=X,-Y
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "servicestack" }
Formatting error with source code on WordPress.com? I've been trying to post some Java code to my blog, but it seems like it has some problems with the formatting. First, whenever I copy/paste code into the editor, it's pasted as pre-formatted, which means that it converts the indents to spaces, all on a single line. And when I try to separate the lines by making each line of code on a single physical line, it doesn't indent them automatically. I'm using the visual editor, and I've checked the HTML code, and nothing seems to be wrong with it. What am I doing wrong? Or is this a bug I should report to WordPress?
Paste the code in the HTML editor, it probably won't try to convert indents and linebreaks. Surround it with the `[sourcecode]` shortcode and only then return to the visual editor.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wordpress.com hosting, code, formatting" }
Reading an Image file on FPGA for processing I am trying to implement image processing on FPGA. I need to have an image for testing my module. I tested the module for single bit, by just generating a pixel value on test bench, but would want to see the result on a whole image. Is there a way to load an image file to an fpga for processing?
If you're doing something simple to the image that only involves one pixel at a time (the values of neighboring pixels don't matter), then you might as well do it in software, because the time that it takes is going to be dominated by the I/O, not the processing. The speed of the FPGA has no advantage here. On the other hand, if you do eventually want to do more complex operations, then the question is too broad to be answered here. Generally speaking, small to medium range FPGAs do not have enough on-chip memory to store an entire image at once. Anything that requires a "frame buffer" is usually going to require off-chip memory, such as an SDRAM chip, and the on-chip memories will be used as line buffers during the processing.
stackexchange-electronics
{ "answer_score": 2, "question_score": 1, "tags": "fpga" }
splitting first and last name regex Hello I have a string of full names. string='Christof KochJonathan HarelMoran CerfWolfgang Einhaeuser' I would like to split it by first and last name to have an output like this ['Christof Koch', 'Jonathan Harel', 'Moran Cerf', 'Wolfgang Einhaeuser'] I tried using this code: splitted = re.sub('([A-Z][a-z]+)', r' \1', re.sub('([A-Z]+)', r' \1', string)) that returns this result ['Christof', 'Koch', 'Jonathan', 'Harel', 'Moran', 'Cerf', 'Wolfgang', 'Einhaeuser'] I would like to have each full name as an item. Any suggestions? Thanks
It'll most likely have FP and TN, yet maybe OK to start with: [A-Z][^A-Z\r\n]*\s+[A-Z][^A-Z\r\n]* ### Test import re expression = r"[A-Z][^A-Z]*\s+[A-Z][^A-Z]*" string = """ Christof KochJonathan HarelMoran CerfWolfgang Einhaeuser """ print(re.findall(expression, string)) ### Output ['Christof Koch', 'Jonathan Harel', 'Moran Cerf', 'Wolfgang Einhaeuser'] * * * > If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs. * * *
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, regex" }
How to change constraints programmatically that is added from storyboard? I have one screen. It will display like below ![enter image description here]( Now When User clicked I have an Account and Password(button) it will display like below ![enter image description here]( I want to move both views accordingly I added constraints using storyboard.Now need to change constraints from programming..
You need to create an IBOutlet of your constraint. ![enter image description here]( Then you set the constant value of your constraint in code: labelWidthConstraint.constant = newValue If you want it animated you can do something like this: # Swift labelWidthConstraint.constant = newValue UIView.animate(withDuration: 0.3, animations: { self.view.layoutIfNeeded() }) # Objective-C self.labelWidthConstraint.constant = newValue; [UIView animateWithDuration:0.3 animations:^{ [self.view layoutIfNeeded]; }];
stackexchange-stackoverflow
{ "answer_score": 58, "question_score": 33, "tags": "ios, objective c, xcode storyboard" }
iPhone calendar: How do you set up an event for next year? I want to set up a reminder for 1 Aug 2021, but there's no way to set the year. All I can do on the scrolling wheel of dates is set it up for this 1 Aug 2020 and add a "repeat annually" to the entry. Surely Apple haven't missed this off?
In Calendar switch on All-Day, then you can chose the year easily. In Reminder the year switch is shown by default. ![calender all day](
stackexchange-apple
{ "answer_score": 0, "question_score": 1, "tags": "iphone, applications, calendar" }
Knockoutjs customBinding text base on language In all my models i have at least 2 Observable properties that i use for language (display base on it) this.id = data.id; this.DataNameEn = ko.protectedObservable(cuberryItem.DataNameEn);//this prop ends with En this.DataNameDe = ko.protectedObservable(cuberryItem.DataNameDe);//this prop ends with De this.DataValue = ko.protectedObservable(cuberryItem.DataValue); I need to create a custom binding so when some global variable example is 'en' than will be display the **DataNameEn** when other language then **DataNameDe** , first i did try it with computed but it don't fill right to do it for every ViewModel. How can i archive this with bindings or is better to leave with computed observable. THX
I would go with the computed observable, if you dont want to do it for all your models then you can use inheritance, and create a class named like Localizable and then all your viewmodels would inherit from this class. Here is an article on using inheritance using jquery < however if you have decent javascript knowledge you should better do it without jquery.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, knockout 2.0, knockout mvc" }
Why two ENIs by default in EKS? When I create an EKS cluster I see that worker nodes have two ENIs, eth0 and eth1. Does EKS require two ENIs for its functionality ? Or two ENIs are added to provide more IPs for the pods (using default AWS CNI) ?
By default EKS uses `aws-vpc-cni-k8s` to allocate IP addresses for pods. The default settings for the CNI plugin is `WARM_ENI_TARGET=1` which will ensure you have an additional ENI available for future assignment. Your addresses will be assigned to the first ENI until the max IPs per ENI for the instance type is exhausted, then allocations will come from the second ENI. Once an IP address is assigned to the second ENI a third ENI will be allocated according to the `WARM_ENI_TARGET` setting. It will continue to allocate additional ENIs as you use addresses until you reach the maximum number of ENIs for the instance type.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 8, "tags": "kubernetes, amazon eks" }
how to move to the end of current cell? in org mode table. I have a cell with many words, and and to append more words to the end. But how to quick move to the end of current cell?
The function `org-forward-sentence` is bound to `M-e`. When inside a table, it will jump to the end of the current field (calling `org-table-end-of-field` as @JeanPierre noted in his answer). All table related keybindings are listed in the manual.
stackexchange-emacs
{ "answer_score": 3, "question_score": 0, "tags": "org mode, org table" }
How do I resolve this " No such property [target] in org.apache.log4j.FileAppender" and "No output stream or file set for the appender named" error? I managed to get log4J with ConsoleAppender to work in Eclipse, but when I change the appender to be FileAppender then I get these red error messages coming out(even though I altered the properties file as directed by this tutorial) : log4j:WARN No such property [target] in org.apache.log4j.FileAppender. log4j:WARN File option not set for appender [file]. log4j:WARN Are you using FileAppender instead of ConsoleAppender? log4j:ERROR No output stream or file set for the appender named [file]. Here is a pic!enter image description here Thank You Very Much
As the error is trying to tell you, `FileAppender` has a `File` option, not a `Target` option.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "eclipse, log4j, slf4j" }
Prefetching double class member requires casting to char*? I have a class which I am using `_mm_prefetch()` to pre-request the cacheline containing a class member, of type double: class MyClass{ double getDouble(){ return dbl; } //other members double dbl; //other members }; `_mm_prefetch()` signature is: void _mm_prefetch (char const* p, int i) But when I do: _mm_prefetch((char*)(myOb.getDouble()), _MM_HINT_T0); GCC complains: > error: invalid cast from type 'double' to type 'char*' So how do I prefetch this class member?
If you read the description for `_mm_prefetch()` from the site you linked to it has : void _mm_prefetch (char const* p, int i) > Fetch the line of data from memory that contains address p to a location in the cache heirarchy specified by the locality hint i. So you need to pass the address of the variable that you want. In order for you to do that you need to pass to the function either the address of a reference to the class member or a pointer to it. The simplest solution woul be to change `getDouble()` to return a reference and then you can use: _mm_prefetch((char*)(&myOb.getDouble()), _MM_HINT_T0);
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "c++, performance, optimization, x86, prefetch" }
value always undefined when I set it in promise angular typescript I have a function getData() in accountService.ts. I'm trying to get user data and user account data together in zip promise. Resolve works correctly and I get the correct data, but when I try to set these local variables to the returned values, they are always undefined. I want to set them to use them in other functions. getData(){ zip(this.getUser(), this.getAccount()).toPromise().then(data =>{ this.user = data.values[0]; console.log(this.user); this.account = data.values[1]; resolve(data.values[0],data.values[1]); }); } I use Angular 8 with typescript. Thanks
Your function `getData()` seems to return no values. I would follow the below approach getData(){ return zip(this.getUser(), this.getAccount()).pipe( tap(data => { this.user = data.values[0]; this.account = data.values[1]; }), map(({user, account}) => ({user, account})) ) } Now we are returning an `Observable<{user: any, account: any}>`. In the component where this function is used we can access the values using `subscribe` ngOnInit() { this.accountService.getData().subscribe({ next: data => { // access account using data.account and user using data.user } }) }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "angular, typescript, angular8" }
If $\alpha,\beta,\gamma$ are the roots of $x^3+x^2-x+1=0$, find the value of $\prod\left(\frac1{\alpha^3}+\frac1{\beta^3}-\frac1{\gamma^3}\right)$ > If $\alpha,\beta,\gamma$ are the roots of the equation $x^3+x^2-x+1=0$, find the value of $\prod\left(\frac1{\alpha^3}+\frac1{\beta^3}-\frac1{\gamma^3}\right)$ **My Attempt:** $\alpha+\beta+\gamma=-1$ $\alpha\beta+\beta\gamma+\gamma\alpha=-1$ $\alpha\beta\gamma=-1$ $\prod\left(\frac1{\alpha^3}+\frac1{\beta^3}-\frac1{\gamma^3}\right)=\prod\left(\frac{(\beta\gamma)^3+(\alpha\gamma)^3-(\alpha\beta)^3}{(\alpha\beta\gamma)^3}\right)=-\prod\left((\beta\gamma)^3+(\alpha\gamma)^3-(\alpha\beta)^3\right)$ Now, one option is to expand the product and put the values where required, but is there a shorter, better approach to do this?
**1.** Let $P(x) = x^3 + x^2 - x + 1$. Since all the zeros of $P(x)$ are non-zero, $\gcd(P(x), x^3) = 1$. Then the Bézout's identity tells that we can find polynomials $A(x)$ and $B(x)$ satisfying $$ A(x) P(x) + B(x) x^3 = 1. $$ Although there is a systematic way of determining $A(x)$ and $B(x)$, called the extended GCD algorithm, it is not hard to see that $A(x) = x+1$ and $B(x) = -x-2$ from the computation $$ (x+1)(x^2 - x + 1) = x^3 + 1 \qquad\implies\qquad (x+1)P(x) = x^4 + 2x^3 + 1. $$ The upshot of this computation is that, if $x = x_0$ is any zero of $P(x) = 0$, then $$ B(x_0) x_0^3 = 1 \qquad\text{and hence}\qquad \frac{1}{x_0^3} = B(x_0) = -x_0-2. $$ **2.** Plugging this to OP's product, we get $$ \prod_{\text{cyc}} \left( \frac{1}{\alpha^3} + \frac{1}{\beta^3} - \frac{1}{\gamma^3} \right) = \prod_{\text{cyc}} \left( -\alpha -\beta + \gamma - 2 \right) = \prod_{\text{cyc}} \left(2\gamma - 1\right) = (-2)^3 P\left(\frac{1}{2}\right) = -7. $$
stackexchange-math
{ "answer_score": 7, "question_score": 3, "tags": "polynomials, roots, products, cubics" }
global variable in controller laravel 5.3 How can definition a global variable for use in all function controller class TestController extends Controller { private $x; public function index() { $this->$x ='22'; } public function send_message() { echo $this->$x; } }
Write `$this->x` rather than `$this->$x` class TestController extends Controller { private $x; public function index() { $this->x ='22'; } public function send_message() { echo $this->x; } }
stackexchange-stackoverflow
{ "answer_score": 42, "question_score": 6, "tags": "laravel 5.3" }
Help me evaluate $\int \arccos(\frac{x^3-3x}{2})dx$ I need to solve $\int \arccos(\frac{x^3-3x}{2})dx$. I tried integration by parts by adding an $x'$, but it didn't work. I also tried a change of variable with $\cos(t) = \frac{x^3-3x}{2}$, but that didn't get anywhere either. Could you point me in the right direction?
integrate by parts: Let $f=\arccos\left(\frac{x^3 - 3x}{2}\right)$, $g'=1$. Then $g=x$ and $$f'= -\frac{3(x^2-1)}{2\sqrt{1-\frac{1}{4}(x^3-3x)^2}}.$$ Thus $$\begin{align*} \int fg'~dx & = x\arccos\left(\frac{x^3 - 3x}{2}\right) + \int\frac{3x^3-3x}{2\sqrt{1-\frac{1}{4}(x^3-3x)^2}}~dx \\\ &= x\arccos\left(\frac{x^3 - 3x}{2}\right) + \int\frac{3x(x^2-1)}{\sqrt{4-(x^3-3x)^2}}~dx \\\ \end{align*}$$ At this point you note that $$4-(x^3-3x)^2 = -(x^2-1)^2(x^2-4).$$ Can you take if from here?
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "calculus, integration" }
C++ bitset in CUDA I have an existing C++ code that extensively uses the bitset template. I am porting this code to CUDA C, and I am really new to CUDA programming. Can I use the bitset template as a " **shared** " variable?
As far as I know, you can't use the `bitset` container in CUDA at all, because there is no device implementation of it. It should be trivial to implement it in terms of a regular array though, and you can put the array in shared memory.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "cuda, gpu, shared, bitset" }
Workflow 4 runtime compiling In WF 4, is there a way to compile XAML at runtime? In WF 3.5 you were able to do this via WorkflowCompiler Is there something similar in WF 4?
You can in fact load an run XAML at runtime. Here are a couple links. But let's be clear that it's not compiling it -- it's interpreting it -- because that's how XAML works. * Walkthrough * Video by Ron Jacobs Let me know if you have any questions!
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": ".net, workflow foundation 4" }
"Hooks" in MVC3 I'm working on a MVC3 project using C#, I was wondering if MVC3 has something similar to hooks in CodeIgniter (for executing code just before each ActionResult executes). I need it to update an arraylist of visited websites in the session. EDIT: I've worked out a solution using an ActionResult, I'll post it here for reference. **ActionFilter:** public class HistoryTracker : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { // code here } } **Global.asax.cs** protected void Application_Start() { // ... GlobalFilters.Filters.Add(new HistoryTracker()); } This makes the ActionFilter always trigger.
You are looking for ActionFilters.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "c#, codeigniter, asp.net mvc 3" }
Excel Help: How to scan a row and return the value of the first cell in that column I have a matrix of numbers and the matrix has column header -- say like this: a b c d e f 0 0 0 1 0 0 0 0 1 0 0 0 What I want to do is to search for each row for the element 1 and return its column header. For example if I scan the first row, I should return 'd'. Similarly if I scan the second row, I should return 'c'. Which combination of formula works good here?
a b c d e f 0 0 0 1 0 0 d =INDEX($A$3:$F$3,1,MATCH(1,A4:F4,0)) 0 0 1 0 0 0 c =INDEX($A$3:$F$3,1,MATCH(1,A5:F5,0)) Trust this helps
stackexchange-superuser
{ "answer_score": 3, "question_score": 2, "tags": "microsoft excel, microsoft excel 2010, worksheet function, macros, microsoft excel 2013" }
mutual information inequality in triangle I want to prove the following inequality (It should be true): A,B,C are independent random variables and U is given by a law $P_{UABC}=P_{ABC}\cdot P_{U|ABC}$. Then: $$ I(U;BC)+I(U;CA)+I(U;AB)\leq 2I(U;ABC)$$ I guess it is not that difficult to prove, and I guess the proof is by step: First bound $I(U;CA)+I(U;AB)$ with ..., then bound $I(U;BC)+...$, then bound with what we want (this intuition comes from the proof of an equivalent problem, where we have those 3 steps and which is not really difficult). But as I'm not used to mutual info, I don't know how to do this...
Remember that if you're not used to mutual information, you can always just deal with entropies, since $I(X;Y) = H(X) - H(X|Y)$. I'll use this method below. Okay, we want to exploit the independence of $A,B,C,$ since that's the only information we have. Recall that for independent $X,Y, H(X,Y) = H(X) + H(Y)$. To utilise this, we'll open up each $I(U;\cdot)$ as $H(\cdot) - H(\cdot|U)$. On doing this and repeatedly utilising the additivity of entropy for independent random variables, the required inequality is equivalent to \begin{align} 2H(ABC|U) &\overset{?}{\le} H(AB|U) + H(BC|U) + H(CA|U) \\\\\iff H(C|UAB) + H(A|UBC) &\overset{?}{\le} H(C|U) + H(A|UC) \end{align} where in the second line we've used the chain rule $H(ABC|U) = H(AB|U) + H(C|ABU)$ and other similar expressions. Now note that the final inequality holds, since conditioning reduces entropy, and so $H(C|UAB) \le H(C|U)$ and $H(A|UBC) \le H(A|UC)$.
stackexchange-math
{ "answer_score": 1, "question_score": 3, "tags": "information theory" }
base64 decryption I am currently trying to decode a base64 encrypted PHP file , but without any luck. Could someone be able to help? < Thanks
One extremely simple script < 278 runs later (about 2 minutes) - the original file - <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, base64" }
How do you position list item bullets inside a list? You will see that the numbers/bullets generated by my HTML make the elements at the left look ugly < I am trying to use margin and padding at my CSS neither works. Help. I want the numbers to show at least 5px from the left of the image.
Add `list-style-position: inside` to your `ol` tag in your CSS stylesheet
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "html, css" }
Cloud Foundry / Bluemix load balancing I know that by default, Bluemix / Cloud Foundry use round-robin load balancing. Is there a way to change that? If I deploy 2 apps with the same route, and want 90% of my traffic to go to blue, and 10% to green, is that possible?
You would have to deploy more than two instances of the app to have better than 50-50 control over who sees what. If you have 10 instances, for example, and you update 1, then you could get your 90-10 split. Check out this CF CLI plugin: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "load balancing, cloud foundry, ibm cloud" }
Query to display Propernoun using SPARQL over dbpedia How to display all propernoun like Manchester_United_F_C., Arsenel_FC, United_States using SPARQL over DBpedia ?
If you want to display _all_ propernouns from DBpedia _and only_ propernouns, you'll have to manually select the labels that correspond to proper noun and filter out those that don't. Start with this query: SELECT DISTINCT ?label WHERE { ?s rdfs:label ?label . } There are 21,695,594 triples matching this triple pattern, so good luck to figure out which are propernouns, which are not.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "sparql, semantic web, ontology, dbpedia" }
Getting value from other parallel object I have object with 2 objects inside : o = { center : { x:1, y:1 }, startPosition : {x:center.x, y:center.y} } And of course I have an error : ReferenceError: center is not defined How to get value of center inside startPosition?
Try this o = { center : { x:1, y:1 } } o.startPosition = {x:o.center.x, y:o.center.y}
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "javascript, object" }
Do you need a shell program for Proxy Forwarding? I am trying to set up a secure proxy for my work. This article suggests using SSH Tunnel + SOCKS Proxy Forwarding. Do I need to have access to a certain shell program on the server? I have `bash`, `tcsh`, and `zsh` available.
If the server does have direct access to the internet ssh is all you need. Using the example of the linked article just put localhost port 9999 to your browser's proxy settings and everything is fine. Another option would be to install an HTTP Proxy server and to use ssh only for portforwarding. E.g. that you local port 8080 is forwarded to the server port 8080 on which a http proxy server is listening.
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 0, "tags": "ssh, xubuntu, socks5" }
How to port Python slicing assignment syntax to JavaScript/TypeScript? I am trying to rewrite a Python library to TypeScript. I am having trouble porting this line from this repository.: is_prime[start - segment_min::pk] = repeat(False, len(range(start - segment_min, segment_len, pk))) I know it's Python slicing assignment, but don't know how to port it to JS/TS. How do I do this in JavaScript/Typescript?
A simple slicing assignment `target[t_start:t_end] = source[s_start:s_end]` can be achieved in JS using a combination of the `splice` and `slice` Array methods: target.splice(tStart, tEnd-tStart, ...source.slice(sStart, sEnd)); However, JavaScript does not support a `step` slicing, for that you'll have to write a loop yourself.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "javascript, typescript" }
Create a "complex" background in CSS ![enter image description here]( I would like to know if it is possible to create a background like this in CSS3. The background should span a header div and the gradient should go from white to black independent of the screen width (always white on the left side and black on the right side). Reason for not using the image is that it takes longer to load and that I can't get it to resize it's width when making the browser smaller than 1920px (the width of the image). Have tried linear-gradient but I can't get it to work... Regards, Jens
If you also want the black bar at the top you should give dimensions to the background, stop the repeating and also position it where you want ( _treat it like a normal background image_ ) div { background-color: black; background-image: linear-gradient(to right, white, black); background-repeat:no-repeat; background-size:100% 20px; /*full width, 20px height*/ background-position:0 100%; /*gradient at bottom*/ /*just to give size to demo*/ min-height:50px; } <div></div>
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "html, css" }
Generalized project euler #4 I tried some basic optimizations, to cut down on the number of operations for the general euler problem #4: def is_palindrome(num): return str(num) == str(num)[::-1] def fn(n): max_palindrome = 1 for x in range(n,1,-1): for y in range(n,x-1,-1): if is_palindrome(x*y) and x*y > max_palindrome: max_palindrome = x*y elif x * y < max_palindrome: break return max_palindrome print fn(999) Can I/how do I optimize this further? (assume it's the general solution, for factors of at most n rather than at most 999).
Some small optimizations: you can break out early of the `x`-loop and reduce the number of calls to `is_palindrome` by swapping the checks around a bit (untested): def fn(n): max_palindrome = 1 for x in range(n,1,-1): if x * n <= max_palindrome: # nothing bigger possible for remaining x break for y in range(n,x-1,-1): if x * y <= max_palindrome: #nothing bigger possible for current x break if is_palindrome(x*y): max_palindrome = x*y return max_palindrome
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python" }
Java: Why can't I insert parameter instead of %s? I have a structure as this: String xml = "<tag><another_tag>%s</another_tag></tag>" and I pass a parameter to method and try to replace `%s`: String str = String.format(xml, parameter); But I have got previous xml file wrapped as a tag on the place of '%s'. If I set a simple `String`: String str = String.format(xml, "parameter"); all works well. Why does it happen?
As Pshemo says, this works fine: String xml = "<tag><another_tag>%s</another_tag></tag>"; String parameter = "abc"; String str = String.format(xml, parameter); System.out.println(str); // <tag><another_tag>abc</another_tag></tag>
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java" }
Code::Blocks: g++ not found Recently I have installed Code::Blocks IDE on my Ubuntu 12.10. The following error appears when I try to run or compile any code written in there: Compiling: /home/sabbir/first.cpp /bin/sh: 1: g++: not found Process terminated with status 127 (0 minutes, 0 seconds) 0 errors, 0 warnings How can I solve this problem?
Most likely you are simply missing a compiler. Get one by installing `build-essential` package. Typing `sudo apt-get install build-essential` into terminal is one of the easiest ways to achieve that.
stackexchange-askubuntu
{ "answer_score": 17, "question_score": 8, "tags": "compiling, c++, code blocks" }
I'm trying to use <a> tag on an array <div class="shared-by-list" ng-show="dashpost.showPostSharedByList"> <span><small><strong><em>Shared by: </em></strong></small></span> <span><small>{{dashpost.postSharedByList}}</small></span> </div> In the above code `dashpost.postSharedByList` is an array of names who shared that particular post. I have to include an `<a>` tag with `href` pointing to that specific profile. The problem is the hyperlink is applied to all the names in the array. I want different links for different elements in the array. Please help!
<div class="shared-by-list" ng-show="dashpost.showPostSharedByList"> <div ng-repeat="postSharedBy in dashpost.postSharedByList"> <span><small><strong><em>Shared by: </em></strong></small></span> <span><small><a ng-href="#/profile/{{postSharedBy}}">{{postSharedBy}}</a></small></span> </div> </div> It would be better if the list would contain objects structured like so: {name: "element name", anchorname: "element anchor" } Anyway it is up to you the choice.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "angularjs, anchor" }
Получить количество подписчиков страницы в facebook Пытаюсь получить количество подписчиков страницы тамким способом... public function getSubFb( $echo = false) { $page_id = ' '; $xml = @simplexml_load_file(" . $page_id . "") or die ("a lot"); $likes = $xml->page->fan_count; if ($echo == true) { echo $likes; } else { return $likes; } } Не получается. Подскажите как правильно это сделать?
Здесь всё написано в принципе: < Надо поставить PHP SDK фейсбука /* PHP SDK v5.0.0 */ /* make the API call */ $request = new FacebookRequest( $session, 'GET', '/{group-id}' ); $response = $request->execute(); $graphObject = $response->getGraphObject(); /* handle the result */
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, facebook api" }
Hector API - Create Column Family - key validation class Hey guys I am trying to load a schema into a Cassandra 0.8.2 database via Hector. I want to add a column family (in a particular keyspace) & specify its name, comparator type, key validation class, and default validation class via Hector. I've looked through the documentation here: < for the function that to do this, but it seems I must have the Column Family already created (via the Cassandra CLI) to specify the default validation class, & key validation class when creating the Column Family via the CLI. Am I correct in this assumption? Am I missing any methods? Is it possible to alter the default validation class & key validation class of a Cassandra column family via Hector?
You can do that with hector. There is an example in CassandraClusterTest where you can see new column families being created with the validation class set. There are methods on BasicColumnFamilyDefinition to set the key validation class and comparator as well.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "api, cassandra, hector" }
How to append the column in R? Consider the following data named `mydata`. My intention is to put `v1` and `v2` in the same column by adding an identifier variable `v4`. id v1 v2 1 2 3 2 4 5 3 7 8 `OUTPUT` required: id v3 v4 1 2 1 2 4 1 3 7 1 1 3 2 2 5 2 3 8 2 Any help is much appreciated!
I think you are looking for something like `dplyr::mutate()` for adding columns, and `rbind()` for stacking two data frames on top of each other. library(dplyr) mydata <- data.frame (id = c(1,2,3), v1 = c(2,4,7), v2 = c(3,5,8)) ) a<- data.frame(mydata$id, mydata$v1)%>% mutate(v4=1)%>% rename(v3=mydata.v1, id=mydata.id ) b<- data.frame(mydata$id, mydata$v2)%>% mutate(v4=2)%>% rename(v3=mydata.v2, id=mydata.id ) > rbind(a,b) id v3 v4 1 1 2 1 2 2 4 1 3 3 7 1 4 1 3 2 5 2 5 2 6 3 8 2
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r, dataframe, append" }
How is your Mac set up for Windows development? I'm looking at buying a MacBook Pro to replace my tiring laptop. My day to day job is as a .NET web developer so I am looking to use VMware Fusion to run VS and SQL server etc. As I've not run my dev environment in a VM before, I would like to know how others are setup. What apps to you have installed? In which environment? Where do you store your files? Within each environment, or some shared drive? Are there any gotchas? Or essentials I should know. Many thanks Matt
I also use bootcamp. It's very simple to setup and I find it much quicker that fusion as there is no sharing of resources. Vs2008 and vs2010 both run very swiftly on quite a clean install of windows i would say as fast as on my desktop. I use svn for storing source files and backup the windows install to external drive every so often. All in all the experience is no different to using a Dell other than the @ symbol is in the wrong place ;) Jon
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 6, "tags": "macos, installation, development environment" }
How to get the Classic Start Menu in Windows 7? Classic start menu is simple and efficient, but the Vista style start menu gets in the way from letting me get on with what I want to do. It also has features I don't want, such as an irritating bitmap that changes according to where the cursor hovers. I've managed to disable most of the unwanted cosmetics and animations but it's still not the dull old Classic Menu that I prefer. How to get the Classic Start Menu in Windows 7 but without a kludge if possible?
The free Classic Shell does a classic start menu for Windows 7.
stackexchange-superuser
{ "answer_score": 1, "question_score": 2, "tags": "windows 7, start menu" }
Excel vba: data validation mandatory and maximum field length I want to have some data validations for the given range ( D2:D65536 ). The validation criteria must check the cells within the range must not be empty and the text length should not more than 35. How to implement this validation using vba? I have tried: ' With Range("D2:D65536").Validation ' .Delete ' .Add Type:=xlValidateTextLength, _ ' AlertStyle:=xlValidAlertInformation, _ ' Minimum:=2, Maximum:="35" ' .IgnoreBlank = True ' .ErrorTitle = "Validation Error" ' .ErrorMessage = "X mandatory and length should be less than or equal to 35" ' .ShowError = True ' End With
I think you are looking for: Sub Validate() With Range("D2:D65536").Validation .Delete .Add Type:=xlValidateTextLength, _ AlertStyle:=xlValidAlertInformation, _ Operator:=xlBetween, _ Formula1:="2", _ Formula2:="35" .IgnoreBlank = True .ErrorTitle = "Validation Error" .ErrorMessage = "X mandatory and length should be less than or equal to 35" .ShowError = True End With End Sub The Help on F1 is less confusing than on a search, but any way have a look at the Add method : < The example you used is for whole numbers, but you wish to check text length.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "validation, vba, excel" }
How do i acess DoubleBuffer[] from java in JNI This is almost like 2D array. Each slot of the array is a DoubleBuffer. Before when I do single Buffer, I used this in JNI: Assume my JNI method take in a DoubleBuffer double *dBuf = env->GetDirectBufferAddress(env, buf); and then just indexing with simply using dBuf[i] => where i is index. Let say I want to pass in an array of FloatBuffer, how do i indexing in to the slot and allocate data can i say double **dBuf = env->GetDirectBufferAddress(env, buf); ?? Help pls thanks
No you can't. You have to obtain each element of the Java array with `GetObjectArrayElement(),` and then access each element as a `DoubleBuffer` using its API via JNI as usual.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, android, android ndk, java native interface, buffer" }
Error Including QGeoPositionInfo I am new to Qt , I have been given this task where i should use GPS so to use to GPS ,i only did this one line of code #include <QGeoPositionInfo> and the following error appeared In file included from ..\Project\mainwindow.cpp:3: ..\Project\/form.h:7:28: error: QGeoPositionInfo: No such file or directory how can i solve this issue ? how can i get this file ? please note that i have tried re installing Qt Creator... **Please be specific i would really appreciate that...**
`QGeoPositionInfo` is part of Qt **Mobility**, which is an extension to Qt.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++, qt, gps" }
SQL: How to show all rows from one table that are not all listed in the 2nd table joined I am having difficulty getting all the rows to show from the 'Customer' table, as they are not all listed in the 'SalesOrder' table I have joined. How do I get all the rows to show from the Customer table even if they have a 0 value? Thank you for any suggestions :) SELECT Customer.CID, Customer.Name, COUNT (SalesOrder.CID) AS NbrOrders, SUM (FullPrice) AS [Total Value of Items] FROM (Customer INNER JOIN SalesOrder ON Customer.CID=SalesOrder.CID) GROUP BY Customer.CID, Customer.Name;
Use a left join. This will show values from second table which dont have corresponding data in first table.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, join" }
FPDF - Inline bold text I am trying to create a PDF from PHP and for legal reason we need to make part of our disclaimer BOLD and the disclaimer needs to be outlined. My current code uses: if(isset($_POST['optout']) && $_POST['optout'] == "yes"){ $pdf->Ln(5); $pdf->SetFont('Arial','I',12); $pdf->SetTextColor(128); $pdf->MultiCell(0,4,'This is my disclaimer. THESE WORDS NEED TO BE BOLD. These words do not need to be bold.',1,'C'); } I am currently using WriteHTML for other parts of the document, and I could easily use that instead of MultiCell, but then how do I create the border? So I have 2 options.. **native FPDF functions** PROS: Give an option for a border CONS: No easy way to make inline text bold **WriteHTML extension class** PROS: Lets me easily add bold text inline CONS: Not sure how to create the border Suggestions?
You could rewrite a part of the extension but it may be easier for you to use the extension writeHTML, then draw a cell (empty text) with a border over the cell you created with writeHTML. By adjusting your cells properly it should work. Don't forget to use SetY **then** SetX to position your cells. Example: if(isset($_POST['optout']) && $_POST['optout'] == "yes"){ $pdf->Ln(5); $pdf->SetFont('Arial','I',12); $pdf->SetTextColor(128); //Your text cell $pdf->SetY($pos_Y); $pdf->SetX($pos_X); $pdf->writeHTML('This is my disclaimer. <b>THESE WORDS NEED TO BE BOLD.</b> These words do not need to be bold.'); //Your bordered cell $pdf->SetY($pos_Y); $pdf->SetX($pos_X); $pdf->Cell($width, $height, '', 1, 0, 'C'); }
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 15, "tags": "php, html, border, fpdf" }
Restrict a number to upper/lower bounds? Is there a built-in way or a more elegant way of restricting a number _num_ to upper/lower bounds in Ruby or in Rails? e.g. something like: def number_bounded (num, lower_bound, upper_bound) return lower_bound if num < lower_bound return upper_bound if num > upper_bound num end
Here's a clever way to do it: [lower_bound, num, upper_bound].sort[1] But that's not very readable. If you only need to do it once, I would just do num < lower_bound ? lower_bound : (num > upper_bound ? upper_bound : num) or if you need it multiple times, monkey-patch the Comparable module: module Comparable def bound(range) return range.first if self < range.first return range.last if self > range.last self end end so you can use it like num.bound(lower_bound..upper_bound) You could also just require ruby facets, which adds a method `clip` that does just this.
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 11, "tags": "ruby on rails, ruby" }
check the data that server sends to frontend { "status": 200, "user": { "company": "DealerSocket", "email": "[email protected]", "first_name": "Phuong", "id": 13, "last_name": "Tran", "profile_picture": " } } the server give me this JSON, I want to check the email of user by `data.user.email`.However, it said: > TypeError: Cannot read property 'email' of undefined. I dont understand why it throws an error. Thanks ![enter image description here](
you are using fields of `user` object in a `data` array, you should first check if `user` exists. When the component is rendering, data fetching may have not been finished therefore there is no `user` element inside data and get an error. The following way will solve the problem. console.log("Email is: "+data.user && data.user.email) When using above code, it will only print email to the console, if the `user` object is available inside `data`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, reactjs" }
SELECT a value and store it in a PHP $_SESSION variable before I leave a page? Is there a way of having a user select an item from an HTML SELECT dropdown and then store it in a $_SESSION variable before they navigate away from a page? I know the obvious way is to get the FORM to return to the same page and then check for the variable being set, but I'm trying to modify something that someone else has done without a major rewrite! I.e. can a session variable be set whose value changes depending on the user's SELECT option without reloading the page? All help much appreciated.
That is called AJAX. < But there is no pure PHP way because PHP is serverside only. So you will have to resort to javaScript.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "php" }
what CSS properties should I add to make the scroll appear in this table? I have the following table: 'table' how cam I save it's width Even when the screen is narrowed and only add a scroll to show it, I have added `overflow: scroll;` to the container `<div>` but it looks like this: 'table' what CSS properties should I add to make the scroll appear in this table to make it responsive?
Add 'overflow-x: auto;' to container: <div class"table-responsive" style="overflow-x: auto;"> <table style="width:200vw;"> <tr> <td>test</td> </tr> </table> </div>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "html, css, html table, scroll" }
How to make method public for my project but not for public API? I write SDK and I have header `MyClass.h` with public API. Some methods are not written in header like `- (void)foo;` so users cannot use them. However my other class use method `foo` but since its not registered in `MyClass.h` \- I cannot use it also. So in each class that want to call method `foo` I wrote: @interface MyClass () - (void) foo; @end Is it legal? I need to write the same in 3 other classes and it looks bizarre. So what is the best practice to _publish_ method for internal usage but not for public API?
Create a new file. Use the “Objective-C File” template: ![choosing a file template]( For “File”, enter “Project”. For “File Type”, choose “Extension”. For “Class”, enter “MyClass” (or whatever your real class name is): ![setting the file options]( Xcode creates a new file named `MyClass_Project.h`. In this file, declare your project-only methods: #import "MyClass.h" @interface MyClass () - (void)foo; @end Then, in every `.m` file that needs to use one of these methods, and in `MyClass.m`, import `MyClass_Project.h`. Any file that imports `MyClass_Project.h` does not need to also import `MyClass.h`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ios, objective c" }
QGIS: why does simplesvg export plugin generate poor quality output? I am exporting a QGIS project to SVG via the simplesvg plugin. However the output is of really poor quality: all coordinates appear to have snapped to a rather coarse grid (while original data, as shown in QGIS main window, have not). Why is this happening?
As detailed in the simplesvg plugin exporting window (not in a very evident position, though), simplesvg works by dumping screen coordinates (expressed in integer pixels) from the current viewport at the moment of exporting. This means that all vertices are implicitly snapped to the pixel grid. A workaround for exporting a large area while still retaining good precision is to zoom in heavily and ask simplesvg to export all data (not only visible data), by unchecking the appropriate checkbox. This will still snap vertices to a grid, but you can make it as fine as you want.
stackexchange-gis
{ "answer_score": 1, "question_score": 1, "tags": "qgis, export, svg" }
Probability of Intersecting Two Random Segments in a Circle I designed this problem and tried to solve it but didn't solve. Choose four points $A$, $B$, $C$ and $D$ from inside of a circle uniformly and independent. What is the probability that $AC$ intersects $BD$? !enter image description here
There are 2 general cases here, either one point lies in the triangle formed by the other 3, or there is no such point. The diagram above is an example of the second case. In the first case, there is no way to connect the line points with 2 lines segments, such that the segments intersect. In the second case, it is possible, but only in the case where "opposite" points are chosen, which is 1 out of 3 possible. So, if the probability of having no point lie in the interior of the triangle formed by the other 3 is $P$, the probability is $\frac{1}{3}P$. Now the trick is how to find $P$. [edit] As Jack notes below, this separate problem has been solved here, yielding $$P=1−\frac{35}{48 \pi^2}$$
stackexchange-math
{ "answer_score": 3, "question_score": 10, "tags": "probability, geometric probability" }
PhpStorm Version 2020.1: Meaning of dots on file icon symbol Can anyone explain to me what these two dots on some file icon symbols stand for in PhpStorm Version 2020.1? I could not find anything helpful in the documentation e.g.: < ![enter image description here](
This comes from Symfony plugin. From v0.20.196 Changelog: > Provide custom Twig file overlay to indicate "extends" and attached controller template types Those icons provide hints on what's inside the file (e.g. somehow similar to how PHP files are handled: separate icon for PHP Class, Trait, Abstract class, Exception etc). * Red dot for "controller" * Yellow dot for "extends" You can check more here: <
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 5, "tags": "icons, phpstorm, symbols" }
How do I add the results of work-items in a work-group in OpenCL? I'm calling the kernel below with GlobalWorkSize `64 4 1` and WorkGroupSize `1 4 1` with the argument `output` initialized to zeros. __kernel void kernelB(__global unsigned int * output) { uint gid0 = get_global_id(0); uint gid1 = get_global_id(1); output[gid0] += gid1; } I'm expecting `6 6 6 6 ...` as the sum of the `gid1`'s (0 + 1 + 2 + 3). Instead I get `3 3 3 3 ...` Is there a way to get this functionality? In general I need the sum of the results of each work-item in a work group. EDIT: It seems it must be said, I'd like to solve this problem without atomics.
You need to use local memory to store the output from all work items. After the work items are done their computation, you sum the results with an accumulation step. __kernel void kernelB(__global unsigned int * output) { uint item_id = get_local_id(0); uint group_id = get_group_id(0); //memory size is hard-coded to the expected work group size for this example local unsigned int result[4]; //the computation result[item_id] = item_id % 3; //wait for all items to write to result barrier(CLK_LOCAL_MEM_FENCE); //simple O(n) reduction using the first work item in the group if(local_id == 0){ for(int i=1;i<4;i++){ result[0] += result[i]; } output[group_id] = result[0]; } }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "opencl, gpgpu" }
Jquery How to grab an element who does not have a child who contains I'm trying to grab out all the tables who don't have a paragraph child element that contains the word "Figure" I tried to do it like this: `$('table :not(:has(p:contains("Figure")))')` doesn't seem to be returning the tables I need. Any Idea on how to do this?
There shouldn't be a space after `table`, since you want the `:not` modifier to apply to the tables. $('table:not(:has(p:contains("Figure")))') The way you wrote it, it returns all the descendants that don't have a paragraph containing `Figure`.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "jquery, html" }
Apply a comparison between two numpy.arrays to only one column but retrieve whole rows I have two numpy arrays with two columns each. import numpy as np a = np.array([[1131, 1], [4131, 2], [421, 1], [41, 1]]) b = np.array([[5881, 2], [637, 2], [742, 2], [36, 2]]) and I want to create a third array with 2 columns that the fist column will contain the minimum between the first columns of a and b and the second column will contain whatever the second column of the array containing the minimum had. the third array should be c = np.array([[1131, 1], [637, 2], [421, 1], [36, 2]]) How can I do that efficiently?
Looks like a perfect case to _ab-use_ `NumPy broadcasting` within `np.where` - np.where((a[:,0] < b[:,0])[:,None],a,b) The beauty is that it would work independent of the number of columns in `a` and `b`, as that's where the broadcasting helps out. Sample run - In [78]: a Out[78]: array([[1131, 99], [4131, 4], [ 421, 56], [ 41, 78]]) In [79]: b Out[79]: array([[5881, 23], [ 637, 42], [ 742, 7882], [ 36, 62]]) In [80]: np.where((a[:,0] < b[:,0])[:,None],a,b) Out[80]: array([[1131, 99], [ 637, 42], [ 421, 56], [ 36, 62]])
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "python, numpy" }
Java: url encoding leaving 'allowed' character intact Simple question from a Java novice. I want to encode a url so that nonstandard characters will be transformed to their hex value (that is %XX) while characters one expects to see in a url - letter, digits, forward slashes, question marks and whatever, will be left intact. For example, encoding "hi/hello?who=moris\\boris" should result with "hi/hello?who=moris%5cboris" ideas?
This is actually, a rather tricky problem. And the reason that it is tricky is that the different parts of a URL need to be handled (encoded) differently. In my experience, the best way to do this is to assemble the url from its components using the URL or URI class, letting the _them_ take care of the encoding the components correctly. * * * In fact, now that I think about it, you have to encode the components before they get assembled. Once the parts are assembled it is _impossible_ to tell whether (for example) a "?" is intended to the query separator (don't escape it) or a character in a pathname component (escape it).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 3, "tags": "java, url, encoding, urlencode" }
Prove that if $a+b = y$, where $a \neq 1$ and $\gcd(a,b) = 1$;$ a^b+b = 1 (\mod y)$ then Prove the following conjecture: If for two integers $a, b$: $a+b = y$, $a ≠ 1$, and $\gcd(a, b) =1$ $a^b+b$ $\equiv$ $1$$\pmod y$ $y$ is prime. (I am new here at math.stackexchange.com)
The conjecture is false, here are some counter-examples: a=22 b=3 y=25 = 5^2 a=62 b=59 y=121 = 11^2 a=12 b=103 y=115 = 5*23 a=136 b=7 y=143 = 11*13
stackexchange-math
{ "answer_score": 2, "question_score": 3, "tags": "elementary number theory" }
Copy two columns from one table to another, but only unique values I have `table1`, which has MBID | Artist __________________ 123321 The Beatles 123214 Led Zeppelin 123321 The Beatles How can I copy all of the **distinct** `MBID's` along with their corresponding `Artist` name, into a new table, so that the new table only has distinct `MBID`'s MBID | Artist __________________ 123321 The Beatles 123214 Led Zeppelin I've tried insert into table2 (MBID,artist) select distinct(table1.MBID),table1.artist FROM danktable But this gives me weird combinations and not only distinct MBID's When I make the `MBID` a primary index, I get an error with this query because i'm getting non-unique `MBID` values. Could someone help me out? Thanks !
You can do it as follows : insert into table2 (MBID,artist) select MBID,max(artist) from table1 group by MBID
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "mysql, sql" }
htaccess Rewriteurl Looping I have problem when using `htaccess rewriteurl`, it was stacking every I change the page, I try this one : Options +FollowSymlinks RewriteEngine On RewriteRule ^category/([^/]*)/([^/]*)$ /test/category.php?k=$1&page=$2 [L] **change this** **become like this** **the problem occure when i'm going to page 3** URL become like this so on... switch page to page 4 why is this looping? what's wrong with my code??
Because you've changed your URL's to look like ` any relative links on that page will think the new URL base is: ` instead of ` which would be the base if the browser loaded ` Because of this, you either need to make all your links absolute URLs or add the base in you html header: <base href="/test/" />
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": ".htaccess" }
What is the closed form of this series: $\sum_{n\geq 1}\frac{n^k{(-1)}^{n+1}}{n!}$ for $k<-10$ and for $k>1$? I would like to check the closed form of this sum $$\sum_{n\geq 1}\frac{n^k{(-1)}^{n+1}}{n!}$$ , for an integer $k>1$ and $k<-10$. **Note** : I run some computation in wolfram alpha i have got :for $k=2$ $$\sum_{n\geq 1}\frac{n^k{(-1)}^{n+1}}{n!}=0$$ and for $k>2$ The sum always gives :$\frac{m}{e}$ where $m$ is integer ,in the same time the sum of series gives $1$ for $k=-11,-12,-13,\cdots $ Thank you for any kind of help
If you first consider that: $$ \sum_{n\geq 1}\frac{(-1)^{n+1} e^{nx}}{n!} = 1-e^{-e^{x}} \tag{1}$$ you get that for $k\geq 0$ $$ \sum_{n\geq 1}\frac{(-1)^{n+1} n^k }{n!} = \frac{d^k}{dx^k}\left.\left(1-e^{-e^{x}}\right)\right|_{x=0}\tag{2}$$ holds. That gives that your constants relate with Bell numbers. The sum for $k=-11$ _does not_ equal $1$, but something very close to $1$, $\approx 0.999756790446$, that is the value of a $_{12} F_{12} $ hypergeometric function at $-1$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "sequences and series, proof writing, closed form, hypergeometric function" }
Change material on part of object with other overlapping object I learned this trick sometime ago but I have forgot. So what I want to do is add different material to an object using other object. For example I have two cubes. One has red material and one has blue material. By overlapping those cubes I'd want the material on the overlapping part of the red cube to turn into blue. ![Sample image below. Actual use would be far more complex case with no matching edges to manually set materials]( Sample image below. Actual use would be far more complex case with no matching edges to manually set materials
You can create 2 overlapping cubes. Create somewhere a third cube that will be the boolean object and make it invisible in render. Give your 2 first cubes 2 different colors, give them both a _Boolean_ modifier with the third cube as _Object_. For the orange cube, choose the _Difference_ option, for the blue one, choose _Intersect_. ![enter image description here](
stackexchange-blender
{ "answer_score": 6, "question_score": 4, "tags": "materials, shaders" }
scheduled task response to channel spring-integration How can I pass a response from task:scheduled in spring-intgeration to a channel? <task:scheduled-tasks> <task:scheduled ref="loadFruits" method="loadFruits" cron="0/5 * * * * *"/> </task:scheduled-tasks> <bean id="loadFruits" class="com.data.taskschedulers.LoadFruits"/> <int:channel id="outboundComplexChannel"/> Now can I some how read the return response of loadFruits method to a channel outboundComplexChannel Please provide if any way of doing this Thanks
Use an inbound-channel-adapter instead <int:inbound-channel-adapter ref="loadfruits" method="loadFruits" channel="outboundComplexChannel"> <int:poller cron="0/5 * * * * *"/> </int:inbound-channel-adapter>
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 3, "tags": "java, spring, spring integration" }
Rotating a UIView that is added to keyWindow I am designing an iOS Passcode Lock library with a "cover view" feature, which hides the content on the screen, when the app is backgrounded. See this image. When my `PasscodeManager` receives the `UIApplicationWillResignActiveNotification` notification, it does this: [UIApplication.sharedApplication.keyWindow addSubview:self.coverView]; This works great, does exactly what I want to do! However, if the iPad is in landscape orientation, this view does not rotate, and looks horrible on the iOS 7 multitasking preview interface. I know that `UIViewController` handles rotations, but I am not sure how to use it for this purpose, because I can't seem to push a UIViewController when the app is getting backgrounded (it looks like 2 view controllers are on top of each other, each half visible).
`UIViewController` takes care of rotating its view. If you are adding subviews directly to the window, you don't get that behavior. So, you have two choices: either use a `UIViewController`, or handle the rotation yourself. If you want to handle it yourself you can listen for `UIDeviceOrientationDidChangeNotification`. You may also need to call `beginGeneratingDeviceOrientationNotifications`. See <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ios, ipad, uiviewcontroller, rotation, uiwindow" }
Concentric circles of radii 1, 2, 3, ...upto 100 are drawn. Concentric circles radii $1, 2, 3, \ldots , 100$ are drawn. The interior of the smallest circle is colored red and the annular regions are colored alternately green and red, so that no two adjacent regions are the same color. The total area of the green regions divided by the area of the largest circle is * $\frac12$ * $\frac{51}{100}$ * $\frac{101}{200}$ * $\frac{50}{101}$ * none of the foregoing
**Hint:** Drawing a diagram, you'll come up with the quantity: $$ \begin{align*} &\dfrac{(\pi\cdot2^2-\pi\cdot1^2) + (\pi\cdot4^2-\pi\cdot3^2) + \ldots + (\pi\cdot100^2-\pi\cdot99^2)}{\pi \cdot 100^2} \\\ &= \dfrac{(2^2-1^2) + (4^2-3^2) + \ldots + (100^2-99^2)}{100^2}\\\ &= \dfrac{(2-1)(2+1) + (4-3)(4+3) + \ldots + (100-99)(100+99)}{100^2}\\\ &= \dfrac{3 + 7 + \ldots + 199}{100^2}\\\ \end{align*}$$ where the second to last step involved factoring several differences of squares. It remains to figure out the sum of an arithmetic series of $50$ terms whose first term is $3$, common difference is $4$, and last term is $199$. Hopefully you can finish the rest off on your own.
stackexchange-math
{ "answer_score": 0, "question_score": -1, "tags": "geometry, circles" }
Jquery .trigger('stop') method for .draggable $('#element').draggable ({ stop: function () { alert ('stopped'); //do some action here } }).trigger('stop'); nothing happens, thought `#element` is draggable now and event does execute after drag is complete. I tried `.triggerHandle` as well as `'dragstop'` as eventtype, no luck
Use this to trigger it instead: .trigger('dragstop') If you want it to behave _completely_ as a normal event, use .bind('dragstop', function) to attach it as well, the start option behaves slightly differently.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 6, "tags": "jquery, event handling, draggable" }
.NET DLL that references older .NET assemblies I am referencing some .NET DLLs in my .NET 3.5 project. Those DLLs have references to .NET 2.0 assemblies (like System.Data, etc.). I can not recompile those DLLs. I would like to install only .NET 3.5 and not have to install .NET 2.0. Will those DLLs work just fine? If not, is there anything I can do to have them use the 3.5 assemblies instead of the 2.0 assemblies they were compiled against?
.NET v2.0.50727 is required for .NET v3.0 and v3.5. All v3.x added is Windows Communication Foundation, Windos Workflow Foundation and Windows Presentation Foundation (at the runtime level) I believe the compiler for the v3.x SDK offers the language extensions for the v3.x framework. The compiler is able to handle v2 and v3 compiles. You can run v2 code unmodified on v2.x and greater .NET frameworks, but you cannot run v3.x .NET code ontop of the v2 framework only. Please correct me if I am wrong.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": ".net, .net 3.5" }
Calculate the length of the longest ordered sub-sequence within the array I was looking at websites such as < and I came across this question: "Given an unordered array of integers of length N > 0, calculate the length of the longest ordered (ascending from left [lower index] to right [higher index]) sub-sequence within the array." For the live of me I am struggling to find a solution in Java. Can anyone help? EDIT: Some examples: Example 1 Input: [1, 4, 1, 4, 2, 1, 3, 5, 6, 2, 3, 7] Expected Output: 4 Example 2 Input: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] Expected Output: 3 Example 3 Input: [2, 7, 1, 8, 2, 8, 1] Expected Output: 2
A term for what you want to find is a subarray, not a subsequence(according to your examples). You can solve it in a linear time using a simple loop: int res = 0; int cur = 0; for (int i = 0; i < a.length; i++) { if (i > 0 && a[i] <= a[i - 1]) cur = 0; cur++; res = Math.max(res, cur); }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java" }
The 'is copy' trait drops the type of Array objects Please consider this code: sub c1(Complex @a) { say @a.WHAT } sub c2(Complex @a is copy) { say @a.WHAT } my Complex @a = 1+2i, 2+3i, 4+2i; c1(@a); # prints (Array[Complex]) c2(@a); # prints (Array) Is this a bug or the expected behavior?
This is a bug. Please create an issue for this. Thank you!
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 7, "tags": "raku" }
Pass "is null" as parameter to a query with sqlsrv I am using sqlsrv driver with PHP 5.3.27. How can I pass "is null" as a parameter to a query. So instead SELECT row_id FROM table WHERE name IS NULL I could use SELECT row_id FROM table WHERE name = ?
I though of another way to do that myself SELECT row_id FROM table WHERE ISNULL(name,-1)=? If you're sure that you will never use '-1' as a condition, this will work. Just use your parameter when you need a value and '-1' when you need "IS NULL". But I guess there is no way to pass "is null" as a parameter
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "php, sql, sqlsrv" }
Need to push values of an array into a variable as a string Need to push values of an array as like ('1','2','3'........) in a $variable. I have a while loop from where I am getting the values 1,2,3.... I am doing like this while ($record = mysql_fetch_array($query, MYSQL_ASSOC)) { $users_id = $record['user_id']; $uid = array_push($users_id, ','); } I need these values as a String in a variable, then I will use explode function to remove ',' and use it according to my need. Please anyone can help me in this.. Thanks!
Adding them to a string and exploding it will give you an array of the values. You can just directly push them to an array $users_id = array(); while ($record = mysql_fetch_array($query, MYSQL_ASSOC)) { $users_id[] = $record['user_id']; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "php" }
golang how does the rune() function work I came across a function posted online that used the `rune()` function in golang, but I am having a hard time looking up what it is. I am going through the tutorial and inexperienced with the docs so it is hard to find what I am looking for. Specifically, I am trying to see why this fails... fmt.Println(rune("foo")) and this does not fmt.Println([]rune("foo"))
`rune` is a type in Go. It's just an alias for `int32`, but it's usually used to represent Unicode points. `rune()` isn't a function, it's syntax for type conversion into `rune`. Conversions in Go always have the syntax `type()` which might make them look like functions. The first bit of code fails because conversion of strings to numeric types isn't defined in Go. However conversion of strings to slices of runes/int32s is defined like this in language specification: > Converting a value of a string type to a slice of runes type yields a slice containing the individual Unicode code points of the string. [golang.org] So your example prints a slice of runes with values 102, 111 and 111
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 3, "tags": "go" }
Embed audio player HTML I am a newbe in HTML and I want to embed an audio player which plays an mp3 file from a link from dropbox. I took a sample code from here however, is doesn't work. It opens a player but doesn't play. This is the relevant part of the code: <audio controls> <source src=" type="audio/mpeg"> </audio>
You point to the wrong source. This link actually points to a html file whose name is rewritten by the web server software. (If I follow this link, a file that starts with `<!DOCTYPE html>` is opened, that is an indicator that this file is an HTML-website) If you do a right-click on the player and select to examine the element you'll find the real link to this file under the preview-auto_container element. So the audio element of your file needs to look like: <audio> <source src=" type="audio/mpeg"> </audio>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, audio, media player" }
How can I create Task when right click on the app? I have seen that there are UWP and desktop applications that have shortcuts. How could you create shortcuts like that? Tasks in Calculator
It sounds like you're referring to jumplists. When you add an item using the jumplist class it will show up when the app is right clicked. Then you just handle the app launch from the jumplist menu item to perform what you need. The windows uwp sample by microsoft for this is straight forward and can be found here.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, uwp" }
Screen randomly switches to console I have the following problem with Ubuntu 13.04: GUI randomly switches to console mode. If I suspend and wake up, it is in GUI again. A related issue is when I switch to a different terminal (e.g. `Ctrl`+`Alt`+`F1`) and then switch back to tty7 (`Ctrl`+`Alt`+`F7`) - I see the same console I mentioned before (looks like a system log). I tried all `Ctrl`+`Alt`+`FN` and `Ctrl`+`Alt`+`Fn`+`FN`, but it does not help. The only thing that helps is suspending (i.e. closing the lid) and waking up.
**Try to reconfigure lightdm, it may fix your issue** * Open terminal(`CTRL`+`ALT`+`T`) and execute following command: sudo dpkg-reconfigure lightdm * Then chose `lightdm` from the list. * Restart your system: sudo reboot now It may fix your issue. If doesn't fix then follow _2nd Method_. **Method 2:** Installing a new display manager can fix your problem. Steps to install **GDM** (a display manager much like _lightdm_ ): * Open terminal(`CTRL`+`ALT`+`T`) and execute following commands: sudo apt-get install gdm sudo dpkg-reconfigure lightdm then chose `gdm` from the list. And restart your system: sudo reboot now Hope these methods solve your issue. Reply if something goes wrong..
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 3, "tags": "13.04, command line, display, suspend, tty" }
Hombrew is asking me for a version of Xcode the OS doesnt support I need to download certain apps through homebrew, one of them being pygtk, but when putting the rather simple command that should install it homebrew says my Xcode (6.4 because I am on Yosemite) is outdated and that need the 7.2.1 which I can't install because it's not supported in Yosemite. How can I fix this?
This may mean that you can't install pygtk through homebrew on Yosemite. You may still be able to compile from source, even with your version of Xcode.
stackexchange-apple
{ "answer_score": 1, "question_score": 0, "tags": "macos, xcode, homebrew" }
Replace 16 digit identifier with new identifier I want to replace existing 16 digit identifier in a file with newly generated identifier defined in shell variable "NEW_IDENTIFIER". SEARCH_PATTERN="g_ExistingMachineID" NEW_IDENTIFIER="456EFABC-4567-546C-B4E2-DA2F45AE2CD3" g_ExistingMachineID[] = _T( "{123ABCDE-1234-312C-B4E2-0E5F15BD1CA9}" ) **Desired Output** g_ExistingMachineID[] = _T( "{456EFABC-4567-546C-B4E2-DA2F45AE2CD3}" ) I got the desired line using g_ExistingMachineID as search pattern but not able to get regular expression to replace 123ABCDE-3640-430C-B4E2-0E6F75AF6CA9 with value stored in NEW_IDENTIFIER. I'm reading SED and trying few expression. Any help would be appreciated. Thanks in advance.
If the ID doesn't contain any characters special to sed, plain `sed` with address + substitution should work: sed -i~ "/$SEARCH_PATTERN/s/{.*}/{$NEW_IDENTIFIER}/" file
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "linux, bash, shell, sed" }
grep "+" operator does not work This ls -l /var/log | awk '{print $9}' | grep "^[a-z]*\.log." outputs this: alternatives.log.1 alternatives.log.10.gz alternatives.log.2.gz alternatives.log.3.gz alternatives.log.4.gz alternatives.log.5.gz alternatives.log.6.gz alternatives.log.7.gz alternatives.log.8.gz alternatives.log.9.gz apport.log.1 apport.log.2.gz apport.log.3.gz but this: ls -l /var/log | awk '{print $9}' | grep "^[a-z]+\.log." outputs nothing. Why? I just changed `*` to `+`. Isn't it similar? Operator `+` just needs at least one match, and `*` zero or more.
This is because `grep` (without any arguments) only works with standard regular expressions. `+` is part of the extended regular expressions, so to use that, you need to use `grep -E` or `egrep`: ls -l /var/log | awk '{print $9}' | grep -E "^[a-z]+\.log." Also, you can just do this if you don't want to use extended regular expressions: ls -l /var/log | awk '{print $9}' | grep "^[a-z][a-z]*\.log."
stackexchange-askubuntu
{ "answer_score": 52, "question_score": 46, "tags": "grep" }
How to change "Activities" text on Ubuntu 17.10 I want to know how can I change the "Activities" text to my own text for example "Task Manager", or is it possible if I can change it to an **image icon**?
Yes, you can do both. You may use a GNOME shell extension called Activities Configurator to achieve your goal. It lets you > Configure the Activities Button and Top Panel. Select an icon. Change the text. And provides many more customisations. ![enter image description here]( (screenshot source: extension's homepage at extensions.gnome.org)
stackexchange-askubuntu
{ "answer_score": 3, "question_score": 3, "tags": "gnome shell, activities overview, top bar" }
How do I make Bowser / Bowser Jr. throw hammers? I played a level online where it looked like Bowser Jr. threw hammers. I know Bowser does this in the original game. I tried dragging a Hammer Bros. onto them, but this just replaces them with the Hammer Bros. How do you make them throw hammers? Side note: I know putting Bowser Jr. into the Koopa Clown Car makes him throw shells... and putting Bowser into the Koopa Clown Car makes him throw Bob-Ombs.
According to this video, adding wings to Bowser Jr. causes him to throw hammers. Bowser himself doesn't seem to have a way to do this; you'll have to stack a source of hammers on top of him or something.
stackexchange-gaming
{ "answer_score": 5, "question_score": 3, "tags": "super mario maker" }