INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Easy SQL Query Classification ! I would like to fill the win column with the classifications win or lose with win defined as 1-3 place finish and loss as everything else.
UPDATE table set win = 'lose' WHERE place NOT in (1,2,3); UPDATE table set win = 'win' WHERE place in (1,2,3); OR with a little CASE statement UPDATE table set win = CASE WHEN place IN (1,2,3) THEN 'win' WHEN place NOT IN (1,2,3) THEN 'lose' END ;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "mysql, data extraction" }
Verifying a certificate I am trying to validate a certificate I got from Apple with their own intermediate and root certificate. This is what I do and the answer I get: c:\dev\OpenSSL-Win64\bin>openssl.exe verify -CAfile k:\MDM\AppleIncRootCertificate.pem k:\MDM\AppleWWDRCA.pem k:\MDM\mdm_public.pem k:\MDM\AppleWWDRCA.pem: OK k:\MDM\mdm_public.pem: UID = NQLH5GG9T6, CN = MDM Vendor: E A/S, OU = E A/S, O = E A/S, C = DK error 20 at 0 depth lookup:unable to get local issuer certificate Does anyone have an explanation or solution to this?
The problem is the way I use `openssl verify` which is incorrect. The certificate chain needs to be concatenated in a file (AppleIncRootCertificate.pem and AppleWWDRCA.pem) and the correct use is like this: openssl.exe verify -CAfile k:\mdm\cert_chain k:\MDM\mdm_public.pem Which results in: k:\MDM\mdm_public.pem: OK
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "certificate, ssl certificate, verify" }
Is there a vocal interface system for Ubuntu (able to map voice commands to console commands and parameters)? As far as I can remember, on some of even pretty old cellphones it was possible to say a name to be dialled. From this I conclude that it is possible and not very complex to implement. So, do such a system exist, which listens to voice commands, converts them to console commands according to a predefined map and executes?
< As i know it features and language to develop own modules. You should give it a try.
stackexchange-askubuntu
{ "answer_score": 4, "question_score": 7, "tags": "sound, command line" }
Read remote registry in python I am able to read the registry key on a local machine using the following code key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\somename1\\somename2") path= _winreg.QueryValueEx(key, "PATH")[0] I would like to do the same for a remote machine, i.e read the registry entries on a remote machine.
You have to connect to the remote computers registry and access it via that object. See the ConnectRegistry function on the doc page. e.g., rem_reg = ConnectRegistry("remotename", HKEY_LOCAL_MACHINE) rem_reg.OpenKey( ... ADDED As long you you have a valid UNC name, have permissions, and have not been blocked by a firewall along the way you should have able to do what you want to the remote registry
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, python 2.7, registry" }
Does amyone know what type of bonsai tree this is !enter image description here I got this tree about a week ago but i dont know what type it is help someone
I think it is a juniperus procumbens nana. It should be kept outside. It is quite cold hardy (being able to survive to nearly -30F/-35C), drought tolerant (which means to be careful not to over water), and needs full sun.
stackexchange-gardening
{ "answer_score": 3, "question_score": 2, "tags": "trees, bonsai" }
Validate .html with W3c if you set target attribute on <a>-element? If you set the target attribute on a element it won't validate at how doe one come around this and still have it validating?
The target attribute is still part of the HTML 4.01 standard (and works in all browsers), but it is no longer part of XHTML (which you are probably trying to validate for). There is currently no HTML-way to emulate its effect. There is the CSS3 Hyperlink Presentation Module draft however, that would bring back such a possibility via CSS. However it is currently not implemented by any browser.
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "website, validation" }
Векторизация, будет ли от неё толк в сетевом программировании? Речь идёт о структуре из пространства имён 'Numerics.Vector', которая по данным с MSDN - "подходит для низкоуровневых параллельных оптимизаций". В каких именно задачах стоит ее использовать? Я по большей части пишу сетевые приложения, где оперирую массивами байт ('byte[]'). Как известно - тип byte это unsigned char из 'C++', диапазон его значений от 0 до 255 и размер 8 бит. Есть ли смысл менять массив байт на вектор, будет ли прирост производительности в данном случае?
Векторизация может ускорить ваше приложение в его модельной части. Если у вас есть часть программы, занимающаяся вычислениями или другой массовой обработкой данных, то применение SIMD-операций может её существенно ускорить. (А может и не ускорить, это уж как повезёт с задачей.) А в обыкновенном сетевом коде прироста производительности скорее всего не будет, т. к. скорость обработки обычно на порядок, а то и несколько, меньше латентности сети. Вы не выиграете ничего. * * * В любом случае, профилируйте. Гарантированно правильный ответ по поводу того, где ваша программа тормозит, даёт только профилирование. Никто здесь на сайте, не зная архитектуру вашей программы, не сможет дать конкретного дельного совета. Мы можем озвучить только общий принцип.
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "c#, .net" }
How to solve equations containing multiple $|x|$s? Suppose I have an equation which looks like: $$|x-2| + |2x+1| = 3$$ or, $$|x-1| + |x-3| - |5x-1| = 2$$ > How should I solve such problems? What i do is generally a kind of "hit-and-trial" method but is there an even better method to do so? **_Thanks!_**
The way that always works (especially for inequalities of the same type, and also for nonlinear stuff in the $| \cdot |$ and for multiple variables) is doing case analysis, such that for each $| \cdot |$ you have 2 cases to look at. In your first example that would be: **Case 1** : $x-2>0$ and $2x+1>0$ **Case 2** : $x-2>0$ and $2x+1<0$ **Case 3** : $x-2<0$ and $2x+1>0$ **Case 4** : $x-2<0$ and $2x+1<0$ it is some work, but often a lot of cases are not important, because they are impossible, such as Case 2 here.
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "algebra precalculus, absolute value" }
Independent variables still independent with additional information? A simple question: Assume that two random variables $A$ and $B$ are independent, and so $E[AB]=E[A]E[B]$. If we take into account some additional information denoted by the information set $X$, does it follow that $E[AB | X]=E[A | X]E[B | X]$ regardless of what this information set $X$ is?
No, if $A$ and $B$ are dice rolls and $X$ implies information about the sum it will no longer be the case that they are independent. For example with two d2's we have $E[AB] = 9/4$ (and $E[A]=E[B] = 3/2$), but given the sum being $3$ we will have $E[AB|X] = (1\cdot2 + 2\cdot1)/2 = 2$ and $E[A|X] = E[B|X]= (1+2)/2 = 3/2$ so the equality doesn't hold.
stackexchange-math
{ "answer_score": 1, "question_score": -1, "tags": "probability" }
PHP installation issue on a Windows Server hosted in the Azure cloud I am trying to setup PHP and MySQL on a Windows Server that is currently in Azure cloud using the information from this blog post. Now I am testing the PHP installation using the methods specified in that tutorial. Here are the steps: 1. Open `C:\inetpub\wwwroot` and add an `index.php`. 2. Save the file then go to `xxxx.cloudapp.net/index.php` But when I do that I get: 404 file or directory not found error I can see the default page at `xxx.cloudapp.net` in the browser, but can’t see the PHP file in browser.
There are a few things to check: * Have you enabled PHP over FastCGI with a module mapping?: !enter image description here * Have you added a default document type? !enter image description here * Have you definitely made sure the php file is in the same directory as the default doc page? * have you recycled the app pools since adding the PHP instance? Possibly none of these, but these are common pitfalls I've seen when deploying multiple PHP/IIS instances before. It might be worth following the guide at: < for installing IIS properly on IIS Also, check that your file extensions are correct. Some texzt editors will save files as index.php.txt or as index.PHP (note that extensions ARE case sensitive)
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "php, mysql, windows server 2008 r2, azure" }
on enter controller call function angularJS The problem is that i need to call a function every single time that a route change to a specific state, lets say i have chatController and i have to fire a() every second but if i exit the controller i have to stop a() and when i'm back to chatController i have to restart a() My code: $scope.stop = $interval(yourOperation, 1000); var dereg = $rootScope.$on('$locationChangeSuccess', function() { $interval.cancel($scope.stop); dereg(); }); function yourOperation() { console.log('$location', $location.$$url) console.log('test'); } Works fine executing every single and stops when the controller change, but it doesn't work anymore if i go back, i tried with ng-init() function but only fires the first time that the controller start, i need it always when i'm on a specifict controller.
1] If it is state then you can use following event to call function every time when you back to state $scope.$on('$ionicView.enter',function(){ $scope.callingFunctionName(); }); Here you may need to add following attribute in app.js state declaration cache: false 2] In case you are using modal then controller will automatically get initialize. just need to call function like following - $scope.callingFunctionName();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, angularjs" }
Are smaller or larger pavers better for covering a concrete patio? I have a large ( 16' x 16' ) thick slab concrete patio that is pouted in 8 x 8 blocks. it has significant spalling and some settling. The concrete is 6" thick and situation in such a way that tearing out the concrete would not be ideal ( not to mention other than the spalling its not in bad shape ). I've considered trying to re-surface or re-pour a layer of concrete over the existing slabs, but now I'm considering just trying to lay concrete pavers over it. I'm wondering ( other than aesthetics ) if there are advantages and disadvantages to using smaller or larger pavers in this application. Ive considered these two options thus far < < and looking for some feedback.
If there isn't a lot of seasonal movement, it won't matter. I'd layer a small amount of sand as a pad and leveler (plus landscape fabric to control weed growth if you like) and go with whatever looks nice to you. If things do move a fair bit, smaller pavers will handle it better and be less likely to break over time.
stackexchange-diy
{ "answer_score": 1, "question_score": 1, "tags": "concrete, patio, pavers" }
Delphi hiding a form: Is there a difference between Form.Hide and Form.Visible:=False? I'm looking through two copies of code and in one I have myForm.Hide and another I have myForm.Visible := False. I can't remember why I changed this, if one was a bug fix or whether there is any difference at all.
There is no difference for `Hide`. The VCL code is: procedure TCustomForm.Hide; begin Visible := False; end; But `Show` is a bit different: procedure TCustomForm.Show; begin Visible := True; BringToFront; end;
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 5, "tags": "delphi, forms, hide, visible" }
Selenium - How to add integer variable in xpath using python Im new with selenium/python and that my problem: I have a simple site with a couple of news. I try to write script that iterates over all news, open each one, do something and goes back to all other news All news have same xpath, difference only with last symbol - i try to put this symbol as variable and loop over all news, with increment my variable after every visited news: x = len(driver.find_elements_by_class_name('cards-news-event')) print (x) for i in range(x): driver.find_element_by_xpath('/html/body/div[1]/div[1]/div/div/div/div[2]/div/div[3]/div/div[1]/div/**a["'+i+'"]**').click() do something i = i+1 Python return error: "Except type "str", got "int" instead. Google it couple of hours but really can't deal with it Very appreciate for any help
You are trying to add a string and a int which is is why the exception. Use str(i) instead of i xpath_string = '/html/body/div[1]/div[1]/div/div/div/div[2]/div/div[3]/div/div[1]/div/**a[{0}]**'.format(str(i)) driver.find_element_by_xpath(xpath_string).click() In the above the {0} is replaced with str(i). You can use .format to substitute multiple variables in a string by providing them as positional values, it is more elegant and easy to use that using + to concatenate strings. refer: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, selenium, xpath" }
How do I limit the date and time which the value provides I'm working on a serverinfo embed for my bot and I wanted to use `ctx.guild.created_at` for the guild's age, but it outputs `2020-11-21 21:38:57.527000`. I would like to get rid of the time and only keep the date.
There are many ways, 1. use strftime 2. manually split it # Split time = str(ctx.guild.created_at).split()[0] >>> 2020-11-21 # strftime time = ctx.guild.created_at.strftime("%Y-%m-%d") >>> 2020-11-21
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "python, discord, discord.py" }
Convert jquery selectors to array I need to be able to store the current selectors in the current viewport and then 10 seconds check if they are still in the users current viewport. My solution for this was to store the selectors in an array and then in 10 seconds compare the old selectors against the new and see if any match. If they do... do something. So i believe using .each and build the array, unless somebody has a more elegant solution to this? $('.gridContainers:in-viewport') This will return a standard selectors.
Calling $(selector) returns an array-like jQuery object, not an actual JavaScript array, though for the purposes of what they're trying to do converting it to an actual array may be unnecessary. This is how one would turn a selector into an native Javascript array. $(selector).toArray() Jquery.toArray()
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 5, "tags": "javascript, jquery, arrays, selector" }
Show that $(P\land\lnot Q)\lor(\lnot P \land Q)$ is equivalent to $(\lnot(P \land Q))\land(P \lor Q)$ without using truth tables I'm trying to show that $$(P\wedge \lnot Q)\vee(\lnot P\wedge Q) \equiv (\lnot(P \wedge Q)) \wedge (P\vee Q)$$ without using truth tables. I've been trying to expand either side through distribution and De Morgan's but I'm getting stuck with how to actually show that these are equivalent? Any tips would be great.
You're on the right path with de Morgan and distributivity. If you use de Morgan on the RHS you get $$(\neg P\vee\neg Q)\wedge(P\vee Q)=*$$ by distribution $$*\equiv ((\neg P\vee \neg Q)\wedge P)\vee ((\neg P\vee \neg Q)\wedge Q)=*$$ again, using distribution $$*\equiv (\neg P\wedge P)\vee(\neg Q\wedge P)\vee (\neg P\wedge Q)\vee (\neg Q\wedge Q)=*$$ finally $\neg P\wedge P\equiv\neg Q\wedge Q\equiv 0$, so you can remove them (since $0$ is the unit of $\vee$), so finally $$*\equiv (\neg P\wedge Q)\vee(\neg Q\wedge P)$$
stackexchange-math
{ "answer_score": 2, "question_score": -1, "tags": "propositional calculus" }
What did the Hulk see during his nightmare vision? As the Avengers make their first move on Ultron, he uses Scarlet Witch to give the entire team (except Hawkeye) visions of their worst nightmares. Thor saw that he destroyed Asgard, Tony killed the Avengers, Natasha went back to the red room and Captain America was alone after the war. What did the Hulk see during his nightmare vision?
Banner's worst nightmare is killing innocent people, he has a major fear of losing control while in a populated area. This point is made multiple times during the movie ("don't turn green") and reiterated at the end of the movie: > **Romanoff** : So what's our play? > **Banner** : I'm here to get you to safety > **Romanoff** : What about the drop-zone evacuation? > **Banner** : We can help with the evacuation but I can't be in a fight near civilians and you've done plenty... The Hulk _lived_ his nightmare vision. Banner turned into the Hulk and ran into a heavily populated city full of civilians and it took Stark in the Hulkbuster armor to stop him.
stackexchange-movies
{ "answer_score": 16, "question_score": 14, "tags": "marvel cinematic universe, avengers age of ultron" }
How do you disable Siri permanently on macOS Sierra (10.12.6)? I work in security as an intern, and I've been asked by my boss to look into disabling Siri on macOS Sierra. I noticed that there's no way to prevent users from re-enabling Siri even if it's disabled by an administrator. I've tried using "csrutil disable" in Recovery Mode and editing Siri's .plist files, but it seems to have no effect. Is there any way to completely prevent any user from running Siri on macOS Sierra?
It turns out an entirely different solution to what I expected is what actually works. It doesn't require you to change any settings at all. Simply reboot into Recovery Mode, open a terminal, and type: csrutil disable to disable System Integrity Protection. Reboot as normal, and then run sudo rm -rf /System/Library/CoreServices/Siri.app to disable Siri. Try to run it and you'll see it won't work. But we're not done yet. **MAKE SURE to re-enable System Integrity Protection by rebooting one more time into Recovery Mode and running:** csrutil enable **and then rebooting.** Congratulations! You've just disabled Siri! In the case that this doesn't work, implement both this and the .plist modifications I mention in my earlier answer.
stackexchange-apple
{ "answer_score": 1, "question_score": 7, "tags": "macos, siri, administrator, enterprise" }
sidekiqctl shutdown not working I'm trying to shutdown a sidekiq worker with `sidekiqctl` bundle exec sidekiqctl stop /mnt/www/project/shared/pids/sidekiq.pid 20 Then I see the message: Sidekiq shut down forcefully. BEFORE running the command, the sidekiq.pid file exists and matches the PID that I can see sidekiq running as. AFTER running this command, the same sidekiq PID is still running (it didn't shut down). But now the pid file is gone, presumably because sidekiqctl deleted it.
Turns out this was a chef/god issue... `sidekiqctl` is working just fine.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sidekiq" }
シェルコマンドで行数と列数の変形 test.csv $cat test.csv a b c d 2 a b c d
`awk``if(NR % 2)` $ awk '{ if(NR % 2) { printf "%s ", $1 } else { printf "%s\n", $1 } }' test.csv
stackexchange-ja_stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "shellscript, shell" }
How to show browser's default theme background in html? Is it possible to make the background of a HTML body the same as a browser's current default background? i.e., if I set my Chrome with a space theme, can I have the same space image as the background for my web site? The goal is to allow users see their own theme merged with the web page.
There is no way to achieve this. Webpages are rendered in an opaque viewport.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -4, "tags": "html, css" }
How to interpret numpy.gradient? In the first example of the documentation < x = np.array([1, 2, 4, 7, 11, 16], dtype=np.float) np.gradient(x) array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ]) Isn't the output should be: array([ 1. , 1., 2., 3., 4., 5. ]) ???
What you expect as output is what you will get when running `np.diff`, but then one element shorter: np.diff(arr) >>> array([ 1., 2., 3., 4., 5.]) `np.gradient` looks takes the i'th element and looks at the average between the differences for the `(i+1)`'th vs. `i`'th element and the `(i-1)`'th vs. `i`'th element. For the edge values it only can use one point. So value number two comes `1.5` comes from averaging `(2-1)` and `(4-2)`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "numpy" }
simplified htaccess i have a .htaccess file RewriteEngine On RewriteCond %{HTTP_HOST} ^localhost/host RewriteRule (.*) [R=301,L] RewriteEngine On RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?seg1=$1 RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?seg1=$1 RewriteEngine On RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ index.php?seg1=$1&seg2=$2 RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/$ index.php?seg1=$1&seg2=$2 RewriteEngine On RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ index.php?seg1=$1&seg2=$2&seg3=$3 RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/$ index.php?seg1=$1&seg2=$2&seg3=$3 my questions, is there a simplified .htaccess for those code? thanks!
If your PHP can process empty parameters correctly then why not RewriteRule ^([-\w]+)?/?([-\w]+)?/?([-\w]+)?/?$ index.php?seg1=$1&seg2=$2&seg3=$3 instead of the six rules? So /a will generate index.php?seg1=a&seg2=&seg3=
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": ".htaccess" }
Laravel 5: best way to modify column name in model What is the best way to modify column name before retrieve data from the model, ex: change `id` to be `uid` $data = user::all(); //return array('uid'=>1,'uid'=>2 ... etc) thanks,
The easiest option would be to create a custom attribute getter. This will allow you to access the `uid` value, like you would any other attribute, and the value will also be accessible via the `toArray()` method. class User extends Model { // ... public $appends = [ 'uid', ]; public function getUidAttribute() { return $this->attributes['id']; } // ... } $user->uid; // 1 $user->toArray() // [..., 'uid' => 1, ...];
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 1, "tags": "php, laravel, laravel 5" }
IE doesn't open from PowerShell script as a scheduled task I want for each 5 minutes to call PowerShell script. The script: $ie = New-Object -com InternetExplorer.Application $ie.navigate(" however, script is executed, I can see blue console of PowerShell program, but it wont open IE to present me a website. Settings in Action: ![enter image description here]( How to force script to open InternetExplorer, or Chrome?
Your script should look like this (one line responsible for showing IE was missing): $ie = New-Object -com InternetExplorer.Application $ie.navigate(" $ie.Visible=$true Then it should work (tested on my Win7). Keep in mind, it's still a good practice to be more explicit while defining your task. For example, in current format it'd fail in case you have spaces in your script name.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "powershell" }
Can't create Remote App via Powershell that points to an Excel workbook I am using Windows Server 2008 R2. I'm trying to use Powershell to create a new Remote App that points to an Excel workbook. The following script fails on the New-Item call: PS C:> Import-Module RemoteDesktopServices PS C:> cd RDS: PS RDS:\RemoteApp> New-Item -Path RDS:\RemoteApp\RemoteAppPrograms -Name "ATM999" -Appli 9\ATM999_Cube.xlsx" New-Item : An unknown error has occurred. At line:1 char:9 \+ New-Item <<<< -Path RDS:\RemoteApp\RemoteAppPrograms -Name "ATM999" -ApplicationPath ube.xlsx" \+ CategoryInfo : NotSpecified: (RDS:\RemoteApp\RemoteAppPrograms\ATM999:Stri \+ FullyQualifiedErrorId : UnknownError,Microsoft.PowerShell.Commands.NewItemCommand As a test, I attempted to create a new item that points to an executable rather than an Excel workbook. That works. Is there a parameter or something that I'm missing that would let me create a Remote App against an Excel workbook?
Figured it out. Here's what I did: Import-Module RemoteDesktopServices cd RDS: New-Item –Path RDS:\RemoteApp\RemoteAppPrograms –Name Workbook.xlsx –ApplicationPath "C:\Program Files\Microsoft Office\Office14\Excel.exe" –CommandLineSetting 2 -RequiredCommandLine "E:\ProcessingFolder\ClientName_Cube.xlsx" This creates an entry that points to Excel but specifies the path to the workbook in the RequiredCommandLine parameter. The "2" setting for CommandLineSetting forces the Remote App to always use the supplied RequiredCommandLine parameter.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "powershell, remote desktop, rdp, remoteapp" }
get the each value in between when only have the limit values I have a table that has a `week_start` and week_end column, both INTs. They are between 1-52 for the weeks of the year. Is it possible to list all the weeks in between `week_end` and `week_start`?
This should work if you have a `week` field (not a `week_start` and `week_end` fields) in the database. SELECT * FROM table WHERE week BETWEEN week_start AND week_end
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql, sql, database" }
Changing custom UIImage in didSelectRowAtIndexPath I have a custom `UIImage` within my cell that I need to change when `didSelectRowAtIndexPath` is called. For some reason the image isn't changing, and I think it's because of my cell declaration inside the method. class CustomCell: UITableViewCell { @IBOutlet weak var indicator: UIImageView! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell cell.indicator.image = UIImage(named: "newImage") } How can I change my `UIImage` to "newImage" when the cell is clicked?
Create cell from index path func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var cell = tableView.cellForRowAtIndexPath(indexPath) as! CustomCell cell.indicator.image = UIImage(named: "newImage") }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "ios, swift, uitableview" }
Accessing private instance variables of parent from child class? Let's say we have a class `foo` which has a private instance variable `bar`. Now let us have another class, `baz`, which `extends foo`. Can non-static methods in `baz` access `foo`'s variable `bar` if there is no accessor method defined in `foo`? I'm working in Java, by the way.
No, not according to the java language specification, 3rd edition: > **6.6.8 Example: private Fields, Methods, and Constructors** > > A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses. But regardless of this language restriction, you _can_ access private fields through reflection: Field privateStringField = MyClass.class.getDeclaredField("privateString"); privateStringField.setAccessible(true); String fieldValue = (String) privateStringField.get(privateObject); System.out.println("fieldValue = " + fieldValue);
stackexchange-stackoverflow
{ "answer_score": 36, "question_score": 31, "tags": "java, oop, class, inheritance, polymorphism" }
PHP </br> where lower-case letters meets uppercase-letter I am trying to put before every character which meets with a uppercase-letter. What I achieved is: $str = "Rating: goodHelps control sebum production Rating: averagePrevents the development of microorganisms in cosmetics Rating: badCan be allergenic Rating: badToxic to cell division"; $string = preg_replace('/([a-z])([A-Z])/', "</br>", $str); print_R($string); Result: > Rating: goo > > elps control sebum production Rating: averag > > revents the development of microorganisms in cosmetics Rating: ba > > an be allergenic Rating: ba > > oxic to cell division It removes the first and after character as you can see. I need the full text with a .
You want to use back-references to what you captured in the replace. The first capture group `()` is `$1` and the second is `$2`: $string = preg_replace('/([a-z])([A-Z])/', '$1</br>$2', $str);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, preg replace, preg match, preg split" }
cannot edit permission for a folder I am using Windows Server 2008 x64. I login using administrator. I want to add a new user for read/write access for a folder under c:\windows\system32. I tried to select folder (right click), then select Property -> Security -> Edit under Security Tab, the Add button is greyed out. Why? I tried the same operation under other non-windows system folder, it is ok to add new user to permission. thanks in advance, George
Changing permissions of a system folder is not a very good idea. Maybe you are not the owner of the folder, you can try to take ownership of the folder, but this could lead to system malfunctions.
stackexchange-serverfault
{ "answer_score": 3, "question_score": 0, "tags": "windows server 2008, permissions" }
What's wrong with my masking in this ImageMeasurements? I want to find the mean color of an image's region defined by a polygon, and I tried this: lena = Import["lena.tif"] poly = Polygon[{{10, 10}, {120, 10}, {100, 100}}]; imgDim = ImageDimensions[lena]; imgBounds = Transpose[{{0, 0}, imgDim}]; mask = Image[Graphics[{White, poly}, Background -> Black, ImageSize -> imgDim, PlotRange -> imgBounds]] ImageMeasurements[lena, Masking -> mask, "Mean"] But when I run this I get an error ImageMeasurements: Masking -> [the mask image] is not a known image measurements property. ImageMeasurements takes the Masking option, so I expected there was something wrong with my masking image. But changing to `Masking -> All` still gives the same error. Is the documentation wrong? (I'm on version 11.2)
The following works well: poly = Polygon[{{10, 10}, {120, 10}, {100, 100}}]; ImageMeasurements[lena, "Mean", Masking -> poly] `Masking` requires the graphical primitive instead your image. The sequence of arguments in `ImageMeasurements` have to be [image, measured value, options]. It does not work otherwise.
stackexchange-mathematica
{ "answer_score": 4, "question_score": 1, "tags": "image processing" }
Messaging from ViewModel to View is not handling I looked through lots of articles about it, but somehow, it is still not working. In the View, in constructor, i have Messenger.Default.Register(this, Constants.MY_MESSAGE, delegate(string s) { DoStuff(); } ); In the ViewModel, i have Messenger.Default.Send(Constants.MY_MESSAGE); Thats it, i just need to send a notification to the View, no additional data. But somehow, DoStuff(); never rises. Debugger just moves further to the next line after Send(); Maybe i should force it to deliver exactly to my View? Is there any shortcuts/list with tips about mvvm light messaging?
Crap. I spent several hours, trying to figure out answer. Correct sending is Messenger.Default.Send(String.Empty, Constants.MY_MESSAGE);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, windows phone 7, mvvm light, messaging" }
How can I take integer regex? I'm trying to use regex in Python for taking some parts of a text. From a text I need to take this kind of substring '2016-049172'. So what's the equivalent regex? Thank you very much. Here's a piece of code: import re pattern = re.compile(r"\s-\s[0-9]+[0-9]$]") my_string = 'Ticketing TSX - 2016-049172' matches = re.findall(pattern,my_string) print matches Of course, my output is empty list. (I apologize for initial bad post, I'm new)
As others have posted, the regular expression you are looking for is: \d{4}-\d{6} The full code I would use: import re my_string = 'Ticketing TSX - 2016-049172' matches = re.findall(r"\d{4}-\d{6}", my_string) print matches If, for example, the length of the second digit varies from 6 to 8 digits, you will need to update your regular expression to this. \d{4}-\d{6,8} All of the details about regex and using regex in Python is available in the docs
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -6, "tags": "python, regex, integer" }
Debug .pyz executable When I run my `main.py` file from console like `python main.py` everything works just fine. However when I package the app with zippapp it opens up window and apparently shows some error which I am unable to read because it immediately closes. How to debug/resolve this? Is it possible to somehow stop that so I can see the error? I have folder in which is _data_ folder and _app_ folder, in the app folder there is _main.py_ and there is _my_function()_ which is being run. The zipapp command: `python -m zipapp Entire_package -m app.main:my_function`
Lulz. One just have to run the `.pyz` file from terminal/command line with python like this: `python my_executable_pyz_file.pyz` and then you get the error printed straight into the terminal/cmd window and you can read it.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, package, pyz" }
Reference an imported module with string variable I have the following code snippet. import {English as en} from 'languages/en.js' import {Spanish as es} from 'languages/es.js' console.log(this.lang) // es I'm trying to call the corresponding imported module using the `this.lang` string. But not sure how I can call that module. window[this.lang] wouldn't work. Any suggestions?
Create an object and look up `lang` in that: const result = { es, en }[this.lang]; Working with the global scope (aka `window`) can get you into real trouble, thats why it is considered an antipattern (and all those ES 6 features, `let`, `const`, `import` enforce that by making "global variables" not leak to the global scope, therefore you can't access them on `window`).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript" }
call a method of a static instance in EJB I have a guess that there is an incorrect code in our codebase but I am not sure. So we have got en EJB like this: @Stateless public class MyEjb { private static Something sg = new Something(); public void doSomething() { sg.execute(); } } The class Something is a normal class: public class Something { public void execute() { ... } } As the MyEJB is stateless EJB so the method doSomething can be called more times simultaneously. Here comes my questions: if the doSomething() has been called twice at the same time then one of the calls will be blocked until the first call finishes? My guess is that it is blocked as there is just one static instance. If I am right the code above is not good as the method 'execute' of class 'Something' is a bottleneck for my EJB. Thanks, V.
Both calls will run simultaneously, unless you restrict the access using a "synchronized" block or a "Write Lock".
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, static, ejb, instance variables, simultaneous calls" }
Expand list of values into cases Here is what I have: sealed abstract class Codes(list: List[String]) object UVWCodes extends Codes(List("U", "V", "W")) object XYZCodes extends Codes(List("X", "Y", "Z")) I would like to use macros to expand the listed values into: parse(str: String): Codes = str match { case "U" | "V" | "W" => UVWCodes case "X" | "Y" | "Z" => XYZCodes } Since Codes is a sealed class, it's possible to get the list of its subclasses. However, how to extract the list of code literals ("U", "V", etc)?
When you write sealed abstract class Codes(list: List[String]) list is just a _constructor argument_ which is _lost_ if not used. If you prefix with the keyword _val_ it becomes an immutable property so you can access outside sealed abstract class Codes(val list: List[String]) UVWCodes.list // Valid code
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "scala, scala macros" }
Given $a_{1}=1, \ a_{n+1}=a_{n}+\frac{1}{a_{n}}$, find $\lim \limits_{n\to\infty}\frac{a_{n}}{n}$ I started by showing that $1\leq a_{n} \leq n$ (by induction) and then $\frac{1}{n}\leq \frac{a_{n}}{n} \leq 1$ which doesn't really get me anywhere. On a different path I showed that $a_{n} \to \infty$ but can't see how that helps me.
Use $a_{n+1} = \frac{1}{a_n} + \frac{1}{a_{n-1}} + \cdots + 1$ and $a_n \longrightarrow \infty$.
stackexchange-math
{ "answer_score": 20, "question_score": 10, "tags": "calculus, sequences and series" }
Нужна ли запятая после ПОТОМУ? Мифы продолжают жить в ряде работ не только потому, что их авторы недостаточно знакомы с историей вопроса, но иногда и потому(,) что они оказываются неспособны взглянуть на исследуемую проблему под иным углом, становясь пленниками определенных методологических установок. Нужна ли запятая в скобках?
Здесь сложный союз **потому что** попадает под условия расчленения (см. ниже цитату из Розенталя), поэтому нужна запятая перед **что**. > К условиям расчленения сложного союза относятся: > ... > 4) включение первой части (соотносительного слова) в ряд однородных членов предложения или параллельных конструкций: _Хозяйственная часть в доме Пшеницыной процветала не потому только, что Агафья Матвеевна была образцовая хозяйка, но и потому ещё, что Иван Матвеевич Мухояров был в гастрономическом отношении великий эпикуреец (Гонч.)_ ;
stackexchange-rus
{ "answer_score": 2, "question_score": 2, "tags": "пунктуация, запятые" }
Can we tell which way AC power is going through a cable without cutting the cable? Assume we have a very long cable whose ends are not visible or accessible. One end we know is a generator, and the other a load. Can we determine which end of the cable has the generator attached without cutting the cable?
A cable consists of two conductors, with a finite space between them. Let's assume they're insulated. Use capacitive sensing to determine the polarity of the instaneous voltage between them as a function of time. Use a Hall sensor to determine the polarity of the magnetic field in the space between them as a function of time. Once you've get the left-hand/right-hand rule polarities right, the vector product will indicate the direction of power flow. As you only wanted direction, polarities are sufficient. However, if you can get the indications to be more accurate, like a measurement, then you can estimate the magnitude of the power flow. As Marcus points out in comments, this is just an application of the Poynting Vector, which is true for electromagnetic waves in all of space, and for DC as well, but here is nicely simplified by there being a waveguide (power guide?) present in the form of your conductors.
stackexchange-electronics
{ "answer_score": 26, "question_score": 17, "tags": "ac, generator" }
How to get a SQL Server stored procedure return value using pyodbc? My team's using a python-based wiki server that calls stored procedures on a SQL Server database. Ideally, we'd like to return integer values (1,0,-1) from the stored procedure to show basic results. According to a 2008 thread on Google Groups, return values aren't supported by pyodbc, so the alternative is to SELECT the result as a row and check it instead. Is that still the case? Is there a (supported and documented) programmatic way to check the return value from SQL stored procedures? (If so, please add a current reference or example.)
Here's some relevant information: < It sounds like return values are still not supported, so you'll need to use a `SELECT`.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 8, "tags": "python, sql, pyodbc" }
Что необходимо учитывать при использовании бесплатного контента? Предположим, я использую бесплатную фотографию или шрифт. Как избежать правонарушения в случае, когда у меня есть лицензия на контент и когда её нет? Также, если не ошибаюсь, сбор пожертвований не является коммерцией? Или это уже «commercial use»?
Надо смотреть под какой лицензией распространяется контент и использовать его в соответствии с установленными лицензией правилами. Что касается шрифтов, то есть множество отличных вариантов под свободной лицензией (< По поводу изображений - надо смотреть каждый конкретный случай. При использовании фотографии из поиска с неопределенной лицензией/автором всегда есть риск нарваться на нарушение авторских прав.
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "лицензирование" }
Why is my CSS Media Query being ignored or overridden? (tumblr) This is my CSS: @media screen and (max-width: 640px){ .double{width:260px;} .double img{width:100%;height:auto;} .title {font-size:50px;} } No matter how much I edit the `@media screen and (max-width: 640px)` property, nothing works. I have tried adding `!important` as well, but it doesn't work. It seems like my `@media` property is being ignored/overridden because when I resize the browser and inspect the element (on FireFox), the CSS used is still `.double img{width:560px;}` when it should be `.double img {width:100%;height:auto;}` Any help would be really appreciated! :) Here's my Tumblr. And if it helps, my JSFiddle is here.
It's simply caused by a syntax error in the `.capz` class, juste before your media query : .capz { opacity:0; filter:alpha(opacity = 0); -webkit-transition: all 0.3s ease; -moz-transition: all 0.3s ease-in-out; -o-transition: all 0.3s ease-in-out; -ms-transition: all 0.3s ease-in-out; transition: all 0.3s ease-in-out; position: absolute; background: rgba(255,255,255; //missing closing parenthesis width: 100%; height: 100%; bottom:3px; } @media screen and (max-width: 640px){ .double{width:260px;!important} .double img{width:100%!important;height:auto !important;} img {max-width: 100% !important;height: auto !important;} } (Note : you don't need `!important` tag anymore in this case) Updated fiddle
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "image, responsive design, media queries" }
jquery drag, drop and clone, find dropped position of element Here, is my fiddle for jquery drag, drop and clone feature. **Problem:** My problem is: when ever I drop element, it is showing: position: {top: 0, left: 0} only for draggable, clone and droppable element. I have also written code for finding position using only `draggable` function and that is working fine. I want this behavior in `draggable, droppable with clone feature` **Please visit JSFiddle** fiddle full-screen output
Finally, resolved the problem. The problem was, I was using `ui.draggable.position();` for storing dropped position to database, which was wrong. The actual position we need to store is: // position of the draggable minus position of the droppable // relative to the document leftPosition = ui.offset.left - $(this).offset().left; topPosition = ui.offset.top - $(this).offset().top; Reference: How do I get the coordinate position after using jQuery drag and drop? Updated Jsfiddle with working example < <
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "jquery, jquery ui, jquery ui draggable, jquery ui droppable" }
prove a vector equation We have to prove the following equation ![enter image description here]( I tried as Taking square root both side and making denominator same in LHS . After I got stuck .
Hint - On solving left hand side $\left( \frac1{|\vec{a}|^2} + \frac1{|\vec{b}|^2} - 2 \frac{\vec{a}.\vec{b}}{|\vec{a}|^2.|\vec{b}|^2}\right)$ = $\left( \frac{|\vec{a}|^2 + |\vec{b}|^2 - 2 \vec{a}.\vec{b}}{|\vec{a}|^2.|\vec{b}|^2} \right)$ = $\left( \frac{\vec{a} - \vec{b}}{|\vec{a}|.|\vec{b}|} \right)^2$ As $\vec a^2 = |\vec a|^2$
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "vectors" }
Post message referencing users As a facebook app I want to post a message that references a set of users (e.g. @John Doe, @Tom Cruise) so that the message will show up on their wall (and their friends can see). How can I do this programmatically? Through what API calls?
As stated by aFacebook employee, tagging users in statuses is not available through the API.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "facebook, api, facebook graph api" }
Iam getting iTunes store operation failed error when validating the app !enter image description here I am getting this error when validating app with itunes connect please help me to fix this Thanks
I found the solution this error happend because i was using old version of google plus sdk i updated the sdk now its fixed
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ios, xcode, app store connect" }
Node.js - asynchronous method call issue I am building an app using node.js and wanted to confirm an issue regarding modules and node's asynchronous nature. If I have a module such as: var email_list = function() { //perform some database query or calculation } exports.email_to = function() { email_list.forEach(function(email) { console.log(email); }); }; And in another file, I call my `email_to` method, does the function`email_list` get called before my `email_to` function gets called? If not, is there a way to guarantee that the `email_to` function gets called after the `email_list` function? Thanks in advance~
I commented, but I'll elaborate a little bit. Your going to want to do something like this: var email_list = function() { return knex('email_list').where({ verified: true }); }; exports.email_to = function() { var response = email_list() .then(function(emailList){ emailList.forEach(function(email){ console.log(email); }); }); }; There is a lot of documentation out there about the event lifecycle of Node and Javascript in general. On a really high level, you are going to want to study how promises and callbacks work. That is how you "guarantee" things get called when you would expect them to. In this case, _email_list_ returns a promise. You can use the result of that promise in your _email_to_ function. You wait for the result of that promise by using _then_
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, node.js, asynchronous, methods" }
Angular frequency - Cannot explain solution Hello I'm learning some electrical engineering today but cannot come to the solution. $w = 2π*f$ How is: $2π*295.4 kHz = 1.86 * 106 s^{-1}$ cannot figure out what $1.86 * 106 s^{-1}$ should be
Use: 1. $$\text{f}_{\left[\text{Hz}\right]}=\frac{1}{\text{t}_{\left[\text{s}\right]}}$$ 2. $$\omega_{\left[\text{rad/s}\right]}=2\pi\cdot\text{f}_{\left[\text{Hz}\right]}=2\pi\cdot\frac{1}{\text{t}_{\left[\text{s}\right]}}=\frac{2\pi}{\text{t}_{\left[\text{s}\right]}}$$ So, when $\text{f}_{\left[\text{Hz}\right]}=295.4\cdot1000=295400\space\text{Hz}$, we get: * $$\omega_{\left[\text{rad/s}\right]}=2\pi\cdot295400=590800\pi\approx1856052.94\space\text{rad/s}$$
stackexchange-math
{ "answer_score": 0, "question_score": -2, "tags": "physics" }
Prove a quotient group is abelian Let $G$ be a group with a normal subgroup $M$ such that $G/M$ is abelian. Let $N\geq M$ and $N \unlhd G$. Show $G/N$ is abelian. **My attempt** : To show that $G/N$ is abelian, we need to show that for all $x,y \in N,~ xNyN=yNxN$ $G/M$ is abelian, so for any $x,y \in M, xMyM=yMxM$. Since $M$ is a subgroup of $N$, the cosets $xM$ and $yM$ are in $B$. Then, I am stuck, but I feel like I should construct some sort of algebraic manipulation to show $G/N$ is abelian. Thanks in advance
By correspondence theorem $N/M$ is normal in $G/M$. By third isomorphism theorem $$G/N \cong \frac{G/M}{N/M} $$But $G/M$ is abelian, and a quotient of an abelian group is abelian, so $G/N$ is abelian.
stackexchange-math
{ "answer_score": 4, "question_score": 4, "tags": "abstract algebra, group theory, abelian groups, normal subgroups" }
Why the Common Lisp REPL keeps infinitely running after the insertion of this circular list? I am using Common Lisp, SBCL and Slime. I am new to Common Lisp. Apparently, this is a circular list in Common Lisp: #1=('a 'b 'c . #1#) This would provide an infinite 'a 'b 'c 'a 'b 'c 'a... When I put this on the REPL it keeps running forever: CL-USER> #1=('a 'b 'c . #1#) Why does that happen? Why the REPL does not return the "object" it received? I can understand an infinite behavior if I was asking for the next element of the list. However, I asked the REPL about the object itself. I was expecting the same behavior that happens with proper lists or dotted lists: CL-USER> (list 'a 'b 'c) (A B C) CL-USER> (cons 'a (cons 'b 'c)) (A B . C)
> I can understand an infinite behavior if I was asking for the next element of the list. Why? The next element is not an operation with infinite compute time. It's just getting the next element, which is only a simple operation. It's just the next element in a circular list. What's infinite is when one asks for the next element in a loop, checking for the end of the list. (cdr list) vs. (dolist (e list) ...) Probably the _printer_ (the part of the Read Eval Print Loop which prints the result) will do something similar when it wants to print the elements of an infinite list. TFB mentioned that one needs special checks to detect circularity to keep the computation bounded.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "common lisp, read eval print loop, infinite, circular list" }
How to make my normal account can execute `sudo`? I installed bare-bone FreeBSD, and added a new user. And added `sudo` package with command `pkg_add -r sudo`. When I logged into the box with new user account, it cannot run sudo command. What procedure is required to do this?.
Adjust your sudo configuration (sample.sudoers) using visudo. Perhaps you what something like this. username ALL=(ALL) ALL
stackexchange-serverfault
{ "answer_score": 3, "question_score": 0, "tags": "freebsd, sudo, accounts" }
What to do with an extra index in the definition of a tensor? I came across this definition of a tensor while reading some vector calculus literature ![Tensor]( This definition contains the index $\ell$ in the last term, however the tensor itself only depends on $j$ and $k$. What am I supposed to do with this extra index? Do I sum over it? Note: The term $\frac{\partial \phi_k}{\partial x_j}$ is irrelevant here; it is just another long expression in terms of the position vectors, although it also contains an $\ell$ within it.
Yes, generally these sorts of expressions follow the Einstein summation convention. This says that whenever you see an index repeated in a multiplication expression, it means to implicitly sum over that index. So $(x_a - X_a)$ is a vector subtraction, but $x_a X_a$ is an inner product. This is then made a little bit more rigorous either for skewed coordinate systems, or non-flat geometries like minkowski space. There you define a vector space with upper indices, and a covector space with lower indices. Covectors take a vector and produce a scalar, so whenever you see you the same the symbol for the upper and lower index, you know that they are applying a covector to a vector to create a scalar.
stackexchange-physics
{ "answer_score": 2, "question_score": 1, "tags": "metric tensor, tensor calculus, notation" }
Efficient implementation of a threaded console window I have a Win32 application that consists of two components: A main window that acts as the app's interface and a secondary modeless dialog that functions as a console. The application generates copious amounts of debug text during certain (regular) operations. Having to update the console's edit control during every debug print call is rather expensive given my constraints. My intention is to create a critical section synchronized message queue that is dumped periodically by a worker thread. I'd appreciate any suggestions on how such an implementation can be coded.
I tried using a timer in the main thread and it worked well enough for me. My thanks to the posters!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c++, multithreading, winapi, console, thread safety" }
Do onsen geisha still exist? Japan's most famous geisha are from Kyoto, Japan's former capital and still a major cultural capital of Japan. But I've also heard of onsen geisha, far away from the big cities, who are at the bottom of the pecking order of geisha. Do such geisha still exist nowadays? Wikipedia's article on geisha mention that the number of geisha overall have declined dramatically, and I suspect the lower-grade geisha might be more likely to disappear. Wikipedia has an article on onsen geisha, with a description of their status post World War 2, but it's rather brief and doesn't feel authoritative. I'm making the assumption that there's such a thing as "onsen geisha". Is this a valid assumption, or is "onsen geisha" just a pejorative title that no-one would use about themselves?
Onsen Geisha is not a specific Rank or similar within a national Geisha hierarchy. Onsen Geisha refer much more for the location where they can be found. You can see Onsen Geisha at several resort towns in Japan, for example Akita; Sample resorts that allow booking of shows or private entertainment: < <
stackexchange-history
{ "answer_score": 5, "question_score": 3, "tags": "cultural history, japan" }
Why are my buttons transparent when I run on my device? So I've colored my buttons in my App. When I'm running on a local server on my PC the colors work fine, but when I deploy to my Device(Android), all buttons are transparent. in my variables.scss it looks like this: ion-button{ --background: #a37001e8; --background-activated: #e9c067e8; color: white; }
ion-button{ --background: rgba(163, 112, 1, 1); --background-activated: rgba(233, 192, 103, 1) color: white; } There is not yet full browser support for alpha use of a hex color. Use the rgba() function only accepts a value in R, G, B, A (Red, Green, Blue, Alpha) format. <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, css, typescript, ionic framework, ionic4" }
Good Practice? Redefining Arrays to Change their Size I'm working in Unity in C#, but this is a more general programming practice question. dataType[] array = new dataType[x]; //Further down dataType[] newArray = new dataType[array.Length + 1]; for (int i=0;i<array.Length;i++){ newArray[i] = array[i]; } Is this considered bad practice? Is it more/less efficient than just using an ArrayList? I'm only performing this operation at the beginning of a level and then never again, so is it worth just working with ArrayLists?
Yes, this is bad practice. If you expect your array size to change then use a List instead of an Array. List works just like an array in terms of indexing. To add new items to the List use Add(). You can even call ToArray() on the list to get an Array from it. If you come across a situation where you can't use a List and need to grow your Array, use Array.Resize() as shown below. int[] array = new int[5]; Console.WriteLine(array.Length); Array.Resize<int>(ref array, 20); Console.WriteLine(array.Length);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, arrays" }
How to get all permutations of a variable-length word I need to find all permutations of a set of letters (word) with following parameters: * Word lengths $\ell = [1, 20]$ * Alphabet $A = \\{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t\\} \Rightarrow \lvert a\rvert=20$ Each letter can only appear once in a word. For each word length in $\ell$ all combinations of all letters must be found. The letter order in a word does not matter. This would be the same: $abcd = dacb$ This simplified problem formulation is needed for implementing a SVM (support vector machine) where the best combination of $20$ different classes must be teached / learned. I have a iterative programmatic solution in mind but this keeps confusing me. Is there anyone here who can master this? Regards
If I'm understanding you correctly, the problem is essentially equivalent to finding the number of distinct subsets of $\;A=\\{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t\\},\;$ minus the empty set (word length $\mathcal l=0$) : i.e., the number of words you can find under the given criteria is given by $$|P(A)| - 1 = 2^{|A|}-1 = 2^{20}-1 = 1048575$$
stackexchange-math
{ "answer_score": 1, "question_score": 2, "tags": "permutations, combinations, formal languages" }
Swift 3 NSCache Generic parameter 'KeyType' could not be inferred This code worked in Swift 2.x: /// An internal in-memory cache private var dataCache = NSCache.init() In **Swift 3** it causes compilation error: Generic parameter 'KeyType' could not be inferred Why is that so and how should I refactor this (Migration tool did not pick this up)?
* In the first Swift 3 betas `NSCache` has been changed to `Cache`. * In the latest betas (currently 5) it has been reverted to `NSCache`. Anyway `NSCache` is now a generic. public class NSCache<KeyType : AnyObject, ObjectType : AnyObject> : NSObject { ... so the most general syntax is private var dataCache = NSCache<AnyObject, AnyObject>() The explicit `init()` is not needed (not even in Swift 2)
stackexchange-stackoverflow
{ "answer_score": 41, "question_score": 18, "tags": "ios, swift, swift3" }
xcode: How to connect intruments Leaks tool with simulator? I want to detect if there are memory leaks in my application. But the problem is that when I click to red button it show a window to chose executable, but I do not know how to point instrument's leak utility to my iphone Simulator application. !enter image description here !enter image description here
In Xcode goto product > Profile, then select leaks.
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 5, "tags": "ios, xcode, memory management, instruments" }
Jquery On Scroll not working with new element created I'm using Jquery 1.9.1 . This code is for capture the scroll event when someone scroll the div in class "myclass". $('.myclass').on('scroll', function() { alert('test'); }); This work well with which element already have in page load. But when i using .append to create a new element : $("body").append("<div class='myclass'> some large text to show the scrollbar ....</div>'); This new element will not fire any scroll event. How to resolve this problem ? * * * Updated the JsFiddle : <
Well, actually the events `load`, `error` and `scroll` do not bubble up the DOM. So you need another approach. The best I can think of is to add the listeners again... Like this: function scrollfunc() { alert('test'); }; function listen_again() { var all = document.querySelectorAll(".myclass"); for (i = 0; i < all.length; i++) { all[i].onscroll = scrollfunc; } } function apdDiv() { $("body").append('<div class="myclass" >This is another div that using append<br>This is another div that using append</div>'); listen_again() } $(document).ready(function () { apdDiv(); listen_again() }); ## Demo **here**
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "jquery" }
Detect keyboard input with support of Unicode in python I want to detect keystrokes in python code. I already try a lot of methods with different libraries but all of them cant detect the UTF keyboard input and only detect Ascii. For example, I want to detect Unicode characters like ("د") or ("ۼ") if a user typed these keys. It means that if I press Alt+Shift it changes my input to another language that uses Unicode characters and I want to detect them. IMPORTANT: I need the Windows version. It must detect keystrokes even not focusing on the terminal. Suppose this simple example: from pynput import keyboard def on_press(key): try: print(key.char) except AttributeError: print(key) if __name__ == "__main__": with keyboard.Listener(on_press=on_press) as listener: listener.join()
Here is the code which returns the number of Unicode. It cannot detect the current language and always shows the old one but only in cmd window itself and if you focus on any other window it shows the current Unicode number perfectly. from pynput import keyboard def on_press(key): if key == keyboard.Key.esc: listener.stop() else: print(ord(getattr(key, 'char', '0'))) controller = keyboard.Controller() with keyboard.Listener( on_press=on_press) as listener: listener.join()
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "python, unicode, utf 8, keyboard events" }
Does indexedDB have anything to do with the DOM? I would guess no, it is a window property and has no dependecies on the DOM. Why then in this net plus tutorial is its detection tied to the DOM content loaded event? Is this just thoughtless boiler plate? <
IndexedDB has nothing to do with DOM. You don't need to wait anything. You can use in head as well. The only thing is it need `window` instance or origin for security and quota management. IndexedDB API, however, still use DOM convention such as event handling and error.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, indexeddb" }
python: the form of key in heaps.nsmallest when I study python cookbook, there raised a question really puzzle me: portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65} ] cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price']) here we can see the 's' is not defined, but how it can work? what should I do if I don't want to use lambda?
Well, actually, `s` **is** defined, just not in a way you are used to define things. Look closer to this expresion: key=lambda s: s['price'] As you can see, `s` is defined you after `lambda`, in the part `lambda s:`. An expression that won't work would be: key=lambda s: a['price'] as you can see, now `a` is not defined. You only have to understand that the function `heapq.nsmallest` takes three parameters, and the last one is a function (in this case a lambda function), and in this case, takes a dictionary and get a specific key.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, python 3.x" }
output message from Hive query When using Hive query, here is the output during the progress of execution, want to confirm it means the query use 27 mapper and 1 reducer? Or using 27 split with 1 mapper? Map 1: 21/27 Reducer 2: 0/1 Map 1: 22/27 Reducer 2: 0/1 Map 1: 23/27 Reducer 2: 0/1 Map 1: 24/27 Reducer 2: 0/1 Map 1: 26/27 Reducer 2: 0/1 Map 1: 27/27 Reducer 2: 0/1 Map 1: 27/27 Reducer 2: 1/1 thanks in advance, Lin
It is using 27 mappers and 1 reducers. The number of mappers and reducers are decided based on the data (number of splits). Check this for more details.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "hadoop, hive" }
Story where humans had the carbon in their cells replaced with silicon to make them stronger I've been trying to remember the name of a sci-fi story, maybe novella, I lost while I was reading. It involved a war where the cells of humans had the carbon replaced with silicon to make them stronger(?) I lost the book about 25 years ago before I finished reading the story.
Escape across the Cosmos by Gardner Fox, fits the question; Karl Carrick, a wounded survivor of an Interplanetary war, has his cells/organs replaced by silicon organs. He's exiled to a desolated planet for the framed murder of the genius who did the replacement Escape Across the Cosmos was plagiarized twice as; Titans of the Universe by James Harvey and Star Chase by Brian James Royal. There is a dedication in Star Chase to James Harvey! Royal and Harvey are presumed to be the same person. !enter image description here!enter image description here !enter image description here
stackexchange-scifi
{ "answer_score": 3, "question_score": 3, "tags": "story identification" }
Gridview should display dropdownlist "Text" which is selected instead of "Value" I have a Form where in I have two DropdownList "Status" & "Shelf" both have SQL Datasources and they are dependent. When ever I Insert a record, it enters perfectly but the "Status" & "Shelf" columns contain "Values" instead of "Text".
since you set parameters using `SelectedValue` property, you get the `DataValueField` bounded to droupdown list. if you need to get `DataTextField`, then try as below command.Parameters.AddWithValue("@status", DdlStatus.SelectedItem.Text); command.Parameters.AddWithValue("@shelf", DdlShelf.SelectedItem.Text);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#" }
Solving $ \begin{cases} e^{-x^2-y^2}-2xe^{-x^2-y^2}(x+y)=0\\ e^{-x^2-y^2}-2ye^{-x^2-y^2}(x+y)=0\\ \end{cases} $ for $x$ (and $y$)? I'm trying to solve the following system: $$ \begin{cases} e^{-x^2-y^2}-2xe^{-x^2-y^2}(x+y)=0\\\ e^{-x^2-y^2}-2ye^{-x^2-y^2}(x+y)=0\\\ \end{cases} $$ for both $x$ and $y$. The problem is that from the first I can get $y=\frac{1-2x^2}{2x}$ and plugging this back says that $x \in \mathbb{R} \setminus \\{0\\}$. Also, wouldn't plugging $x$ back into $y$ give yet that $y \in \mathbb{R} \setminus \\{0\\}$? I haven't tried the second one, but the first one seems to produce such confusing results that I'm not sure whether I'm attempting to solve the system in the correct way. The second equation seems to give $$y=\pm \frac{\sqrt{x^2+2}}{2}-\frac{x}{2}$$ How does this give me any way to find out any other solution than $x,y \not = 0$?
\begin{cases} e^{-x^2-y^2}-2xe^{-x^2-y^2}(x+y)=0\\\ e^{-x^2-y^2}-2ye^{-x^2-y^2}(x+y)=0\\\ \end{cases} Dividing both equations by the positive number $e^{-x^2-y^2}$ yields \begin{cases} 1-2x(x+y)=0\\\ 1-2y(x+y)=0\\\ \end{cases} which can be rewritten \begin{cases} 2x(x+y)=1\\\ 2y(x+y)=1\\\ \end{cases} Adding and subtracting them gives \begin{cases} (x+y)^2=1\\\ (x+y)(x-y)=0\\\ \end{cases} If $x+y=0$ the first cannot be satisfied, so we must have $x=y$, which when we plug into the first we get $$x=y=\pm \frac 12$$ Thank you to John Wayland Bales for the first part of this.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "exponential function, systems of equations" }
How to run sql script in geany? I am able to run my `ex1.sql` script from the command line, but in geany the follow error pops up: ./geany_run_script.sh: 5: ./geany_run_script.sh: ./ex1: not found Does anyone have an idea?
Geany cannot execute sql directly. You have to configure the Build Commands from inside the build menu to do this e.g. to `psql -f %f` to run sql script with psql client.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "sqlite, ubuntu 12.04, geany" }
visual studio 2013 project installer how to create custom actions I am trying to create a custom action in a setup project in visual studio 2013 using this extension < But I cannot add a custom action or an installer class to my project. The purpose of the custom action is to change file access rights after installing my application, how can I do this ?
In the simplest case you go to the editor window View=>Editor=>Custom actions, and to add an executable you right click (say) the Install node and add the exe, browsing to it. This might help too, still applies: < But you haven't said what you've tried exactly, or where you are trying to add the class. If you're trying to add an installer class to the setup project, that's the wrong place. If, for example, you are installing a service with an installer class, then it's a class you add to the service. Then in the setup project you have a custom action to call that class. In your case, have you added an installer class to your C# project (or whatever it is)?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, visual studio 2013, windows installer, setup project, custom action" }
At what level can a dragon innately cast its spells? In D&D 5e, when using the Variant: Dragons as Innate Spellcasters, a spellcasting young red dragon is going to know 4 spells of up to 3rd level and can cast each spell once a day. When the dragon casts, are the spells cast at 3rd level or at the lowest level for the spell? Eg, does the dragon cast _cure wounds_ at 3rd level, because it can? Could the dragon cast _invisibility_ on itself and its pet by casting it at 3rd level?
## Dragons cannot upcast innate spells The MM says this on innate spellcasting (p.10): > Unless noted otherwise, an innate spell of 1st level or higher is always cast at its lowest possible level and can't be cast at a higher level. This is not circumvented by the rules for dragons (p.86) > Each spell [..] the spell’s level can be no higher than one-third the dragon’s Challenge rating (rounded down) The latter is about what spells the dragon _knows_ , not about the spells they _cast_.
stackexchange-rpg
{ "answer_score": 40, "question_score": 19, "tags": "dnd 5e, spells, dragons" }
Google contacts sync to Lotus Notes? Is there any way to sync google contacts to lotus notes?
Try Awesync < to sync contacts, cal and tasks
stackexchange-superuser
{ "answer_score": 3, "question_score": 6, "tags": "lotus notes, google sync" }
JQuery DatePicker Highlight Date onSelect Hi I am trying to create a date range selector. below is the given code which I need to fill in. How do I highlight all the Selected date $(document).ready(function () { $("#fromCalendar").datepicker({ numberOfMonths: [1, 6], stepMonths: 1, autoSize: true, dateFormat: 'dd/mm/yy', onSelect: function (date) { selectDate(date); } }); }); function selectDate(date){ //Code }
$(document).ready(function () { numberOfMonths: [1, 6], stepMonths: 3, autoSize: true, changeMonth: true, changeYear: true, dateFormat: 'dd/mm/yy', onSelect: function (dateText, inst) { selectDate(dateText); }, beforeShowDay: function (date) { var gotDate = $.inArray($.datepicker.formatDate($(this).datepicker('option', 'dateFormat'), date), dates); if (gotDate >= 0) { return [false, "ui-state-highlight ui-state-active ui-state-hover"]; } return [true, ""]; } }); });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "jquery, datepicker" }
Session dissapears after refresh PHP I want do store multiple values each time page is loaded. But my session array is not working, it's acting like a simple array. session_start(); ...some code... $_SESSION['a'] = $input_value; print_r($_SESSION); //here I have only 1 variable
Your not creating an array, try the code below $_SESSION['a'][] = $input_value;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, html, web" }
Overload type method? Is there a way to make an **overload of a type method**? My goal in this particular situation is to make an overload of `string.Substring()` with parameters `start_index` and `end_index`.
No but you can use so called extension method of a `string`: public static class StringExtensions { public static string SubstringRegion(this string str, int startIndex, int endIndex) { return str.Substring(startIndex, endIndex - startIndex + 1); } }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, methods, overloading" }
Secondary monitor does not display native resolution I have a laptop (Acer Aspire 8730G) which runs a GeForce 9300M GS. Its native resolution is 1680x945 pixels. Now, I connected my monitor to it (LG E2250V-PN) with VGA (laptop only has a VGA or HDMI input but I do not own a HDMI cable) and set the lay-out to "extend". Everything works as it should, but: My LG monitor cannot receive its native resolutions. When going to the Screen Resolutions options of Windows I can choose between these values: !Windows Screen resolution options NVidia control panel shows me this (running latest drivers 310.70 on Windows 8): !NVIDIA control panel I know I can add a 'custom resolution' but I have no idea what to put into these fields ("Timing"): !Custom resolution Any tips?
Okay, I solved it! Go to your NVidia Control Panel and add a Custom Resolution. Fill in your resolution (1920 and 1080 in my case) and then under the heading "Timing" choose GTF (Generalized Timing Formula). For more information on advanced timings, see NVIDIA's website.
stackexchange-superuser
{ "answer_score": 1, "question_score": 3, "tags": "resolution, nvidia graphics card, external display" }
Promise.reject() continues with then() instead of catch() I am making myself a library which retries failed promise "chain-parts" - I collect methods to be called and queue next phase only after previous succeeded. Conceptually rounded up - my problems are more fundamental. This is where I arrived with debugging: this.runningPromise .then(function() { return Promise.reject(); }) //; //this.runningPromise .then(this.promiseResolver.bind(this)) .catch(this.promiseRejector.bind(this)) ; Works, `promiseRejector` kicks in. When I uncomment out the two lines, works not. `promiseResolver` gets called. Can't find anywhere anything. Nodejs 6.10.3 with browserify on Windows, Chrome.
If you uncomment two rows means you are calling `this.runningPromise` twice and each time it has its own callbacks. If you keep the rows commented then it will act as a promise (and associated callbacks) Better you should assign promise to a variable and then you can use it multiple times. let newPromise = this.runningPromise .then(function() { return Promise.reject(); }); newPromise .then(this.promiseResolver.bind(this)) .catch(this.promiseRejector.bind(this)); With above code you can use `newPromise` multiple times.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "node.js, promise, browserify, es6 promise" }
Mention general flagging in vote-to-migrate dialog I see that we've recently changed the list of provided migrations to better reflect the current most popular migration routes. This is good, but it would be really nice if the dialog were to _mention_ that general flagging-for-mod-attention should be used to propose a migration to another SE site. !Current vote-to-migrate dialog Yes, people using that dialog ought to be aware of that as a possibility anyway through reading Meta, but I'd bet they aren't.
Best thing to do would be to add a button (or replace the final button with one) that says something like: **It Belongs Somewhere Else:** with a text entry field. This could act as a standard mod attention flag, but preserves the existing workflow, rather than telling the user to back up and select a different flag type. Bonus points if it would still cast an off-topic close vote for users with appropriate reputation along the way.
stackexchange-meta
{ "answer_score": 6, "question_score": 5, "tags": "feature request, migration, close dialog" }
Dart analyzer is not parsing the dynamic generated files I checked and the file is OK. Dart 1.23.0 AngularDart 3.1.0 The error I am getting is: Target of URI hasn't been generated: 'file.g.dart' ![enter image description here](
It may help to run "Synchronize" -- bound by default to Ctrl-Q. You can restart the analyzer on the dart analysis tab, in the top left is a button with arrows running in a circle, if you hover over it it says 'Restart Dart Analysis Server'. Example picture
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 9, "tags": "dart, angular dart" }
Does Xcode 4 have any affect on the current version of MonoTouch? Is it safe to install Xcode 4?
Today's release of MonoTouch will let you install XCode 4 and continue building applications with MonoTouch. But if you use install XCode 4, you wont be able to edit your XIB files. We advise developers to install the new XCode 3 release that contains support for iOS 4.3 and still comes with Interface Builder. We are hard at work at building a new integration system from MonoDevelop to XCode4 (since they now merged Interface Builder with XCode)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "iphone, xamarin.ios" }
How would one go about referencing an audio file from a relative path? I am working on a hobby project in JavaFX and want to play some music. I currently reference the entire file path when I put in the song, which looks something like C Drive -> Games ->myGame -> Audio -> song.mp3. However, this would mess it up if I moved the file or another user would install it somewhere else. How do I create a relative path to the song file? Media song= new Media("file:///E:/games/gameName/audio/song.mp3"); player= new MediaPlayer(song); player.play();
if you want to load media relative to Application directory: Media song= new Media(new File("./audio/song.mp3").toURI().toString()); ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, javafx" }
How do I use Capybara to test that a form element is disabled when using jQuery's prop method? In my Rails 3 app, I've been using jQuery's attr() method to do things like this: $('#application_dust_type_id').attr('disabled', 'disabled'); I would use Test/Unit, capybara and capybara-webkit to test this with: assert page.has_selector? 'select[id=application_dust_type_id][disabled=disabled]' Now, I'm trying to switch to using the prop method, as jQuery recommends: $('#application_dust_type_id').prop('disabled', true) But now the above assertion fails, even though the javascript still works the same in the browser. How can I make an assertion based on an element's property (instead of an attribute) using capybara?
Try just checking for the existance of a `disabled` attribute as that is all that is really required to disable an input: assert page.has_selector? 'select[id=application_dust_type_id][disabled]' Note that the value of a `disabled` attribute is moot. You could set `disabled="false"` or `disabled="foobar"` and the element would be rendered as disabled.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 7, "tags": "jquery, ruby, ruby on rails 3, capybara, testunit" }
Accessing global constants using globalThis/window I just played around with global declerations using var, const, and without any, and noiticed that while var and without can be accessed using globalThis, const cant. aaa = "aaa"; var bbb = "bbb"; const ccc = "ccc"; console.log(globalThis.aaa, globalThis.bbb, globalThis.ccc); // logs: aaa bbb undefined My question is, is there a way to access them using window or globalThis? And if not where else are they? As they are global there is not really any practical need for this, I'm just curious.
Variables declared with var and without any keyword are attached to the global object. _My question is, is there a way to access them using window or globalThis?_ Yes, if you create a new property on the global object pointing to your const. But why do that. _And if not where else are they?_ They are variables just like `globalThis`. Not attached to anything, can be accessed directly. If you are talking about the scope then they are block scoped. Live inside the `{ }` they are defined in.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, constants, javascript objects, global" }
Why did Stormtroopers leave their stations to watch lightsaber duel between Vader and Kenobi? The only reason Luke, Leia, Han and Chewbacca were able to escape the Death Star is because the Stormtroopers left their stations and ran like kids to watch the lightsaber duel between Vader and Kenobi. Why didn't the stormtroopers act like professionals? If they were so interested, they could have watched a hologram or video of the duel later.
Though whether Darth Vader actually held rank in the Imperial military was unclear, he is still at the very least a VIP aboard the Death Star. The stormtroopers choosing to provide such an important figure with backup when he is engaged in combat with an unknown foe is perfectly reasonable. In addition, the stormtroopers aboard the Death Star were specifically instructed to allow the Millennium Falcon to escape after the tracking device was installed so that they could be tracked to the location of the rebel base. Leaving their posts to provide aid to Darth Vader is a perfect excuse to do so.
stackexchange-scifi
{ "answer_score": 152, "question_score": 70, "tags": "star wars" }
What is the R convention when plotting (e.g., for a scatterplot) if the data has missing values? How does `R` treat missing values when plotting data? For example, if I have data that I read in from a csv like the following: Y X1 X2 0.1 0.2 0.1 0.2 0.2 ... how would `R` treat that second observation when plotting (specifically for a scatterplot)?
They will be omitted. However the visual effect depends a lot on the type of chart you choose. Try with these: x <- c(1,NA,3,5,2,4) plot(x, t="l") #line plot(x, t="p") #points plot(x, t="b") #both barplot(x) I'd say `barplot` is the best way when plotting data that includes `NA`'s, but of course that's up to you. see `help(plot)` or `help(barplot)` for details. * * * EDIT: with a scatterplot these would be omitted as well, see below y <- 1:6 plot(x,y, t="p") #points
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r, plot, missing data" }
JetBrains Rider "Reformat code" action (Ctrl+Alt+L) removes line feed at end of file I am using JetBrains Rider version 2018.3.3 on Ubuntu 18.04. I have enabled the setting `Editor -> General -> Ensure line feed at file end on Save`. This works great when saving a previously edited .NET/C# `.cs` file. However, when applying the "Reformat code" action (keyboard shortcut: `Ctrl`+`Alt`+`L`) which also automatically saves the file after applying the code reformat, the line feed at the end of the file is removed again. Is this something for a bug report or is there another setting to configure the reformat action to stop this behavior?
I found the required setting. Checking `Line feed at end of file` in `Settings -> Editor -> Code Style -> C# -> Line Breaks and Wrapping` prevents code reformat/cleanup actions from removing the newline at the end of files. ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "c#, .net, jetbrains ide, rider" }
Javascript: Convert date to UTC format I have the following date in UTC format: `2016-06-18T05:18:27.935Z` I am using the code below to convert it to the following format `2016-06-18 05:18:27 ` so I can compared it in `MySQL` database against `updatedAt` column. var date = new Date(lastRequest); date = date.getUTCFullYear() + '-' + ('00' + (date.getUTCMonth() + 1)).slice(-2) + '-' + ('00' + date.getUTCDate()).slice(-2) + ' ' + ('00' + date.getUTCHours()).slice(-2) + ':' + ('00' + date.getUTCMinutes()).slice(-2) + ':' + ('00' + date.getUTCSeconds()).slice(-2); I need to get the date of the last record and convert its date back to UTC format. Basically, how do I go from the following format: `2016-06-18 05:18:27` back to UTC?
new Date('2016-06-18 05:18:27').toUTCString() The toUTCString() method converts a date to a string, using the UTC time zone. < And in fact, your format maybe the result of this: new Date('2016-06-18 05:18:27').toISOString() And by the way, if you want to format the date, moment.js or fecha may be better. You can also find similar answers in How do you convert a JavaScript date to UTC?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, mysql, node.js, sequelize.js" }
Detecting mysql support in php I want to get info about mysql support with PHP. I need a code to detect if server have mysql support.
if (extension_loaded('mysqlnd')) // or 'mysql' or 'pdo_*' echo 'MYSQL extension is loaded'; you can also use: if (function_exists('mysql_connect')) echo 'MYSQL functions are available';
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "php, mysql" }
Electric Bidet Toilet seat started tripping GFCI I have an electric bidet toilet seat that plugs into the GFCI outlet in my bathroom. After about 6 months it started tripping the GFCI instantly upon being plugged in. Does this mean the toilet seat has an electrical problem? If the toilet seat works on a non-GFCI outlet would it be safe to use one? I am afraid of electrified water being shot at my rectum. Would the normal ground wire be enough to prevent any danger?
## It broke My bet? The appliance is tripping the GFCI _because the appliance has a ground fault_. Shocking, I know, right? I'd have a qualified technician examine it for signs of what went wrong, or replace it outright if repair is not an option.
stackexchange-diy
{ "answer_score": 6, "question_score": 0, "tags": "electrical" }
Yii - Get min, max of a column using active record I am using active record. Lets call the model Product. How can i get "select min(price) from tbl_product where name like '%hair spray%'" using active record?
You could use something like this: $criteria = new CDbCriteria; $criteria->select='MIN(price) as minprice'; $criteria->condition='name LIKE :searchTxt'; $criteria->params=array(':searchTxt'=>'%hair spray%'); $product = Product::model()->find($criteria); You would just need to declare: `public $minprice;` in your model class. (Using the above example.) See docs here
stackexchange-stackoverflow
{ "answer_score": 24, "question_score": 9, "tags": "php, activerecord, yii" }
Why does Lex Luthor want Batman dead? Traditionally, Lex Luthor is an enemy of Superman, as shown in films like _Superman_ and _Superman Returns_. However, in the movie _Batman V Superman: Dawn of Justice_ , Lex forces Superman to bring him Batman's head. Does he really want to kill Batman? If yes, then why?
**Lex doesn't actually want to kill Batman - he wants to kill Superman.** All Lex Luthor wants to do throughout _Batman V Superman: Dawn of Justice_ is kill Superman, as he fears that a man as powerful as Superman will one day become a dictator of sorts, using his godlike powers to take over the world. By forcing Superman to fight Batman by taking Martha Kent hostage, Lex hopes that Batman will use the Kryptonite he stole from Lex to kill Superman - which very nearly happens. It's worth noting that Lex has been baiting the two of them into battle for some time, setting up a series of events that lead Bruce Wayne/Batman to come to the same conclusion that Lex has - that Superman is too dangerous to live. As such, Batman is nothing more than a pawn in the game that Lex Luthor is playing.
stackexchange-movies
{ "answer_score": 11, "question_score": 10, "tags": "dc extended universe, batman v superman dawn of justice" }
Complemented subspace constructed from finite pieces Suppose $Y=\overline{\cup E_n}$ is a closed subspace of a Banach space, where each $E_n$ is a $n$-dimensional subspace, $K$-complemented in $X$, and for any $n$, $E_n\subseteq E_{n+1}$. Can one conclude that $Y$ is complemented in $X$?
No. Take $X=\ell_\infty({\bf N})$ and take $E_n = \operatorname{span}(e_1,\dots, e_n)$. Then $Y=c_0({\bf N})$ which is well-known - by a non-trivial argument - to be uncomplemented in $X$ (in the sense of Banach spaces). Look up "Phillips's Lemma".
stackexchange-mathoverflow_net_7z
{ "answer_score": 2, "question_score": 1, "tags": "fa.functional analysis, banach spaces" }
R: how to find the first digit in a string string = "ABC3JFD456" Suppose I have the above string, and I wish to find what the first digit in the string is and store its value. In this case, I would want to store the value 3 (since it's the first-occuring digit in the string). `grepl("\\d", string)` only returns a logical value, but does not tell me anything about where or what the first digit is. Which regular expression should I use to find the value of the first digit?
Base R regmatches(string, regexpr("\\d", string)) ## [1] "3" Or using `stringi` library(stringi) stri_extract_first(string, regex = "\\d") ## [1] "3" Or using `stringr` library(stringr) str_extract(string, "\\d") ## [1] "3"
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 9, "tags": "regex, r" }
Which is faster: glob() or opendir() Which is faster between `glob()` and `opendir()`, for reading around 1-2K file(s)?
Obviously `opendir()` should be (and is) quicker as it opens the directory handler and lets you iterate. Because `glob()` has to parse the first argument it's going to take some more time (plus `glob` handles recursive directories so it'll scan subdirs, which will add to the execution time.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 6, "tags": "php, file io, glob, opendir" }
thousand and million formatting for negative numbers (excel/ googlesheets) Hello I currently use this formatting to show big numbers as either 1.2M or 20K (instead of 1 200 000 ans 20 000): [>999999]0.00,,\M;[>999]0.0,\K;0.0,\K I have an issue for negative numbers, I can show -20K but how can I also show -20M? Thanks in advance.
**Its not possible.** What you could do is add a formulae like this or you could use conditional formatting along with multiple formats like this
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "excel, google sheets, formatting" }
Open all images in a folder on gimp using Python I get something similar using: gimp = r'C:\Program Files\GIMP 2\bin\gimp-2.10.exe' os.chdir(folder) filesnames= os.listdir() for f in filesnames: actfile = folder+'\\'+f p = subprocess.Popen([gimpcamin, actfile]) p.wait() But this script can open only one image and the next image opens when I close Gimp. Note: I am using VSCode
I believe that the issue is that you have `p.wait()` immediately after `p = subprocess.Popen([gimpcamin, actfile])`, which makes it wait for that command (i.e., Gimp) to return before proceeding. You should try: gimp = r'C:\Program Files\GIMP 2\bin\gimp-2.10.exe' os.chdir(folder) filesnames= os.listdir() processes = [] for f in filesnames: actfile = folder+'\\'+f processes.append(subprocess.Popen([gimpcamin, actfile])) # wait for all processes to finish for p in processes: p.wait() I'm not sure that this what you really want. I suspect you rather have just another Window of Gimp open for each image, rather than opening a whole different instance. You should double-check Gimp's interface to see if that's possible.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, gimp" }
3-DOF Robot Dynamics error in Robotics Toolbox I am trying to compute dynamics of 3 DOF robot using Robotics Toolbox by executing this code: robot.accel(q, zeros(1,3), zeros(1,3)) But I am getting this error: Assignment has more non-singleton rhs dimensions than non-singleton subscripts My robot is: L(1)= Link([0 0.03 0 -pi/2]); L(2)= Link([0 0 0.28 0]); L(3)= Link([0 0 0.2 0]); L(1).m = 1; L(2).m = 4; L(3).m = 3; L(1).r=[0 0 -0.015]; L(2).r=[0.14 0 0]; L(3).r=[0.1 0 0]; ax1=0.03; ay1=0.03; az1=0.03; ax2=0.28; ay2=0.05; az2=0.05; ax3=0.2; ay3=0.05; az3=0.05; I1=1/12*[ay1^2+az1^2 0 0; 0 ax1^2+az1^2 0; 0 0 ax1^2+ay1^2]; I2=4/12*[ay2^2+az2^2 0 0; 0 ax2^2+az2^2 0; 0 0 ax2^2+ay2^2]; I3=3/12*[ay3^2+az3^2 0 0; 0 ax3^2+az3^2 0; 0 0 ax3^2+ay3^2]; L(1).I=I1; L(2).I=I2; L(3).I=I3; q=[0 0 0] robot=SerialLink(L);
This is not a great error message and it only happens if you are using the MATLAB rather than the (100x) faster MEX version of the dynamics. The error occurs because the motor inertias are not set, and they default to []. To fix this I ran this code after the robot was defined >> for i=1:3 robot.links(i).Jm = 0; end but you could build it into your initialisation code. The acceleration is >> robot.accel(q, zeros(1,3), zeros(1,3)) ans = -0.0000 22.6479 -11.5237
stackexchange-robotics
{ "answer_score": 1, "question_score": 4, "tags": "robotic arm, matlab, dynamics, simulator" }
MySQL Server 5.7 and WAMPServer in the same machine wamp can't run I have installed mysqlserver 5.7 and after that I can not run wampserver it's orange icon never turn to green. any body please help.
WAMPServer also has a MySQL Server installed as part of it. By default MySQL Server talks with the outside world using a TCP port (3306) and only one app can be using a TCP port at any one time. So basically you have 2 people both trying to use the same phone line, which is not possible. If you have WAMPServer installed you have no need to install another MySQL Server instance, so I suggest you uninstall the independant MySQ Server that you have installed. It is quite possible for one MySQL Server to run 100's of seperate databases, so if you thought you needed ONE MYSQL PER DATABASE that is not the case.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "mysql, wampserver" }