INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Help with a simple trigonometry problem > A decorative garden is to have the shape of a circular sector of radius $r$ and central angle $\theta$. If the perimeter is fxed in advance, what value of $\theta$ will maximize the area of the garden? I've given it a go, but I don't think I really understand the problem. Here's my try: the area of a sector is $A=\frac{1}{2}r^2 θ$. The perimeter being fixed means that we can treat $r$ as a constant. We need to find the value of $\theta\in[0,2\pi]$ that maximizes $A$, but since $A$ is really just a line with a positive slope, that value is $2\pi$. Needless to say that isn't the right answer according to the solution manual. So, what am I doing wrong? Thanks.
Let $P$ be the perimeter and $S$ be an area of the garden. Thus, $2r+\theta r=P$, which gives $r=\frac{P}{2+\theta}$ and by AM-GM we obtain: $$S=\frac{1}{2}r^2\theta=\frac{P^2}{2}\cdot\frac{\theta}{4+4\theta+\theta^2}=\frac{P^2}{2}\cdot\frac{1}{\frac{4}{\theta}+\theta+4}\leq$$ $$\leq\frac{P^2}{2}\cdot\frac{1}{2\sqrt{\frac{4}{\theta}\cdot\theta}+4}=\frac{P^2}{16}.$$ The equality occurs for $\theta=2$.
stackexchange-math
{ "answer_score": 4, "question_score": 1, "tags": "geometry, trigonometry, optimization, circles, a.m. g.m. inequality" }
Scala type parameterization, Shapeless - could not find implicit value for parameter Generic I'm unable to implement shapeless.Generic with scala type parameterized functions. In the following piece of code, I am getting error "could not find implicit value for parameter gen: shapeless.Generic[T]". def fooT = { val gen = shapeless.Generic[T] //getting error in this line!!! val values = gen.to(instance) println(values) } case class Bar(x:String, y:String) var bar = Bar("a","b") foo(bar) Is there anything I am missing?
def fooT, HL <: HList( implicit gen: Generic.Aux[T, HL] ) = { val values = gen to instance println(values) } case class Bar(x: String, y: String) You need to use the `Aux` pattern usually, generics are macro materialised but produce an arbitrary type that's exposed as an abstract type member. If you don't understand all the words here just yet, read more **here**.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "scala, shapeless" }
Insert records into mysql database without reloading page What is the most simple way to insert values into a mysql database without reloading the page? In this particular example, I'd like to have a form with one input field, and when the form is submitted, the user's input to the field is inserted into a mysql database table, but the page is not reloaded.
You can use AJAX to send content to a server side file (without reloading) and that file can insert row(s) in the database. Here's an example : < Here, this guy creates a digg like vote button and it inserts and updates rows without reloading the page. Check it out.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, database" }
Isolate one computer on the network. DD-WRT Here is the setup: ISP -> WRT -> Switch: Box 1,2,3... I need to let box 3 out on then internet and I need to forward a port or two to box 3. I found some information on setting up a vlan by port, but I need (guessing) is a vlan by MAC. There is no way to physically go from box 3 to the WRT or I would have done that already. Any input would be appreciated. Specs: ASUS WL-520GL running DD-WRT v24-sp1 (07/27/08) vpn
You can't. Not with a dumb switch in the way.
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "networking, vlan, router" }
Context.User is null in a Signalr 2.0 Hub I'm using VS 2013 Express and the standard MVC5 template to create a new clean app. Authentication is enabled and I can log into the site just fine. I can see the user context in my controllers, but when I add Signalr I can't get the Hubs to register that authentication has take place. Context.User in the hub is null. Using Signalr 2.0.2 and all related OWIN packages.
The resolution to the program was very simple. In my startup class I had the code in the wrong order. This is what I had when it wasn't working: app.MapSignalR(); ConfigureAuth(app); However, this is the correct order to have Signalr work with authentication: ConfigureAuth(app); app.MapSignalR(); This may be a no-brainer for most, but I think it's an easy mistake to make.
stackexchange-stackoverflow
{ "answer_score": 27, "question_score": 6, "tags": "asp.net mvc, signalr" }
Ruby On Rails ActiveRecord model not showing "blacklist" field So I'm trying to rough out a design in Ruby, and so I ran ruby script/generate scaffold item name:string description:text model:string manufacturers_name:string category:string weight:decimal upc:string ebay_cat_id:string blacklist:bool in_discovery:bool archived:bool The only problem is that none of the bool fields are on the model. If I use ruby script/consol and run item = Item.new I get #<Item id: nil, name: nil, description: nil, model: nil, manufacturers_name: nil, category: nil, weight: nil, upc: nil, ebay_cat_id: nil, created_at: nil, updated_at: nil> Is there a limit to how many fields it will show on the object? I know the fields were created in the database... double checked that. Come to think of it the date timestamps aren't on the object either. Any hints for me? Do I have to manually write accessors for these or what?
Have you tried: blacklist:boolean It looks like you must declare the full name, the docs say: > Instantiates a new column for the table. The type parameter is normally one of the migrations native types, which is one of the following: `:primary_key`, `:string`, `:text`, `:integer`, `:float`, `:decimal`, `:datetime`, `:timestamp`, `:time`, `:date`, `:binary`, **`:boolean`**. Just like you cannot use `int`, you must declare `integer` To answer the second part of your question, _Yes!_ there is a limit to the number of columns you may have, 4096. It's likley that once the interpreter hit "bool" it nixed the latter column names and types, that is why you're probably missing your timestamps and what not.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ruby on rails, activerecord, sqlite" }
How to put all print output from cmd to a txt file? Can you help me identify what's wrong in this code? I want to put all the print output on the cmd to a txt file. This code only puts the last line. import urllib.request fhand = urllib.request.urlopen(' for line in fhand: z = line.decode().strip() with open('romeo.txt', 'w') as f: print(z, file=f)
You are creating and writing 'romeo.txt' file for every line of the content. Swap the for loop and the opening file. Something like this: import urllib.request fhand = urllib.request.urlopen(' with open('romeo.txt', 'w') as f: for line in fhand: z = line.decode().strip() print(z, file=f)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, cmd" }
How to take the cube root of a negative number in VBA for Excel? I am trying to compute the cube root of a negative number in VBA for Excel. Taking the cube root of a negative number in an Excel worksheet works fine: =(-2)^(1/3) -1.25992 However the same concept coded into VBA: (-2)^(1/3) gives a `#VALUE!`error when returning the value to the worksheet. I suspect VBA is parsing the `1/3` to its decimal representation `0.3333...` and therefore causing a mathematical error since negative numbers can't be raised to non-integer powers in the real domain. Is there a workaround?
Try using the `POWER()` function: POWER(-2, 1/3)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "vba" }
Automatically name anonymous functions with regex I am working on a regular expression substitution that automatically names anonymous functions in a Javascript file. Until now I've come up with this regex: /^(\s*)(?!window\.)(\w+\.)?(\w+)(\s*)([:=])(\s*)function(\s*)\(/gm that correctly names functions (and preservers spacing) except the ones that are on the `window` object or that are referenced in an array (`this.foo[i] : function() {}`). The problem is that this regex doesn't match functions specified as vars, like this: var foo = function() {} This is a regex online tester with my regex so far < Any help?
Now i got it :D `^(\s*)((?!\s*window\.)|(var))(\s*)(\w+\.)?(\w+)(\s*)([:=])(\s*)function(\s*)\(`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, regex, anonymous function" }
Add two Storyboards to project for different languages I want to add a right to left language to my project. May I have two Storyboard one of them for LTR and another for RTL languages? How?
Yes, you can use two storyboards to do it. You can put an if statement in your appDelegate class to check if the device language is RTL or LTR, then switch between storyboards by their ID. let preferredLang = NSLocale.preferredLanguages().first! if NSLocale.characterDirectionForLanguage(preferredLang) == .RightToLeft { storyboard = "Main" }else{ storyboard = "MainEn" } let Main = UIStoryboard(name: storyboard, bundle: nil).instantiateViewControllerWithIdentifier("vcMain"); self.window?.rootViewController=Main self.window?.makeKeyAndVisible()
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "ios, swift, xcode, storyboard, multilingual" }
Obter a lista de números primos menores que N Estou com um exercício no qual preciso entrar com um número (N) e calcular com Python quais são os números inferiores a N que são primos. Esse é o código que tenho agora. num == int(input("Insira um número: ")) while num < 0: num == int(input("Valor inválido! Insira um número novamente")) n = 1 c = 0 while n < num: if n%1 == 0 and n%n == 0 O problema é que tecnicamente todo número dividido por 1 e por ele mesmo tem como resto zero, que condição eu posso usar pra quebrar essa?
Pra receber todos os números primos menores que um tal 'n' é simples Segue o código from math import sqrt numero = int(input()) aux = 0 aux1 = 0 if numero > 3: print(2,'\n',3) #Coloquei isso aqui, porque estavam ficando de fora, haha while numero > 1: aux = sqrt(numero) aux = int(aux) aux1 = 0 while aux >= 2: if numero%aux == 0: aux1 += 1 if aux == 2: if aux1 == 0: print(numero) aux -= 1 numero -=1
stackexchange-pt_stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "python" }
Separate Title Page in Wordpress With a wordpress blog (preferably the new 3.0), Is there a way to have a different page be the home page of the blog, and put the usual blog posts and such on a separate page, such as www.domain.com/blog ?
If I understand what you want to do correctly, you want to have a static front page that links to your blog. You can use Pages to get that. From the codex: > A Page can easily be set to be your site's Front Page. Visit the Administration > Settings > Reading panel and under Front page displays, you can choose to set any (published) Page or Posts Page as the Front Page. The default setting shows your blog with the latest blog posts.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php, wordpress, wordpress theming" }
HTTP2 from the browser with early SSL termination I want to set up my web page to make HTTP2 requests to a Jetty API server. I read that browsers will only use the "h2" protocol, that is, HTTP2 with TLS. However, my setup has a kubernetes ingress performing SSL termination, and proxying a cleartext request back to the Jetty server. The dilemma is that I don't think I want to negotiate an "h2" connection using Jetty, because that would require an SSL context on that server. My question is, will this setup allow a browser to perform HTTP2 requests? If so, what do I need to enable on the Jetty server in order to properly serve HTTP2 requests?
You can configure Jetty to serve clear-text HTTP/2 (also known as `h2c`), so that your setup will be: `browser -- h2 --> kubernetes tls termination -- h2c --> Jetty` In order to setup Jetty with clear-text HTTP/2, you just need to enable the `http2c` module if you are using Jetty as a standalone server, see < Alternatively, if you're using Jetty embedded you can look at this example.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "http, ssl, jetty, kubernetes, http2" }
Is there an alternative to Redshift and F.lux which only dims the screen? I want one where it reduces the screen's brightness, either by time or on demand (I don't mind). I have onboard Intel graphics. I don't want it to be like Redshift where it changes the screen's hue.
On a computer with Ubuntu 11.04 and onboard Intel graphics this works for me: $ xrandr | grep connected | cut -f1 -d" " VGA1 Use the output name found (in this case "VGA1") and adjust the brightness $ xrandr --output VGA1 --brightness 0.7 Note, that the **xrandr** man page has this to say about the --brightness flag: > However, this is a software only modification, if your hardware has support to actually change the brightness, you will probably prefer to use **xbacklight**.
stackexchange-askubuntu
{ "answer_score": 14, "question_score": 19, "tags": "11.04, graphics, intel graphics, brightness" }
How to use mkdtemp in solaris I am currently trying to build a 3rd party project (qt 5.0.1) for Solaris and am currently stuck with the following error: io/qtemporarydir.cpp: In member function 'void QTemporaryDirPrivate::create(const QString&)': io/qtemporarydir.cpp:150:30: error: 'mkdtemp' was not declared in this scope gmake[3]: *** [.obj/release-shared/qtemporarydir.o] Error 1 From what I have found out, mkdtemp should be found in stdlib.h which is in /usr/include. However looking in stdlib.h on my solaris system it soes not define the mkdtemp method. Does anyone know of a workaround for this? (Or how I can compile Qt for Solaris...)
I have since found that there was an additional function in the Qt source which replaced mkdtemp for systems which did not define it themselves. However it was wrapped in an #ifdef statement which did not account for Solaris builds. Uncommenting the #ifdef wrapper fixed that buil
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, qt5, std, solaris" }
What are the advantages using SUMO vector for expression? My question is : What are the advantages using SUMO vector for expression?
As the pET SUMO info page states > It utilizes a small ubiquitin-related modifier (SUMO) fusion, belonging to the growing family of ubiquitin-related proteins, to enhance the solubility of expressed fusion proteins. So, in general, you could consider using SUMO vectors to improve the solubility of your protein.
stackexchange-biology
{ "answer_score": 0, "question_score": -1, "tags": "molecular biology, protein expression, transformation, experimental, vector" }
Compositing/flattening images in Rails with Paperclip I'm building a Rails application where a user can upload an image which is automatically cropped to a certain size, then they can choose an overlay which is exactly the same size as the cropped image. What I want to do is composite or flatten the two images and save it as a single image - I've looked at the Image Magick documentation, but I can't see how to apply the example they give: composite -gravity center smile.gif rose: rose-over.png to work with Paperclip. Also, the example references two specific images, but I'm wondering how I can pass in a variable (the user uploaded image) instead?
I believe you want to use a paperclip processor. Here is the high level description: < Here is a gist example of using composite (recommended here < <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, imagemagick, paperclip" }
I can not find a way to set the ons-popover background-color Is there any way to change the background color of the ons-popovers? Changing the style did not seem to work and I don't see an attribute to do it.
For Onsen 1.x and Onsen 2 prior to beta.8: .popover__content { background-color: red; } .popover__top-arrow, .popover__bottom-arrow, .popover__left-arrow, .popover__right-arrow { background-image: linear-gradient(45deg, red, red 50%, transparent 50%); } Change `red` with the color you want.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "popover, onsen ui" }
Is Regression objective in XGBoost invariant to feature attributes' scaling? I am relatively new to using XGBoost. Classification problems clearly don't get affected by the feature scaling as the new splits would take care of that. But when doing regression in XGBoost, aren't we 'fitting', say, a linear regression (objective "reg:linear" in xgboost) model at some step? If so, that step might fail if the feature attributes involved aren't of similar variance. Is it or is it not?
xgboost won't fit any linear trends to your data unless you specify `booster = "gblinear"`, which fits a small regression in the nodes. The `reg:linear` objective tells it to use sum of squared error to inform its fit on a regression problem. Linear regression with gradient boosted trees is unaffected by any feature scaling as long as the rank order of the feature doesn't change.
stackexchange-stats
{ "answer_score": 4, "question_score": 4, "tags": "machine learning, cart, ensemble learning, boosting" }
Why did John make such a big deal about being a faster runner than Peter? John 20:3-8: > So Peter and the other disciple started for the tomb. Both were running, but **the other disciple outran Peter and reached the tomb first**. He bent over and looked in at the strips of linen lying there but did not go in. Then Simon Peter, **who was behind him** , arrived and went into the tomb. He saw the strips of linen lying there, as well as the burial cloth that had been around Jesus’ head. The cloth was folded up by itself, separate from the linen. Finally the other disciple, **who had reached the tomb first** , also went inside. He saw and believed. Why did John choose to mention _three times_ that he beat Peter to the tomb?
The issue that John is addressing is that no one went into the tomb unaccompanied. John arrived first, but did not go in. His testimony is that he did not disturb anything before Peter got there. "...who was behind him" does not emphasize that John was first but that Peter, and not another, was second. The final reference simply clarified which "other disciple" is being referred to.He is just saying that he one who arrived first followed Peter in, and not another disciple that perhaps arrived third.
stackexchange-hermeneutics
{ "answer_score": 8, "question_score": 11, "tags": "john, peter" }
Selenium Webdriver Donwload file path (NodeJS) I'm trying to set download location for Chrome browser but I'm stuck. const webdriver = require('selenium-webdriver'); const chrome = require('selenium-webdriver/chrome'); const chromeOptions = new chrome.Options(); chromeOptions.set('download.default_directory', __dirname + '/download'); const builder = await new Builder() .forBrowser('chrome') .setChromeOptions(chromeOptions) .build(); What am I doing wrong or what is the correct method to pass my own download folder? Many thanks!!
I've finally find out. const { Builder } = require('selenium-webdriver') const chrome = require('selenium-webdriver/chrome') const chromePrefs = { 'download.default_directory': __dirname + '/download' } const chromeOptions = new chrome.Options().setUserPreferences(chromePrefs) const driver = await new Builder() .forBrowser('chrome') .setChromeOptions(chromeOptions) .build() .catch(e => console.error(e)) in NodeJS setUserPreferences are nolonger experimental!
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "node.js, selenium, selenium webdriver" }
Why does Notes only show a sub-set of the Share extensions enabled on my Mac? ![My Share menu in Safari]( I'm really enjoying the new version of Notes.app, now that I can set the text size to something I can read. But one aspect continues to bug me, and maybe it's some setting I haven't found. The first image above shows the list of apps in my Share menu, as listed in Safari, but in Notes it is a smaller list. ![Share menu in Notes]( I would like the 'Add to Together' share item to be available to me in Notes.
It's up to the individual share extension developer to tell the system which inputs are compatible with their extension, and to then implement the necessary code to be compatible with each.
stackexchange-apple
{ "answer_score": 0, "question_score": 1, "tags": "sharing, notes.app, plugins" }
How to format dates differently? I'm working with Python and I have a list of dates in year-month-day format, and I want to convert it to just year-month. So the beginning of my list looks like this: ['2020-02-26', '2020-02-27', '2020-02-28', '2020-02-29', '2020-03-02', '2020-03-03'.... and I want it to become this: ['2020-02', '2020-02', '2020-02', '2020-02', '2020-03', '2020-03'... I am not sure where to start, and I'm thinking regex might be the solution, but I'm awful with it and I don't understand it. I have months going all the way up to December, if that changes anything. Thanks for any help!
If your dates are all in that fixed format, it's probably simplest just to slice off the day part: dates = ['2020-02-26', '2020-02-27', '2020-02-28', '2020-02-29', '2020-03-02', '2020-03-03'] out = [d[:-3] for d in dates] Output: ['2020-02', '2020-02', '2020-02', '2020-02', '2020-03', '2020-03']
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "python" }
Burgers equation change of variable In this paper on the Burgers equation (1.1), $$ u_t = \left(\nu u_{xx} - \sigma u^2\right)_x, $$ the authors use a simple change of variables (2.1a,b) $$\begin{align} u(x,t) &= q(y,t) \\\ x &= y + s(t) \end{align}$$ to write the equation as (2.2) $$ q_t - \left(q_{yy} + 2\sigma qq_y\right)=\dot{s}(t)q_y. $$ However, should not the $2\sigma qq_y$ term have the opposite sign?
It may be because $\sigma$ is defined as $\pm 1$, so either sign is appropriate.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "partial differential equations, coordinate systems" }
The Python Equivalent of the MATLAB function unique I am aware that this question has been asked but i am not able to find the answer yet. Any help is very much appreciated In Matlab it is written as: `[C,ia,ic] = unique(A)` I am interested in all output elements i.e., `C`, `ia` and `ic` ### here is an example of what the matlab function does A = [9 2 9 5]; Find the unique values of A and the index vectors ia and ic, such that C = A(ia) and A = C(ic). [C, ia, ic] = unique(A) C = 1×3 2 5 9 ia = 3×1 2 4 1 ic = 4×1 3 1 3 2 How can I reproduce this in python please? As mentioned, i am interested in all output elements i.e., `C`, `ia` and `ic`
A solution using `numpy.unique` (thanks to @SBad himself for improving the quality of the solution): import numpy as np A = np.array([9,2,9,5]) C, ia, ic = np.unique(A, return_index=True, return_inverse=True) print(C) print(ia) print(ic) **output** [2 5 9] [1 3 0] [2 0 2 1] * * * with list comprehension you can also get `ic` as: ic = [i for j in A for i,x in enumerate(C) if x == j] * * * **Note** : Remember that **MATLAB** uses 1 (one) based indexing, while **Python** uses 0 (zero) based indexing.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "python, python 3.x, matlab, group by, pandas groupby" }
Will air flow freely through a hose in the opening of a Bag of Holding? If I lay a Bag of Holding (BoH) on its side, and have a hose half in and half out of the BoH, will air flow freely through it? Or will the opening of the BoH block the air from flowing?
# It's up to your DM There's nothing in the description for the item that describes or even implies whether such a thing would work. Nothing in the item description gives us any idea of how the bag opening works mechanically or even if air flows freely into it when open. The only description that implies air in the bag is: > Breathing creatures inside the bag can survive up to a number of minutes equal to 10 divided by the number of creatures (minimum 1 minute), after which time they begin to suffocate. The implication here is that there is a finite amount of air in the bag, but nowhere is it described how air gets in or even if it can. A strict RAW reading would note that nowhere does it allow for more air nor does it strictly even say that air is the issue. Also covered nowhere in the description is how something would act if it sticks partially out of the bag. Such ambiguities are thus solely left to the discretion of your local DM to decide for their table.
stackexchange-rpg
{ "answer_score": 13, "question_score": 7, "tags": "dnd 5e, magic items" }
GDB pretty printers for igraph_vector_t and igraph_matrix_t I'm using the C interface of igraph, and sometimes, while debugging I would like to see the content of some `igraph_vector_t` variables as well as `igraph_matrix_t`. Is there some GDB pretty printer available like those available for STL containers ( `std::vector<T>` usually?)
No, there isn't, but you can try calling `igraph_vector_print()` from within `gdb` if that is possible. Alternatively, you can access the `stor_begin` member of `igraph_vector_t` \-- this is a pointer to the memory area that hosts the contents of the vector. `stor_end` points to the end of that area, and `end` points right after the last element of the vector - so, the "useful" part of the vector is between `stor_begin` and `end`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, c, debugging, igraph, pretty print" }
Installing an iOS app from Xcode over the same app downloaded from the app store (or vice versa) What are the details or rules governing what will work here? Does it have to do with certificates/provisioning profile or just the bundle id? If for example I have a user who has an issue with app downloaded from the App Store and I want to examine their app bundle, can I attach their iOS device to a Mac with XCode, compile the app overtop the app store version, and then download the bundle from the Device Manager?
You can do what you want, but both the AppStore and replacement app must have the same bundle ID and be signed with certificates from the same developer account.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, objective c, xcode, provisioning profile, app id" }
Auto Layout keeps stretching UIImageView I am using Auto layout and it's driving me crazy. I have done everything I could to prevent UIImageView from stretching all over. I have no idea why it does that. I tried using constraints, solving auto layout issues. For now, the only solution was turning the auto layout itself. Could anyone please tell me why xcode is completely ignoring my constraints? I would expect the UIImage to stay as 320x320 when I explicitly set it as that, but noooooooo.... I want to post images, but the site won't let me, and I would like to add code to this question so that it is more specific, but there's literally no code at all. I just dragged "UIImageView" from storyboard, made it small, set constraints as is, and it's just ignoring my code.
You'll want to make sure your `UIImageView` is set to clip to bounds. If not, the image will spill out of the view and will appear to not stretch correctly (even though in reality it is). In interface builder, make sure the Clip Subviews box is checked. !enter image description here If you're not using interface builder, the following code will do the same thing: yourImageView.clipsToBounds = YES;
stackexchange-stackoverflow
{ "answer_score": 49, "question_score": 31, "tags": "ios, iphone, objective c, xcode, storyboard" }
Selenium webdriver Unable to identify elements by xpath containing &nbsp; I have following table row. I am unable to identify **th** using XPath. <tr> <th>My&nbsp;Home</th> <th>My&nbsp;School</th> <th>Home</th> </tr> I have tried : mydriver.findElement(By.xpath("//tr/th[text()='My Home']")); mydriver.findElement(By.xpath("//tr/th[text()='My\u00a0Home']")); mydriver.findElement(By.xpath("//tr/th[text()='My${nbsp}Home']")); I have also tried contains() inside xpath.
You can try below workaround //th[starts-with(text(), "My") and substring(text(), 4)="Home"] But note that it just allows you to skip `&nbsp;` identification If you not familiar with this syntax, it means _`th` node with text that starts with substring `"My"` and starting from 4-th character the text is equal to `"Home"`_
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, selenium, xpath, selenium webdriver" }
All my requests to Firestore are classified as unverified because of AppCheck? I enforced Firebase AppCheck for Firestore. Now, when I try to access data, I get an error: firebase .firestore() .doc(firestoreRoot.configs.priceIds._pathUrl) .get() .then((v) => console.log(v.data())); ![appcheck error]( In Firebase, it says all my requests are unverified: ![enter image description here]( This only happens for firestore. Is there something else I must do? I enabled AppCheck in my app using: const appCheck = firebase.appCheck(); appCheck.activate("MY_SITE_KEY", true); I tried disabling AppCheck in the firebase console, and now all my requests are accepted.
The firebase documentation says: > Important: Cloud Firestore support is currently available only for Android and iOS clients. If your project has a web app, don't enable Cloud Firestore enforcement until web client support is available. Therefore, appcheck cannot be used with firestore for web applications.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "javascript, firebase, google cloud firestore, firebase app check" }
Add '\n' after a specific number of delimiters How can I add a `\n` after each four `;` delimiter in a CSV file (with bash)? Input file sample: aaaa;bbbbbb;cccc;ddddd;eeee;ffff;gggg;hhhh;iii;jjjj;kkkk;llll; Output needed : aaaa;bbbbbb;cccc;ddddd eeee;ffff;gggg;hhhh iii;jjjj;kkkk;llll
Using (GNU) `sed`: ... | sed -r 's/([^;]*;){4}/&\n/g' `[^;]*;` matches a sequence of characters that are not semicolons followed by a semicolon. `(...){4}` matches 4 times the expression inside the parentheses. `&` in the replacement is the whole match that was found. `\n` is a newline character. The modifier `g` make `sed` replace all matches in each input line instead of just the first match per line.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "bash, csv, sed, awk, cut" }
In html on click button values is increase or decrease by 1 I want to add or subtract value from given div or p tag using add or subtract button given code look like this when i click on + button it increment by 1 and when i click on - it detriment by 1 value of 0 is increase or decrease. Please help.. Thank in advance enter image description here
Found this jQuery increment value of <span> tag You can do this: <button id="plus">+</button> <span id="number">0</span> <button id="minus">-</button> <script src="jquery.js"></script> <script> $("#plus").on('click', function() { $("#number").html(parseInt($('#number').html(), 10)+1); }); $("#minus").on('click', function() { $("#number").html(parseInt($('#number').html(), 10)-1) }); </script>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "html" }
DD-WRT mini: How to disable remote access? I would like to completely disable remote access to the router from the Internet and Wi-Fi. I want it to be configurable only over LAN. What is the simplest way to do that? The router is running DD-WRT mini.
By default WiFi and LAN are bridged together and you can't disable one and keep another open
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "security, router, dd wrt" }
Debugger step filters in IntelliJ? Does IntelliJ have a feature similar/like "Use Step Filters" in Eclipse for debugging? I'm new to IntelliJ and would like to avoid jumping into hibernate or jboss proxy classes.
You can define the _Do not step into the classes_ list here: `Settings` -> `Build, Execution, Deployment` -> `Debugger` -> `Stepping` Just add things like `org.hibernate.*` to the list.
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 14, "tags": "eclipse, debugging, intellij idea" }
The factors include... or Factors include.. (is article necessary) Here's an example text: > Factors that affect a person's adaptation to exercise could be seen as falling into one of two groups: the subjective and the objective factors. **The** subjective factors include, among other things, the age and sex of a person. **The** objective factors include the external conditions ... Is the definite article needed here? Or is it in the wrong place here? "Subjective factors" and "objective factors" are mentioned in the first sentence, but only vaguely, not as some definite finite group. In books I find examples of "subjective factors include" without the definite article.
Grammatically both are correct and both sounds perfectly normal but they ( at least in my opinion) have slightly different meanings. The passage begins saying "factors" without the article because wet haven't said anything about them and we are more talking about the idea of factors while. Later on, once we have classified them as "these factors" and "those factors" we have a more concrete description of them and we are talking about specific factors. Of course it really makes little difference and I wouldn't have thought twice about it had it been done differently.
stackexchange-ell
{ "answer_score": 2, "question_score": 3, "tags": "articles" }
Python how can you check for consecutive letters in a user input? How can you check a user input in python for every time a set of 3 consecutive characters appears (according to a qwerty keyboard). It should also be case insensitive. E.g: `asDFg` should have three sets (`asD`, `sDF`, and `DFg`), and 1 point should be subtracted from a score for each set.
use three strings a b and c representing each row in qwerty keyboard and check for substrings while converting to lowercase a="qwertyuiop" b="asdfghjkl" c="zxcvbnm" str=raw_input() score=0 for i in range(0,len(str)-2): t=str[i:i+3] if t.lower() in a or t.lower() in b or t.lower() in c : score+=1 else: score-=1 print score input asDFg output 3
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python" }
Смена фона (у элемента (к примеру, div)) с помощью jquery Как сменить фон у элемента посредством JQuery методом .animate?
$("#menu a").hover(function(){ $("#menu").css("background", "#f00"); }, function(){ $("#menu").css("background", "#00f"); });
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "javascript, jquery" }
why the Issue tracking list has its Description field's internal name as "Comment" I have added an Issue tracking list inside my team site collection. and when i checked its built-in fields, i have noted that the Description field internal name is "comment" instead of being "Description". i noticed this as i wrote a powershell script and i was not able to reference the Description field using "Description" internal name. here is the internal name for the field when i access it from the site settings page :- ![enter image description here]( so can anyone adivce what is the reason behind this ? is there is any ofcourse ?
Because they decided to reuse an existing site column they created as part of the application. There are other instances of this most notably, many content types share the Keywords site column. This has been the case for several product revisions.
stackexchange-sharepoint
{ "answer_score": 2, "question_score": 1, "tags": "2013, list, administration, site column, issue tracking" }
What is better "lives up to his name" or "just like its name"? What of this two sentences is better and doesn't sound weird? 1. > "Transverse foramen", just like its name, says that the foramen moving across this bone. 2. > "Transverses foramen", its name lives up to his name, and says that the foramen moving across this bone. If you have a better option, please, kindly let me know it.
> 1. "Transverses foramen", just like its name _implies_ , says that the foramen _moves_ across this bone. > and > 2. "Transverses foramen" lives up to _its_ name, and says that the foramen _moves_ across this bone. > In both, the phrase "says that the foramen moving across this bone" needs a verb. In 1. I added _implies_ , this is an improvement but could be left out. And in 2, the first comma is not needed so I would just remove it.
stackexchange-ell
{ "answer_score": 2, "question_score": 0, "tags": "sentence construction, gerunds" }
How to design constructors? Lets assume a class `Foo` with 2 instance variables, int x and int y. The use case demands I can construct the class with either none, single or all params. input X input Y 0 0 no constuctor 0 1 public Foo(int x); 1 0 public Foo(int y); 1 1 public Foo(int x, int y); Now whats the convention/best practices in this case. Do I need to add all the permutations of constructors ? If yes, the it would result in exponential growth. If No, then whats solution ?
Short answer: It depends. Longer answer: Add the ones that correspond with real use cases. If that means one with all parameters, or one with none (which sets defaults for the parameters), great. If there are common use cases for having some parameters default and some not, provide constructors for that. Note that you cannot have multiple constructors with the same order, number, and types of parameters.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, constructor" }
How do I create a promise in Ember.js for an Ember-data model I have an Ember-Data model. I would like to do some processing in the .then promise once it has loaded and then return the same model as a promise. This is what I have right now. How do I wrap up the return object as a promise so that other promises can be chained? App.Member.find(1).then(function(member){ //do some processing here return member; // Does this need to be wrapped as a promise? }
Basically you can create a promise like this: var promise = new Ember.RSVP.Promise(function(resolve, reject){ // succeed resolve(value); // or reject reject(error); }); and then you can use the `then` property to chain it further: promise.then(function(value) { // success }, function(value) { // failure }); You can aslo have a look at this jsbin which shows how they could be implemented. And this is also very helpful. Hope it helps.
stackexchange-stackoverflow
{ "answer_score": 35, "question_score": 16, "tags": "ember.js, promise" }
What is the use of Vuex in context of data paginated from backend Being new to Vue, I have been reading a lot of the pros and cons of its use or otherwise where there are simpler options like Vue.observable. I am trying to understand a store's function in relation to a paginated data source. So when I land on stackoverflow's dashboard, I see a long list of questions of which there must be millions...so the app must be paginating from the server obviously. The Vuex examples state that it's best practice to fetch from the database inside the store's actions/mutations. All the examples ead the entirety of the database table. If stackoverflow was developed in Vue, what would be the pattern for the current app behaviour? Would the store keep only the current paginated dataset or is this not an applicable use case for Vuex?
Vuex is about a shared and a reactive state across app components (or subset of components dividing state into modules). If a paginated dataset is used by a single component only then you don't need Vuex to store the current page of the dataset.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "vuejs2, vuex" }
How do I increase VirtualBox resolution past 800x600 in Linux? > **Possible Duplicate:** > Ubuntu on VirtualBox can only show resolution of 800x600 - how to change it? No matter what I do I cannot get the resolution past 800x600. If I am using a Windows install in VirtualBox, I can get it to 1024x768. What is limiting me from doing this in Linux?
Have you installed the VirtualBox Guest Additions on your guest yet? If so, then the size of the guest should reflect the size of your VirtualBox window, so if you maximise the latter, your guest should resize its display accordingly. You may also need to activate VirtualBox's Auto-resize Guest Display option (Host-G is a hot key for that).
stackexchange-superuser
{ "answer_score": 33, "question_score": 26, "tags": "linux, virtualbox" }
How to make my flutter app return the user to the OS home screen? I'm working on an app that will have a lock screen, but I'm having some issues getting it to behave correctly. Right now I'm using the `didChangeAppLifecycleState` to navigate to the lock screen when the user suspends/resumes the app. I'm also using the `WillPopScope` to intercept and deny the back button. The problem with this approach is that pressing the back button and having nothing happen doesn't feel super intuitive. Ideally, I'd like the back button to take the user out of the app and back to their OS home screen when they're on the lock screen. I also want to do this in a way that the user's route history is maintained for when they successfully unlock the app. Is there any way to accomplish what I'm trying to do, or should I just accept that the back button won't do anything on the lock screen?
You can create an identifier in your LockScreen state and check for the identifier in `onWillPop` and if the user is pressing the back button from the lock screen, exit the app. String identifier = "lockscreen"; bool onWillPop() { if (identifier == "lockscreen") { SystemNavigator.pop(); SystemChannels.platform.invokeMethod('SystemNavigator.pop'); //preferred.* return true; } } SystemNavigator.pop(): On iOS, calls to this method are ignored because Apple's human interface guidelines state that applications should not exit themselves.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "flutter" }
How do I make tabs for a ViewPager now that ActionBar tabs are deprecated (Lollipop) I've seen that `PagerTabStrip` is a method of displaying tabs for a `ViewPager`. And now that `ActionBar` has been deprecated for `Toolbar`, it seems that the `PagerTabStrip` is my only option. Except, I only see it comes out in the following style: !enter image description here I really just want normal tabs (with icons) the way I could do it with the ActionBar before like this: !enter image description here What is the proper way of doing this now? Should I use an old `TabWidget` and add tabs manually? Or is there a way of styling the `PagerTabStrip` that I didn't know about? EDIT: Here's the library I ended up using: <
Have a look at SlidingTabLayout from Google I/O Android App. It depends on SlidingTabStrip. You can see how it's used by doing a simple search: you add it to your layout and then just connect it with your `ViewPager` like so: slidingTabLayout.setViewPager(viewPager); There is a way to `setCustomTabView` to customize the tabs.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 16, "tags": "android, android fragments, tabs" }
How to unmarshal a json array with different type of value in it For example: {["NewYork",123]} For json array is decoded as a go array, and go array is need to explicit define a type, I don't know How to deal with it.
First that json is invalid, objects has to have keys, so it should be something like `{"key":["NewYork",123]}` or just `["NewYork",123]`. And when you're dealing with multiple random types, you just use `interface{}`. const j = `{"NYC": ["NewYork",123]}` type UntypedJson map[string][]interface{} func main() { ut := UntypedJson{} fmt.Println(json.Unmarshal([]byte(j), &ut)) fmt.Printf("%#v", ut) } `playground`
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 4, "tags": "json, go" }
View files saved after specific date in unix I try to open a group of files which were saved after a specific date using the following command View /*/*log | grep 'Aug 30' But I get a message as Vim: warning : output is not to a terminal And nothing happens. Any suggestions???
You are effectively telling `view` to open all the log files. You then tell it to send its output not to the screen as normal, but to another command called `grep`. You probably want to use `find` to generate a list of files and then tell `view` to open them. So, to find files changed yesterday (1 day ago), you could use: find /wherever/the/logs/are -name \*.log -mtime -1 Now, you want to edit those files, so pass the list to `view`: view $(find /wherever/the/logs/are -name \*.log -mtime -1)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "unix, grep" }
AdMob Earnings - How are they calculated How are AdMob Earnings calculated? Is it dependent on the number of clicks alone? Or is it dependent on the ads that are shown? Or a combination of both? One day I have 11 clicks that earned me $0.12 and the next day I have 14 clicks that earned me $0.51 and then one day I just earn $0.07 for 11 clicks. Here is the screenshot of my earnings from AdMob... !enter image description here
It also depends on the impression that it makes, if the ads are show many times and u get 11 clicks u get less money if the ads are displayed less time and you get 11 clicks u get more money. Also it got more of complex process Hope you understand try this link it may have what you are searching.
stackexchange-stackoverflow
{ "answer_score": 25, "question_score": 40, "tags": "admob" }
in Javascript, how to create the new array using another array The output that I want to have is newArray = [4, 9, 16, 25]. But I don't get it. Where did I make errors? Please help me. var array = [2, 3, 4, 5]; var result = []; function multiply(a) { return a * a; } function newArray (a) { for (i=0; i<a.lenght; i++){ result.push(multiply(a.value)); } } var newArray = newArray(array);
var array = [2, 3, 4, 5]; function multiply(a) { return a * a; } function newArray (a) { return a.map(multiply) } var result = newArray(array); console.log(result)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "javascript, for loop" }
Does windows 7 supports docker daemon? I have installed docker toolbox on windows 7. Every thing works well including docker-compose,docker-machine except docker daemon. **My docker version :** client: version:1.11.1 API version:1.23 os/Arch:windows/amd64 server: version:1.12.1 API version: 1.24 os/Arch: linux/amd64 When i execute `docker daemon` command, it throws this error > time="2016-9-08T14:39:53.685141700+05:30" level=fatal msg="Error starting daemon : The version of windows does not support the docker daemon" When i give `dockerd`, it throws > bash: dockerd: command not found Is there any steps to make it work? or windows 7 does not support?
No, it doesn't. Native Windows containers are still in development and I don't believe Windows 7 will be included in that supported list, Windows Server 2016 is being targeted. With Windows 7, Docker runs as a Linux VM under the covers.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "docker" }
A greedy cryptarithm > Find all solutions to > > > EAT > ATE > + EATEN > ------- > YUMMY > > > Where different letters represent different digits from 0 to 9. * * * Problem by myself
> Let's look at carries: col 4 to col 5 must be 1, hence carry $3\rightarrow 4 \in \\{1,2\\}$, $A \in \\{8,9\\},U \in \\{0,1\\}$ $Y=E+1$. From the last, carry $1\rightarrow 2 \in \\{0,1\\}$, but as cols 2 and 3 are completely identical their in and out carries must be the same, therefore all four carries are 1, $A=9,U=0,T+N=11,E+T=M$ > Therefore $N\le 8$, so $T\ge 3$; also $M\le 8,E \ge 1$, so $T\le 7$, $M\ge 4$. Summary so far: > $A=9,U=0$ $3\le T\le 7$ $1\le E\le 5$ $4\le M=E+T\le 8$ $Y=E+1$ $N+T=11$ but $E=5$ can be ruled out because it forces the collision $M=8,T=3,N=8$ > Let's split on $E$ and $T$: $E=1 \Rightarrow Y=2, (T,N,M) = (3,8,4),(4,7,5),(6,5,7),(7,4,8)$ \--- $E=2 \Rightarrow Y=3, (T,N,M) = (4,7,6),(5,6,7),(6,5,8)$ \--- $E=3 \Rightarrow Y=4, (T,N,M) = (5,6,8)$ \--- $E=4 \Rightarrow Y=5, (T,N,M) = (3,8,7)$ Oof, that wasn't pretty, but I think that's them all: > $9$ solutions.
stackexchange-puzzling
{ "answer_score": 5, "question_score": 3, "tags": "mathematics, calculation puzzle, no computers, alphametic" }
Select in Where Clause Well, I did some research before posting here and I haven't find the correct solution. Here is my SQL, I would like to improve the performance and remove select clause after where if possible by join or any other way. The catch is Table1 is the first table to join and it is the same table in Where clause. I am not sure whether I am doing it right or wrong. I would like to know if there is any other efficient way to get the same result SELECT T3.Id, T3.Name FROM dbo.Table1 T1 JOIN dbo.Table2 T2 ON T1.Id = T2.Id JOIN dbo.Table3 T3 ON T2.Name = T3.Name WHERE T1.fId = (SELECT fId FROM dbo.Table1 WHERE Id = 1)
You can do this with a simple join: SELECT T3.Id, T3.Name FROM dbo.Table1 T1 inner JOIN dbo.Table2 T2 ON T1.Id = T2.Id inner JOIN dbo.Table3 T3 ON T2.Name = T3.Name inner join dbo.Table1 T4 on T4.fId = T1.fId and T4.Id= 1
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "sql, sql server" }
How to get the input of a TinyMCE editor when using on the front-end? I'm not sure why I haven't been able to find this, but does anyone know how to get the input of the TinyMCE editor? I am using it in the front end and want to be able to save whatever the user has typed into the TinyMCE to a database but cannot find the best way to capture that value. The two solutions that I've implemented with some success are: 1. `tinyMCE.activeEditor.getContent();` \- This one seems to only get the value of the visual editor so if I'm in the HTML editor and make changes and then save, they aren't picked up. 2. `$('#html_text_area_id').val();` \- This one is the opposite, it only seems to get the value of the HTML editor. I know there is a better way - I just can't seem to find it... p.s Yes, I'm going to implement security measures to make sure people can't blow up the database.
Ok apparently WordPress keeps track of what kind of editor (visual or html) is active as a class which is added to the content wrapper so here is a solution that will get you the latest content in the editor function get_tinymce_content(){ if (jQuery("#wp-content-wrap").hasClass("tmce-active")){ return tinyMCE.activeEditor.getContent(); }else{ return jQuery('#html_text_area_id').val(); } }
stackexchange-wordpress
{ "answer_score": 23, "question_score": 8, "tags": "tinymce, wp editor" }
How to iterate over the file in python I have a text file with some hexadecimal numbers and i am trying to convert it to decimal. I could successfully convert it, but it seems before the loop exist it reads some unwanted character and so i am getting the following error. Traceback (most recent call last): File "convert.py", line 7, in <module> print >>g, int(x.rstrip(),16) ValueError: invalid literal for int() with base 16: '' My code is as follows f=open('test.txt','r') g=open('test1.txt','w') #for line in enumerate(f): while True: x=f.readline() if x is None: break print >>g, int(x.rstrip(),16) Each hexadecimal number comes in a new line for input
The traceback indicates that probably you have an empty line at the end of the file. You can fix it like this: f = open('test.txt','r') g = open('test1.txt','w') while True: x = f.readline() x = x.rstrip() if not x: break print >> g, int(x, 16) On the other hand it would be better to use `for x in f` instead of `readline`. Do not forget to close your files or better to use `with` that close them for you: with open('test.txt','r') as f: with open('test1.txt','w') as g: for x in f: x = x.rstrip() if not x: continue print >> g, int(x, 16)
stackexchange-stackoverflow
{ "answer_score": 78, "question_score": 53, "tags": "python" }
Parse for string in string php I have a problem with regular expressions in PHP. I have a string: "NAPLAK ROSSO+S.ARG.+LACC.ARG.+NK", all of this words contain options like ROSSO,S.ARG, Are colors ROSSO = Red, s.arg = silver and so on. Out of this string i need to generate a description like: Material: Naplak, Color: Red, Silver.... .... I thought, that there is going to be an array with laguage codes something like this: $options = array( "ROSSO" => "COLOR_RED", "S.ARG" => "COLOR_SILVER" ); Could you please help me to write a regular expression for this purpose? Best regargs, RussianRoot.
I don't think you need regex for this. Probably easier and faster to do something like: $item = explode(' ', "NAPLAK ROSSO+S.ARG.+LACC.ARG.+NK"); $args = explode('+', $item[1]); $item = $item[0]; echo $item; Gives us "NAPLAK" print_r($args); Gives us: array(4) [ 'ROSSO', 'S.ARG', 'LACC.ARG.', 'NK' ];
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, regex, string, parsing" }
How to identify that the string is a path to any file, using PHPcode? Using PHP, How to identify that the string is a path to any file?
< $path = 'string'; if(is_file($path)){ // look, it's a file! }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php, filepath" }
SQL Server 2005 vs. ASP.net datetime format confusion I've found a similar question on stack overflow, but it didn't really answer the question I have. I need to make sure that my asp.net application is formatting the date dd/mm/yyyy the same as my SQL Server 2005. How do I verify the date culture (if that's what it's called) of the server matches how I've programmed my app? Are there specific database settings and OS settings? Is it table-specific? I don't want to transpose my days and months. thank you
When you get a DateTime out of the database, it should be in a non-cultured format (like the DateTime object, based on the number of ticks since a certain date). It is only when you are converting that value into a string that you need to be concerned with culture. In those cases, you can use yourDateTimeValue.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) to make sure that the information displays correctly.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "asp.net, sql server 2005, datetime, culture" }
typescript. array returning type of argument function last(anArray:any[]) /*:????*/ { return anArray[anArray.length-1]; } Without resorting to generics, is it possible to specify the return type in the function above being the type of the elements of the argument so let strs:string[]=["aaa","bbb","ccc"]; let lastStr=last(strs); // type of lastStr should be string let dates:Date[]=[new Date]; let lastDate=last(dates); // type of lastDate should be Date **Edit** : Seeing the fine answer from @Titian Cernicova-Dragomir I should have stated "Without resorting to generics when invoking the function"
Not sure why you say 'without resorting to generics'. This is exactly the reason for generics in typescript. Using generics is not that hard: function last<T>(anArray:T[]) :T { return anArray[anArray.length-1]; } // usage let strs:string[]=["aaa","bbb","ccc"]; let lastStr=last(strs); // string let dates:Date[]=[new Date()]; let lastDate=last(dates); //date Without generics there is no way to accomplish this.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "typescript, return type" }
What is the difference when parsing between Tab and Spaces in sql server 2008 R2 I have encountered a scenario below Declare @var int = ' 123' select @var Declare @var1 int = ' 123' select @var1 for the first case I have used spaces in front of the value and while execute it returns value as 123 In Second case I have used tab instead of space in front of value and while execute it throws conversion error Can anyone let know what is the difference between these 2 scenario..
Even though you have put same number of spaces (using spaces and then Tab) the character codes for both of them is different and that is the reason that space and TAB are treated as separately in SQL Server. More information about character codes and character encoding can be found at below 2 links:- < < Also if you think mathematically and logically:- having spaces before integer numbers does not make sense. It's like having zeros before numbers. For Example:-' 123' (5 spaces and then 123) is like 00000123. Yet one more reason that spaces are trimmed before the integer numbers
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, sql server, sql server 2008" }
Delete documents using lucene 4 and retrieve all docIds of deleted docs I am using Lucene 4 to persist my data. The problem I'm facing right now is the following: How to delete documents from the index and then retrieve the docIds of the deleted documents? Here is the method I use to delete the documents: Query query = new BooleanQuery(); ... indexWriter.deleteDocuments(query); but once this method invoked, I haven't found a way (method or callback) to get deleted documents (and their fields). Does anyone have an idea on how to do that?
I don't think you can do this in one call. As Lucene deletes don't happen immediately (extra `commit()` is required), returning deleted document ids would be a bit ambiguous. If you look inside delete method, it actually just adds jobs to one of the delete queues. That said, `commit()` doesn't return anything related to this either ;-( Anyway, the only way I can think of is to run your `query`, gather documents/document IDs and run the `deleteDocuments(query)` afterwards. You might get some overlap (say if another thread would delete the same documents) but this is inevitable because of the `commit()` phase.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, lucene" }
What exactly are DRM keys? I was thinking of unlocking my ST17i's bootloader but I saw on the Sony Mobile website that unlocking the bootloader will result to the deletion of DRM keys from my phone. What exactly are they? And what will be affected if I lose the said "DRM keys"?
DRM stands for "Digital Rights Management", and mainly is used with sold eBooks/PDFs and the like (and also for sold music files plus maybe even videos). Those keys are to identify your ID as to prove if you have permission to access those documents. If you never bought any of those "crippled" documents, chances are you don't have to bother.
stackexchange-android
{ "answer_score": 4, "question_score": 2, "tags": "bootloader, drm" }
Check if Field is from specific class To display keys & values of a dataobject, I'm using a Collection of AccessibleObjects to generate a table. The AccessibleObject'S are collected on a specific time, but the values are read, when the render have to render the table. The Problem: I'm not only want to hold AccessibleObject's of one specific Class. Is it possible to check a AccessibleObject Class-Origin? e.g. `accessibleObject.fromClass(classType);`
Do you mean Member member = field or method; Class clazz = member.getDeclaringClass() to get the class the field appears in. Note: this is the actual class, not the class you might have used to look it up. e.g. say A has a field `x` and a subclass B. If you get field x of class B, it will say the declaring class is A. This is because A and B can have a field called `x`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, reflection" }
How to measure area height and width in pixels (rather than cm) in Photoshop CS6? I just started using Photoshop CS6 because i needed to make a design for an application. I wanted to use the rectanglure marquee tool to messure the height and width of an square in pixels but instead the tool is showing it in centimeters, like this: ![]( The tool is showing the height and width in cm and i want that it show it in pixels. How can I do this?
Press `Ctrl`+`R` to bring up the ruler. Then right-click the ruler and select _pixels_.
stackexchange-superuser
{ "answer_score": 13, "question_score": 8, "tags": "adobe photoshop" }
Why does question mark show up in web browser? I was (re)reading Joel's great article on Unicode and came across this paragraph, which I didn't quite understand: > For example, you could encode the Unicode string for Hello (U+0048 U+0065 U+006C U+006C U+006F) in ASCII, or the old OEM Greek Encoding, or the Hebrew ANSI Encoding, or any of several hundred encodings that have been invented so far, with one catch: some of the letters might not show up! If there's no equivalent for the Unicode code point you're trying to represent in the encoding you're trying to represent it in, you usually get a little question mark: ? or, if you're really good, a box. Which did you get? -> Why is there a question mark, and what does he mean by "or, if you're really good, a box"? And what character is he trying to display?
There is a question mark because the encoding process recognizes that the encoding can't support the character, and substitutes a question mark instead. By "if you're really good," he means, "if you have a newer browser and proper font support," you'll get a fancier substitution character, a box. In Joel's case, he isn't trying to display a real character, he literally included the Unicode replacement character, U+FFFD REPLACEMENT CHARACTER.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 5, "tags": "browser, unicode, utf 8" }
Can I use Pro-Tools 9 on my PC and Mac I am thinking moving to Pro Tools 9 soon, but I am unsure if I can register Pro tools 9 on both my PC and Mac, cause sometimes I need to work on both systems and its going to get messy.
With iLok you can use it on both Systems, however, only one at a time.
stackexchange-sound
{ "answer_score": 3, "question_score": 2, "tags": "pro tools, post production, software, mac, pc" }
Do low voltage "Nixie tubes" exist? I want to make a small clock using Nixie tubes (for the cool/retro/steampunk look of them), I have some basic knowledge of electronics, but I have never done anything with more than 12V DC and ~10A. I saw that Nixie tubes are usually using 3mA at 180V in order to make the Neon glow and I am concerned with the safety concerns. Because I do not want to hurt myself with a shock of 180V caused by a mistake due to my poor experience with high voltage, **I wonder if some indicator tubes that look like Nixie ones are functioning in low voltage/current ?** I know no Nixie tubes at low voltage can not exist because the gas needs to be excited to produce light, thus, the "look like" is very important.
No, low voltage _nixie_ tubes do not exist. But if you're after that nixie tube "look" you can buy Numitrons that work at 4.5v. < for an example of what a Numitron looks like.
stackexchange-electronics
{ "answer_score": 4, "question_score": 5, "tags": "safety, low voltage, nixie" }
What does the classifying space of a topological monoid classify? The classifying space $BG$ of a topological group $G$ classifies principal $G$ bundles. I have come to appreciate this. I hope the following question is appropriate for MathOverflow: What does the classifying space of a topological monoid classify?
Section 5 of Segal's Classifying spaces related to foliations shows that for discrete monoids $M$ the space $BM$ still classifies principal $M$-bundles (in a suitable sense). In Moerdijk's _Classifying spaces and classifying topoi_ there is a kind of answer for general topological monoids (Cor IV.4.5); it is not in terms of principal bundles though, but rather in terms of linear orders. (He formulates it for topological categories, but topological monoids are just topological categories with one object.) His version with principal bundles (Section IV.2) has again a discreteness condition.
stackexchange-mathoverflow_net_7z
{ "answer_score": 7, "question_score": 10, "tags": "at.algebraic topology, classifying spaces" }
What does “up through” mean? I'm a newbie in English. While I was reading a book, I found that phrase in "(something) will be the topic of the following chapters up through Chapter 3.", but I don't understand what it means.
_Up_ here names the direction of reading. Presumably the author thinks of readers 'ascending' from Chapter 1 to Chapter 2 to Chapter 3 ... going _up_ the scale of numbers. _Up_ is really superfluous here--but colloquially we US speakers are getting fonder and fonder of giving our utterances a little extra dynamism with prepositions like that, and the use is common in all but the most formal styles these days. _Through_ names the 'distance' of reading during which the topic will be in the foreground: not **to** Chapter 3, which would imply that when the reader gets to Chapter 3 the topic will change, but **through** Chapter 3, all the way to the end of Chapter 3.
stackexchange-ell
{ "answer_score": 2, "question_score": 1, "tags": "prepositions" }
Let $f(x) = x^5 + x^3 + x$. Assuming that f is invertible, find $f^{−1}(3)$ I'm having difficulty with this question. Am I supposed to change the function to its inverse form, $x = y^5 + y^3 + y$. Also what does it mean that $f$ is invertible? How should I isolate for $y$? Thanks in advance.
**Hint** : Assume that "$f$ is invertible" means that you can start with the assumption that some function $f^{-1}$ with $f\circ f^{-1} = f^{-1} \circ f = {\rm id}$ exists. You don't have to find a term representing it. You only have to find a (by assumption of existence of the inverse, **the** ) real number $x$ such that $f(x) = 3$, as: $$ f(x) = 3 \iff x = f^{-1}(3). $$ Can you see such a number? (Just try) * * * Addendum: If you want to prove the invertibility, you can use that $f$ is monotonically increasing, but the question - as stated - does not tell you to do that. You can just use the invertibility.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "calculus" }
No uncountable subset can be well-ordered $\iff$ Hartogs ordinal is $\omega_1$ I'm looking at an exercise which starts as follows: > Suppose that no uncountable subset of $\mathcal P\omega$ can be well-ordered (equivalently, the Hartogs ordinal $\gamma(\mathcal P\omega)$ is $\omega_1$). In order to proceed with the exercise I should probably understand this equivalence. I guess that "no uncountable … can be well-ordered" means "there is one that can't be well-ordered", otherwise any finite set would be a counterexample (as they don't have such uncountable subsets yet their Hartogs ordinal is surely not $\omega_1$). Having this said, I get that the existence of an uncountable subset that can't be well-ordered implies that $\mathcal P\omega$ doesn't inject into $\omega_1$. However, why does it imply that $\omega_1$ doesn't inject into $\mathcal P\omega$?
If an ordinal can be mapped injectively into a set, then the range of such injection has an induced order isomorphic to your ordinal. In this case we are talking about the least uncountable ordinal, or $\omega_1$.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "set theory, order theory" }
how to calculate the mean value of an incomplete matrix with maxima? maybe I miss the obvious, but how do I get the mean value of the following matrix ? matrix( [ , , ], [7.5133, , 5.3 ], [4.93 , 5.7667 , 2.9067 ] ); I tried mean, geometric_mean, ... and the other commands from the descriptive package, but they don't work with missing values. regards, Marcus
I think one have to implement it. For example M: matrix( [ und , und, und], [7.5133, und, 5.3], [4.93 , 5.7667 , 2.9067] ) $ ulength(x):=block([n: 0], matrixmap(lambda([e], if e#'und then n: n + 1), x), n) $ usum(x):=block([s: 0], matrixmap(lambda([e], if e#'und then s: s + e), x), s) $ umean(x):=usum(x)/ulength(x) $ umean(M);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "symbolic math, maxima" }
How to convert a numeric date vector into text date vector? I have a numeric vector corresponding to dates in the following format yyyymmdd, ie for December 24th, 2010 it is 20101224. How can I convert it into text format, i.e. in the following format 'mm-dd-yyyy'?
You should really use `datetime` rather than convert to strings, dates = datetime(20100124,'ConvertFrom','yyyymmdd') The first input can be a numeric vector, assuming it's of the yyyymmdd format. If you then want to specify a display format use, dates.Format = 'MM-dd-yyyy' If you really need them as strings you can then use, dates = datestr(dates)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "matlab, date, datetime" }
PHP mail() function not working I've been trying to configure the mail() function for 3 days by now, and I'm running out of ideas. I've installed and configured postfix as a satellite, following this guide: How to have my PHP Send mail? but it seems I lack the file /etc/postfix/sender_canonical (and of course I have no idea of what to put inside it). By now this is the only clue I have about the problem... I'm trying to run it on Ubuntu 12.04 laptop, built with x32 architecture. **EDIT:** After a few iterations of apt-get purge and apt-get install, mail() started to return true, the error log has stopped growing so it seems all ok, but no mail managed to reach my inbox, not even as spam.
This might be overkill for what you want, but following the directions here: < and literally just copy pasting all commands and following the directions carefully should get you there. I run 12.04 on three different systems and have set all of them up this way - i've had zero problems with mail(). I'm still a bit of a newbie at this, so like i said - it might be overkill for what you need. Hope it helps though.
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 1, "tags": "12.04, php, postfix, sendmail" }
How to extract the values from a string from slack ruby bot I am trying to create a slackbot which can save incoming data to a database. I have used the gem `slack-ruby-bot` and I'm able to receive my text, but I want to extract specific parts of the text, to save in a database. ### Given the following received text: * I worked on 'stackoverflow' for 10 hours. I must be able to extract the project name, **stackoverflow** , and the hour, which is **10**. Is there someway to do it? command 'activity', '/^Activity/' do |client, data, match| client.say(text: "#{data.text}", channel: data.channel) end This is just a sample code which gets the command activity.
Wherever you receive the string, you might use the regular expression and `String#scan` to get the data. "I worked on 'stackoverflow' for 10 hours.".scan /'[^']+'|\d+/ #⇒ ["'stackoverflow'", "10"]
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby, ruby on rails 5, bots, slack" }
How do I add a Python-style Get() method which takes a default value to my C# dictionaries? I'd like to be able to specify a default value to return if the key I specify can't be found in the dictionary. e.g. int default = 5; string key = "MyKey"; int foo = myDictionary.GetValue(key, default); if `key` is in `myDictionary` `foo` should hold the value from the dictionary, otherwise it will hold `5`.
I found a piece of code here which does the job nicely by adding an extension method to IDictionary: using System.Collections.Generic; namespace MyNamespace { public static class DictionaryExtensions { public static V GetValue<K, V>(this IDictionary<K, V> dict, K key) { return dict.GetValue(key, default(V)); } public static V GetValue<K, V>(this IDictionary<K, V> dict, K key, V defaultValue) { V value; return dict.TryGetValue(key, out value) ? value : defaultValue; } } }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c#, dictionary, default value" }
Chopin Polonaise in Ab major, op 53 change in key In Chopin's polonaise in A-flat major, op.53, in the second section the key changes from A flat to E major. What type of change is this? Is it from the flattening of the sixth (F-flat major), or was it made some other way? ![enter image description here]( ..................................................................................................................... ![enter image description here]( ![enter image description here](
You're exactly right! It's technically a motion to VI, which would be F major. But in order to make it easier to read, he spells it in E major (V). F isn't in A major, but it _is_ in A minor; thus this is an example of mode mixture. The modulation is created by the common tone between the original A tonic and the new E tonic. A becomes the chordal third (G) of the new key to create a smooth modulation. This move to VI is really common in the Romantic era. Schumann's "Widmung" does the exact same modulation, and in the exact same key!
stackexchange-music
{ "answer_score": 16, "question_score": 10, "tags": "theory, harmony, key, key signatures, modulation" }
Horizontal bars analysis I'd like to add a visual progress bar as per my image below onto a website. I've searched for an easy way to do something like this either by embedding a chart or using CS and the result is poor. I want to code it manually as I will need update the values. I'd be really greatful for any ideas! !Image Many thanks
The following will get this result: !enter image description here <div class="text">Example Text</div> <div class="container"> <div class="bar"></div> </div> CSS: .container{ border:1px solid gray; height:8px; width:200px; padding:1px; display: inline-block; } .bar{ background-color: purple; width:50%; /*change this for progress*/ height: 100%; } .text{ display:inline-block; } This styling will make it look the same as your examples. You would then position the analysis bar by adding css tot he container class. You can dynamically change the progress with JavaScript/jQuery using this: $('.bar').css('width', '76%'); where 76% is chaged to whatever % value you need.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, css" }
Resetting the database in Rails 4 So I made a new branch in git to continue my rails study as suggested in Michael Hartl's 3rd edition. I used rails console to create a new user so that I could setup the user page (at this time we did not have the sign up form). So per instructions it says > Since we’re about to add the ability to create new users through the web, let’s remove the user created at the console in Section 6.3.4. The cleanest way to do this is to reset the database with `bundle exec rake db:migrate:reset` I was under the impression that `db:reset` is suppose to dump the current database and rebuild it from the schema.rb, but for me it deletes everything in my schema leaving it blank and I have to copy an earlier version of my schema from another branch. Is there something I'm not doing correctly or overlooking? I thought I understood the db::xxxx commands but apparently not as well as I fooled myself into thinking ha.
Nope, this is the expected behavior. The test data resets every time you run the tests unless you provide seed date. You should check out Factory Girl to build objects for your test database: < Hartl covers Factory Girl later in the book/tutorial, so you might not have gotten to that part yet. So you are partially correct; rake db:reset will rebuild your schema, but all the data will be destroyed. It's a bad idea to use a copy of an existing database for testing purposes. To rebuild the schema I usually run: rake db:test:prepare Works every time.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "git, ruby on rails 4, sqlite" }
Ingres: how to read the database in a specified encoding in PHP? I've to use CakePhp with ingres. The problem is that I've to use UTF-8 in the website and the database is provided in ISO-8859-1. So my question is, how to manage this charset problem? On MySql I know I can run a "SET NAMES UTF-8" request on the database, but I can't find how to do this with ingres? Thank you very much!
Unfortunately the encoding/character set is defined at a system level using the environment variable `II_CHARSETxx`. See the output from `ingprenv` to get your value. You can change it but you are likely to get data corruption. Your best bet to work with UTF-8 is to use N(VAR)CHAR, instead of VARCHAR and the PHP driver will assume that all data coming in is in in UTF-8 and convert to-from UTF-16. This conversion is controlled by the ini setting `ingres.utf8` (see <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, cakephp, character encoding, ingres" }
How to unobtrusively bind a function to an element's click when the element was created with AJAX I have a nested form in my app that uses AJAX to load an additional sets of fields. One of those fields is a file upload that I want to hide and effectively replace with a text field for pasting a Youtube link. It works for the first sets of fields, however since the function is bound on document.ready, it doesn't work for new AJAX fields. I need to bind it some other way. What do? $ -> $(".foo").click -> $(this).css "display", "none" Update: I wasn't having luck, so I went to read the jQuery .on() documentation, and it reminded me of what Fresheyeball said about binding it on to a parent div. After that, it worked perfectly. Thanks for the great advice! $ -> $("#create").on "click", ".foo", -> $(this).css display : "none"
The new jQuery .on should work for you: $(document).ready -> $(window).on 'click', '.multiswitchr', -> that = $(this) that.css display : 'none' that.closest(".fields").find(".f-upload").first().css display : "none" that.closest(".fields").find(".attachment-holder").first().css display : "none" that.closest(".fields").find(".youtube-link").first().css display : "inline" The way this work is it binds the listener to `window` (or you can use the direct parent) to listen for the existence of `.multiswitchr` and binds the `'click'` event to it. P.S. in coffeescript the shorthand for document ready is just `$ ->`
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, jquery, ajax, coffeescript" }
How can I stop Ubuntu linux trapping the CTRL-tab key combination? I want to use `Ctrl` \+ `Tab` in an emacs application. But the Ubuntu 10 OS under GNOME traps this key combination. How can I disable it?
You can change the Gnome keybindings by running the program `gnome-keybinding-properties` from a terminal window (or alternately from the Gnome menu _System->Preferences->Keyboard Shortcuts_ ).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "ubuntu, keyboard shortcuts" }
Using a given formula find the probability Let $X_n\sim B(n,\frac{1}{2})$, where $n=100$. Calculate $P\\{|X_n-\frac{n}{2}|\geq\frac{\sqrt{n}}{2}\\}$ using following formula: $$ P\\{k_1\leq k \leq k_2\\}\approx \Phi(\frac{k_2-np}{\sqrt{npq}})-\Phi(\frac{k_1-np}{\sqrt{npq}}),$$ where $0<p<1$, $q=1-p$ and the function $\Phi$ is defined: $$\Phi(x)=\frac{1}{\sqrt{2\pi}}\int_0^x e^{-\frac{t^2}{2}}dt, x\in \mathbb{R}. $$
We have $$P\big\\{|X_n-\frac{n}{2}|\geq\frac{\sqrt{n}}{2}\big\\}=1-P\big\\{|X_n-\frac{n}{2}|<\frac{\sqrt{n}}{2}\big\\}.$$ Also, $$|X_n-\frac{n}{2}|<\frac{\sqrt{n}}{2}$$ is the same event as $$\frac{\sqrt n}2-\frac n2<X_n<\frac{\sqrt n}2+\frac n2.$$ So,$$P\big\\{|X_n-\frac{n}{2}|\geq\frac{\sqrt{n}}{2}\big\\}=1-P\big \\{\frac{\sqrt n}2-\frac n2<X_n<\frac{\sqrt n}2+\frac n2\big\\}.$$ Now, you can use the formula given.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "probability, random variables" }
How to get the answer to $\int \frac{dx}{\sqrt{2x-5}}$ It looks fairly simple: $$\int \frac{dx}{\sqrt{2x-5}}$$ The answer is $$\sqrt{2x-5}$$ How is this done?
Make the substitution $$u = 2x-5$$. Then $$du = 2 dx $$. So after the change of variables, we have $$\frac{1}{2}\int \frac{1}{\sqrt {u}} du$$ You should be able to take it from here.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "integration, indefinite integrals" }
Clever way to find the maximum element in an array recursively I know recursion is not the best way to do what i described in the title, but it's an exercise. I was wondering if there's any way of finding the maximum in an array recursively (in C) with the following conditions: * No static variables allowed; * If the first element is passed as a parameter, it would be cool to do so without the writer of the main block actually doing it (e.g. the writer passes the array and the dimension of the array, but the function uses `array[dim-1]` as the first maximum) Thanks for the answers!
The basic idea is to realize that the maximum of an array is the larger of the first element and the maximum of the sub-array with the first element removed. Then you call the max function on the sub-array to get the maximum of that array. (I'll let you code the rest.)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -3, "tags": "c, recursion" }
c# passing instance of different Windows.Forms types I have a function, which accepts a Parameter from type `System.Windows.Forms.Label`, so im able to pass a specific Label-Instance, so far so good. But i want to keep this Parameter as flexible as possible. So for example, i want also to be able to pass a Textbox-Instance as Parameter to the function, or anything else, **which provides the`.Text` property and is `invokeable`**. So I have this: public void Test(Label targetLabel) { //stuff } But i want something as flexible as possible, something like public void Test(object target) { //stuff } \--> but then how do i convert `target` into the right Type which is a) `Invokeable` b) has the property `.Text` * otherwise throw exception or something?
Accept anything of Type `System.Windows.Forms.Control`. Control.aspx) is the Class that first declares the .Text property and also implements the `ISynchronizeInvoke`.aspx) interface (which brings the `*Invoke` methods into play).
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "c#" }
ASP.NET Conversion of DataRow[] to DataTable How to get a DataTable from DataRow[] collection ? I tried the following conversion , but it returns null. string ProcessQuery(ref DataRow[] rows) { DataTable _tb = new DataTable(); foreach (DataRow _dr in rows) { _tb.Rows.Add(_dr); } _tb.AcceptChanges(); ... ... } Request your help.
Each dataRow has a Table property, So if you have the datarows DataRow[] just pick any row and go: rows[0].Table string ProcessQuery(ref DataRow[] rows) { DataTable _tb = rows[0].Table; // other stuff }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "asp.net, ado.net, datatable, datarow" }
relation tableName does not exist - PostgreSQL I have a database named **mimic** on my **postgres DB** . I'm trying to execute this command : select hadm_id from admission_ids where hadm_id in (select distinct on (subject_id) hadm_id from (select * from admissions order by admittime) tt but I receive this error : **relation "admissions" does not exist** When I modify the query by changing admissions to mimic iii.admissions it works. knowing that mimic iii is the schema , when I type this query this is the result that appears: SELECT table_name FROM information_schema.tables WHERE table_schema = 'mimiciii'; table_name -------------------- admissions callout caregivers datetimeevents ... My question is what can I do to make the user type only the name of the table without using the schema.tableName ?
> My question is what can I do to make the user type only the name of the table without using the schema.tableName ? By putting the schema into your `search_path`. Besides `SET search_path TO ...` which is valid for the duration of the session, it can be made permanent per user with `ALTER USER username SET search_path='...'`, or per database with `ALTER DATABASE dbname SET search_path='...'`.
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "postgresql, query" }
SELECT using schema name I have an issue with psql. I am trying to select the records from a table but psql acts like the table doesnt exist. I have tried finding it and found that it resides in the 'public' schema. I have tried selecting from this table like so: highways=# SELECT * FROM public.CLUSTER_128000M; This does not work stating the following: ERROR: relation 'public.CLUSTER_128000M' does not exist I know that it definetly exists and that it is definetly in the 'public' schema so how can I perform a select statement on it? ### Edit: This was caused by useing FME to create my tables. As a result FME used " marks on the table names making them case sensitive. To reverse this see the comments below.
This issue was caused by the third party software FME using quotes around the names of the tables at time of creation. The solution to make the tables useable again was to use the following command: ALTER TABLE "SOME_NAME" RENAME TO some_name
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "postgresql" }
IRA contribution income limits different than deduction income limit? I never had to consider it, but am I correct in noticing that the income limits Traditional IRA contribution are different than the income limits for actually taking the tax deduction? The conundrum to me is that traditional IRA is supposed to be pretax, but if I have to coordinate the transfer myself (with the remainder of withheld employment income) because my employer has no facility to make the tax exempt deduction per paycheck, then I need to take a tax deduction during tax time. Can I be under the income limit for contributions, but over the income limit for taking the tax deduction? Let me know if I am misunderstanding this, thanks!
There is no income limit for making Traditional IRA contributions. There are only income limits for the tax deductibility of such a contribution, given by the IRS here. If you above that income limit, then you are almost certainly better off doing a Roth IRA contribution except in special cases. Traditional IRA contributions that are deductible are similar to 401(k) contributions, but not associated with your employer. You make the contribution on your own through a financial institution you choose. The deductibility benefit comes in when you file your tax return, and your IRA contribution will lower the amount of tax you owe (assuming you are eligible). You may want to decrease your tax withholding with your employer so you don't end up with a large refund because of this.
stackexchange-money
{ "answer_score": 2, "question_score": -1, "tags": "united states, taxes, ira, income, self directed ira" }
Can Blackberry devices sync directly to Exchange? We've got Exchange configured for Outlook Anywhere/Mobile Access which allows us to sync using ActiveSync on Windows Mobile and "Mail for Exchange" on Nokia devices. Can a Blackberry device work in a similar way? We've got somebody who has a Blackberry Storm on a personal contract. Need to know whether it'll work like the above or another handset is needed. Cheers, Rob.
Try NotifySync works with Exchange and many other messaging servers.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 2, "tags": "exchange, blackberry, activesync" }
Execute Python files in windows 7 CMD I have installed python 32 package to the > C:\python32 I have also set the path: > PYTHONPATH | C:\Python32\Lib;C:\Python32\DLLs;C:\Python32\Lib\lib-tk; but I still cannot run files typing "python file.py" using cmd. What else should i do? Thank you for your answers
Add your Python's installation directory to `PATH`: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python" }
How do I get the Intellij code autoformatter to keep an annotated field on one line? Whenever I run the IntelliJ autoformatter - it converts this: @Autowired private CustomerDao customerDao; into this: @Autowired private CustomerDao customerDao; How can I stop it from doing that?
Navigate to **Preferences -> Editor -> Code Style -> Java -> Wrapping and Braces tab**, then locate the section **Field annotations** and check the option **Do not wrap after single annotation**. In IntelliJ v14: !eIntelliJ v14 Java style preferences
stackexchange-stackoverflow
{ "answer_score": 39, "question_score": 25, "tags": "intellij idea, code formatting" }
How to share Directus project? I'm currently running Directus project and PostgreSQL database on localhost and everything works fine. For now, I have to share this project with another person, but in the source folder of the project there are no generated files that I can share, so I assume everything is saved in node_modules. How to correctly share the project or push it into GitHub? **Directus version: 9.9.0**
Everything you need to share an instance of Directus is in the database, within the asset storage (folder), the `.env` file, and any custom extensions you've created. Hopefully, that helps!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "node.js, directus, headless cms" }
'object Object' variable displayed on a form input field In my AngularJS template I have the following login input field section. It is currently autopopulating the input field with rather than the email address address, it is showing up as in the email field (rather than [email protected] etc..) [object Object] my template/view <input ng-model="form.email" type="email" name="email" placeholder="Email" autocomplete="off"> The ng-model using the variable form.email (although I cannot see where exactly that is coming from yet) - what could be wrong?
Make sure that `form.email` should be a `string` not an `object`. **Working demo :** var app = angular.module('myApp',[]); app.controller('MyCtrl',function($scope) { $scope.form = { email: "[email protected]" } }); <script src=" <div ng-app="myApp" ng-controller="MyCtrl"> <input ng-model="form.email" type="email" name="email" placeholder="Email" autocomplete="off"> </div>
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "javascript, angularjs, object" }
Can a DB table with just one column be in 3NF and can a table with two fields both the primary key be in 3NF Hi this maybe simple but I'm trying to teach myself database design and I was wondering if the following is true. 1. Is a table with just one column in 3NF given that each value is a primary key? e.g. Supplier table with the column name, assuming each supplier name is always unique 2. Is a table with two fields that make a composite primary key in 3NF? e.g. orderitems table with the columns ordernumber and itemID, assuming that order number and item ID are held in their own relevant tables e.g. order and stock_items. Thanks in advance.
Any relation which has only one candidate key and has no non-key attributes is automatically in at least 6th Normal Form.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "database design, normalization" }
R boxplot long names out of the plot area My boxplot names are long and making it vertical chop these names. How can I avoid the names/labels of boxplot going out of the plot area? dat <- data.frame(values = rnorm(100), group = gl(2, 50)) levels(dat$group) <- c("reallyreallylonglabel", "anevenlooooooooooooongerlabel") boxplot(values ~ group, data = dat, las = 3)
Increase the bottom margin using the par() function. par(mar=c(14, 3, 1, 1)) boxplot(values ~ group, data=dat, las=3)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "r, label, boxplot" }
Problem finding elements by class with beautiful soup I am trying to get the name of the events on this page, using beautiful soup 4 : < I tried to filter the html code for tags with class="biab_item-link biab_market-link js-event-link biab_has-time", has it seemed to be the ones containing each unique event name once. Here is my code from bs4 import BeautifulSoup import urllib3 http = urllib3.PoolManager() url = ' response = http.request('GET', url) soup = BeautifulSoup(response.data, features="lxml") for tag in soup.find_all("a", class_="biab_item-link biab_market-link js-event-link biab_has-time"): print(tag["title"]) But nothing happens.
That's because html content is dynamically changed by javascript. Data came from this URL: < but honestly I don't know where can you find these IDs. This URL returns JSON response which you can easily parse using Python library.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, web scraping, beautifulsoup" }
Decrypting message hashed with SHA256 I was given a 16 byte key(used to encrypt message in RC4). First 8 bytes are unknown for me. I know that key was created by hashing a message using SHA256(secret) and getting first 16 characters from string obtained from this hashing function. Unfortunately i don't see a way to get the first 8 bytes of this key. As i know SHA256 is one way hashing function(we cant decrypt it). So how i can use half of the key to get a whole? I would be grateful for giving me some advice.
You answered your own question. The point of a hash is that it's very hard to get the original value, and that the hash changes completely when even a single bit is different. The 8 bytes you're looking for could be anything, dependent solely on the original value that was being hashed. If you don't know the original value, there is no way to determine what the first 8 bytes of the hash are.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, sha256, rc4 cipher, sha2" }
How many elements does $\mathbb{Z}_2(a)$ have, where $a$ is a zero of $f(x)$ in some extension field of $\mathbb{Z}_2$ > Let $\mathbb{Z}_2=F$. Let $f(x)=x^3+x+1\in\mathbb{Z}_2[x]$. Suppose $a$ is a zero of $f(x)$ in some extension field of $\mathbb{Z}_2$. How many elements does $F(a)$ have and express each member of $F(a)$ in terms of $a$. My Try: Some info I understand: $f(x)$ has degree $3$ and doesn't have a root in $\mathbb{Z}_2$, so we conclude that because the degree is low, there are $f(x)$ is irreducible in $\mathbb{Z}_2$. Since $f(x)$ is irreducible I know that $\mathbb{Z}_2[x] / \langle f(x)\rangle $ is a field(I'm not sure if this information is relevant to the question or not.) $a$ is a root so $f(a)=0$ in some extension field of $\mathbb{Z}_2$ Can someone help push me in the right direction?
The field consists of all polynomials in $\mathbb{Z}_2[x]$ of degree at most $2$ evaluated at $a$. This is because the field $\mathbb{Z}_2[x]/\langle f(x) \rangle$ is "produced" by taking all polynomials in $\mathbb{Z}_2[x]$ and reduce them modulo the polynomial $f(x)$.
stackexchange-math
{ "answer_score": 1, "question_score": 3, "tags": "abstract algebra, field theory, extension field" }