INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to extract DV data from a Sony DCR-PC5E video recorder I bought the Sony DCR-PC5E back in 2001 and it worked flawlessly until today. I wanted to extract data from the almost 100 video tapes that gathered over the years and discovered that none of my Macs has a Firewire input anymore. Also when I tried to revive older Macs I noticed that they were not powerful enough to extract unaltered data from the video recorder. What to do?
I bought a IOCrest IEEE 1394b Firewire Controller Card and installed it on my Debian v9.1 `3.16.0-4-amd64 #1 SMP Debian 3.16.43-2+deb8u2 (2017-06-26) x86_64 GNU/Linux` home computer. I installed the following Debian packages: apt-get -y install dvgrab libraw1394-11 libavc1394-0 libiec61883-0 I connected the camera with the computer, ran the command dvgrab --format raw --noavc foo and launched viewing of a tape on the camera. This started capturing data, which resulted into 999.89 MiB for every 4 minutes and 51 seconds of movie, without any loss of data.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "debian, video capture" }
scale_fill_discrete and scale_fill_manual - legend options confusion I have a problem with applying two different changes on my `ggplot2` object. I have a barplot with 3 groups on it. I want to: 1. set color for each group 2. reorder the order of legend labels I have found the following solutions to the above problems: 1. `+ scale_fill_manual(values = c("red", "green", "blue"))` 2. `+ scale_fill_discrete(guide = guide_legend(reverse=TRUE))` The problem is the second application (`+ scale_fill_discrete(...)`) is overriding the first one: Scale for 'fill' is already present. Adding another scale for 'fill', which will replace the existing scale. (separately both of them work fine). How to deal with it?
You do not need to make it double, this should work: scale_fill_manual(values = c("red", "green", "blue"), name = "My name", guide = guide_legend(reverse = TRUE))
stackexchange-stackoverflow
{ "answer_score": 47, "question_score": 26, "tags": "r, colors, plot, ggplot2, scale" }
How to properly search and parse an array using a sequence of elements as the target I have a byte array that looks something like this: byte[] exampleArray = new byte[] { 0x01, 0x13, 0x10, 0xe2, 0xb9, 0x13, 0x10, 0x75, 0x3a, 0x13 }; My end goal is to split this array into sub array's anytime I see the sequence `{ 0x13, 0x10 }`. So my desired result on the example array would be: { 0x01 } { 0xe2, 0xb9 } { 0x75, 0x3a, 0x13 } Ideally, I would also need to know that the final array, `{ 0x75, 0x3a, 0x13 }`, did not end with the search sequence so that I could work with that as a special case. Any thoughts on the best approach?
List<byte[]> Split(byte[] bArray) { List<byte[]> result = new List<byte[]>(); List<byte> tmp = new List<byte>(); int i, n = bArray.Length; for (i = 0; i < n; i++) { if (bArray[i] == 0x13 && (i + 1 < n && bArray[i + 1] == 0x10)) { result.Add(tmp.ToArray()); tmp.Clear(); i++; } else tmp.Add(bArray[i]); } if (tmp.Count > 0) result.Add(tmp.ToArray()); return result; } The last array can not end with sequence, any splited part does not contein separator. Only byte 0x13 can happen, so if this is importane for you, you can jast check last byte of last sub array.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 5, "tags": "c#, .net, arrays, parsing" }
merging particular text files in different directories I have 6 directories. Each directory includes 8 text files. These text files share the same prefix. I need to combine these text files as follows; Assume, first text file in directory_1 contains files containing the text `abc_1`, directory_2 contains files with the text `abc_2` and so on. Merged text file for the first text files needs to be in this form: abc_1 abc_2 abc_3 .. abc_6 The second, third... and eighth text files also need to be combined with the same rule.
Your files must be sortable, so assuming the names of the files in each directory end with a number from 1 to 8, such as `foo1`, `foo2`... in one directory and `bar1`, `bar2`... in another and so on, you could use `cat` and a `for` loop to con **cat** enate them: for j in {1..8}; do cat directory_{1..6}/*$j > newfile$j; done (no need to "quote" a variable we know is a single digit) This will print, in, for example, `newfile1`, the contents of directory_1/foo1 directory_2/bar1 directory_3/baz1 ... whatever those contents are, and in `newfile2` the contents of `directory_1/foo2`, `diectory_2/bar2` etc
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 3, "tags": "command line, text processing" }
Date Picker always show from the year 0 when pop up When load the page, I've set the date to datepicker.. But when it's pop up, it always show from january 0(year). why is like that. I am using Bootstrap datepicker. **In my text box the date is 28 nov 2013 . But this date is not highlighted in datepicker widget ** **But on change works perfectly. I don't know why ?**
_You have to **update** the date in `bootstrap datepicker` widget in order to see it in the calender_, after setting the date. $('.datepicker').datepicker('update'); Check this **answer** for pictorials. var plus14days = new Date(); plus14days.setDate(plus14days.getDate() + 14); $("#datepicker").datepicker("setDate", plus14days); //set 14 days prior $("#datepicker").datepicker('update'); //once updated you can it in datepicker
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, twitter bootstrap, datepicker" }
How to make common method which would be call from any component I have components some of which use the same function (in client-side JavaScript controller). At this moment i resolved this problem putting this function in each component. But it isn't comfortable :( I tried to use tag aura:method with access="global" in main component and invoke it from child ones but it isn't work. How to resolve this problem without using events?
The only way to "share" at the moment is to use the extends keyword. If you create a component, and then use the extends attribute on a child component, that component's helper are available to the child. See What is Inherited? for additional things that are inherited when you extend a component.
stackexchange-salesforce
{ "answer_score": 5, "question_score": 4, "tags": "lightning aura components" }
Erro comparando array php $rua[] = {1,1,2,2,2,2}; $countRua = count($rua, COUNT_RECURSIVE); for ($i=0; $i < $countRua; $i++) { if ($rua[$i] == $rua[$i+1]) { } } Possuo o `for` acima percorrendo um `array` e validando se a posição é igual a próxima posição porém, quando chega na última ele tenta comparar com a posição 7 e retorna o erro abaixo, algum jeito de ajustar isso ? > Undefined offset: 6
Pode resolver isso verificando se o índice existe com `isset()` a condição do if deve ficar composta dessa forma: if (isset($rua[$i+1]) && $rua[$i] == $rua[$i+1]) {
stackexchange-pt_stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "php" }
ОШИБКА при установке yaml для Python При установке yaml, командой: $ `pip install pyyaml` вылезает оповещение, что пакет установлен, а при запуске проекта: ModuleNotFoundError: No module named 'yaml' как фиксануть?
Вы можете проверить был ли установлен модуль командой: $ pip freeze Если модуль установлен, то требуется больше информации по вашей проблеме, например, показать код где вы его используете (импортируете).
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python, api, telegram, yaml" }
Adding an event handler for a control in child form from parent form in C# I have two forms. One is a parent form with a button and a text box. On click of the button, a dialog opens the child form which in turn has a textbox and a button. Now what I want is whenever the text in the child form textbox changes the text in the parent form textbox changes automatically. To acquire this, what I did is: Form3 f3 = new Form3(); f3.delBetInpTxt.TextChanged +=new EventHandler(delBetInpTxt_TextChanged); public void delBetInpTxt_TextChanged(object sender, EventArgs e) { TextBox t = (TextBox)sender; simDelTxt.Text = t.Text + " ms"; } I added the above code in the parent form and the child form is Form3. But nothing happens, the parent form textbox still doesn't change even after changing the text in the child form. What am I doing wrong here?
You can add event in child form and rise it when text changed. Then create event handler in parent form and change text in parent form. In child form: public event EventHandler OnChildTextChanged; private void textBox1_TextChanged(object sender, EventArgs e) { if(OnChildTextChanged != null) OnChildTextChanged(textBox1.Text, null); } In parent form: private void button1_Click(object sender, EventArgs e) { ChildForm child = new ChildForm(); child.OnChildTextChanged += new EventHandler(child_OnChildTextChanged); child.ShowDialog(); } void child_OnChildTextChanged(object sender, EventArgs e) { textBox1.Text = (string)sender; } Hope it helps.
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 4, "tags": "c#, winforms, inheritance" }
How can I prove that $ \neg (A \Rightarrow B) \iff A \land \neg B$ on a more formal level? I want to prove that $\neg(A \Rightarrow B) \iff A \land \neg B$ holds without using a truth table. "$\Leftarrow$": This one is simple: Suppose $A \land \neg B$. We want to show: $(A \Rightarrow B) \Rightarrow \bot$. For that we suppose $A\Rightarrow B$. Now our goal is $\bot$. Since by our assumption $A$ and $A\Rightarrow B$ are true we get $B$ by using Modus ponens. Since $B$ and $\neg B$ holds we get $\bot$ by using Modus ponens again. $\square$ How does "$\Rightarrow$" work? Thanks in advance!
Following from my comment: the $\Rightarrow$ direction requires that you invoke a non-constructive rule, such as the law of excluded middle or double-negation elimination. So assume $\neg (A \Rightarrow B)$. Using the law of excluded middle: * $A \vee \neg A$ is true. If $\neg A$ is true then $A \Rightarrow B$ is true by ex falso—contradiction! So $\neg A$ is true. * $B \vee \neg B$ is true. If $B$ is true then $A \Rightarrow B$ is true—contradiction! So $\neg B$ is true. _[Edit: LEM is not actually required in this step.]_ So $A \wedge \neg B$ is true.
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "logic, propositional calculus" }
Channel permission update for members? When I change the permission of a role in a voice channel, the members that are inside of it don't get muted. They need to leave and then re-enter to get muted. Here is a piece of my code: cat = ctx.guild.get_channel(categorychannel) everyone = ctx.guild.default_role perm = cat.overwrites_for(everyone) perm.speak = False channel = await ctx.guild.create_voice_channel("test", category=cat) await channel.set_permissions(everyone, overwrite=perm) Would it be possible to have something similar to an update function?
After some tests I found that we can move the member to the same channel that it update the permissions. So... you can use these functions: member.move_to(channel) Or member.edit(voice_channel=channel)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, api, discord.py" }
how to check particular input contain dot (.) or not in magento2? I want to use magento2 framework validator .I'm not able to identify which function need to use.i think for this i have to use `Zend_Validate` class. In plain php i can use following way. $pattern="/./"; $subject="some.thing"; preg_match($pattern, $subject, $matches);
Refer to this zend documentation this will help <
stackexchange-magento
{ "answer_score": 0, "question_score": 0, "tags": "magento2, validation, zend framework" }
Regex: Capture everything after first colon if colon exists otherwise capture everything Using regex alone, I am having trouble capturing things after a field entry that comes in one of three ways: Address: 123 Test Lane, City St Address:123 Test Lane, City St 123 Test Lane, City St I need to extract only the address, name, other info. I found Regex to capture everything after optional token and made a simpler regex `^(?:.*:\s?)?\K.+` that works but the system I'm using does not support the `\K` operator. I'm hoping I'm not out of options here.
You can use [^:\s][^:\n]*$ _Details_ : * `[^:\s]` \- any char other than `:` and whitespace * `[^:\n]*` \- zero or more chars other than `:` and LF * `$` \- end of string / line (if multiline mode is turned on). See the regex demo.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "regex" }
How to change content of variable inside a Broadcast Receiver? In my `BroadcastReceiver` I'm trying to detect a missed call. So I'm checking if the phone goes from `EXTRA_STATE_RINGING` to `EXTRA_STATE_IDLE`. I'm giving each state a fixed value and checking if a particular value is obtained. However, the values of the variable are not reflected as I expect them to. I've tried using `SharedPreferences`, but I don't think they can be used inside a `BroadcastReceiver`. I've tried calling in a different class' object but it's giving me errors. How can I achieve this? Please help.
You should use some king of persistent storage to keep your state variable value between receiving broadcasts. You can use `mysql`, `files` or better `SharedPreferences`. You can easily use `SharedPreferences` from `BroadcastReceiver`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "android, broadcastreceiver" }
Making a wysiwyg in Qt What I would like to do is to make a WYSIWYG editor, not a big one, just the common utilities, so bold, italic, underline, size, font, in Qt. My approach for now is to make it in a QTextEdit, when the user click the button i get the signal and using the cursor index i put html tag, but I don't know if it's a good idea. Any Advice?
You can always use the **webkit** module and relay on the `contentEditable` feature.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c++, qt, wysiwyg" }
How can I find elevation in my iOS application I am developing an iOS application in which I provide a facility to find the distance, average speed, calories, time etc. according to a walking path. Now I want to find the elevation of my walking according to distance and speed. I also want to draw the elevation graph of my walking path. I have searched a lot for that but I can't find a solution.
You can use the google elevation api It returns the data in JSON format. You just need to add SBJSON to your xcode project. And then send the NSURLReuest in the following manner : Everything from here is just a cakewalk if you know how to parse JSON response :)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "ios, geospatial" }
Use ng-repeat index as class name? Is it possible to use the $index of ng-repeat in the class name? Example: ng-class="{'hand-' + $index: true}" Thank you!
You can use it like this: ng-class="['hand-' + $index]" Additionally, you can use the class attribute to interpolate the class value class="hand-{{$index}}"
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 10, "tags": "angularjs" }
How can I audit ONLY logon / logoff's in Windows Domain I am aware of multiple "auditing" questions around SF, however I feel as though this question is slightly different. **The Goal** : Audit _only_ user logons and logoffs in my domain. The domain functional level is 2003 right now, however I'm hoping to raise it shortly to 2008 and then 2008 R2. As it stands, this is the auditing policy !enter image description here This is the result of that policy !enter image description here What I'm not concerned with is the Directory Service Access / Other object Access, etc events. I just want logons and logoffs as the other events bloat the logs. Can anyone spot what I'm doing wrong here?
What you're doing wrong may not be what you want to hear. What you're currently attempting to do is limit your logging to just what you want to see. What you should be doing is letting the logging collect and accumulate and then use another tool to filter out what you need to find relevant. This is what a log collection device does. As for "bloating the logs" unless these logs are approaching hundreds of megabytes in size I don't think you need to worry about that. Windows has a rotation mechanism for dealing with logs. So... be sure account logon events are logged... this should be applied by default at your domain controller policy. Then look into the Windows facilities for centralizing those events, which were new features in the 2008 or 2008R2 systems.
stackexchange-serverfault
{ "answer_score": 2, "question_score": 0, "tags": "windows server 2008, active directory" }
Projection homomorphism of an abelian group is closed Let $G$ be a an abelian topological group and let $\Gamma$ be a discrete subgroup. Is the projection homomorphism $\pi:G\to G/\Gamma$ closed?
No. For instance, taking $G=\mathbb{R}$ and $\Gamma=\mathbb{Z}$, the set $\\{n+1/2^n:n\in\mathbb{Z}_+\\}$ is closed in $\mathbb{R}$ but is image in $\mathbb{R}/\mathbb{Z}$ is not.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "general topology, group theory, topological groups" }
Get array item permutations and compare to array In my program, I'm trying to see if the user input is equal to the value in the database. However, the user input might be in a different order from the value in the database. For example: User input A,C,B,E,D,F,G Database value A,B,C,E,F,G,D Therefore, when I compare user input to the database value, the strings will not match, even though the user input will have the appropriate responses. My question is whether or not it is possible to compare the user input to all possible permutations of the database value. The user input and database value may be of variable lengths. If there is one match, then show a messagebox saying "Correct". If there are no matches, then show a messagebox saying "Incorrect". The user input is in a string, and the database value is also a string. Thanks for your help. * each item is unique
The `HashSet` class has a `SetEquals` method that will determine if two sequences represent the same set of items (sets are unordered). public static bool SetEquals<T>(this IEnumerable<T> first , IEnumerable<T> second , IEqualityComparer<T> comparer = null) { comparer = comparer ?? EqualityComparer<T>.Default; return new HashSet<T>(second).SetEquals(first); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, permutation" }
BI Publisher .rtf Spacing if there is null value I am facing an issue on BI Publisher, I have some texts shown in a list.When they have value everything is fine , but when any of them is null then the space is held and shown empty line.Is it possible to wrap the empty line ? You can notice my code above. < "PDF" < "RTF" Observações: COMMENTS <?if@inlines: FORM = 'ABC' ?>This is a test . <?end if?> <?if@inlines: STS = 'LATE' ?>TESTETSTS<?end if?>
Take off the @inlines. That's what is preventing the new lines.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "oracle, bi publisher" }
Tensorflow filter operation on dataset with several columns I want to create a subset of my data by applying tf.data.Dataset filter operation. I have this data: data = tf.convert_to_tensor([[1, 2, 1, 1, 5, 5, 9, 12], [1, 2, 3, 8, 4, 5, 9, 12]]) dataset = tf.data.Dataset.from_tensor_slices(data) I want to retrieve a subset of 'dataset' which corresponds to all elements whose first column is equal to 1. So, result should be: [[1, 1, 1], [1, 3, 8]] # dtype : dataset I tried this: subset = dataset.filter(lambda x: tf.equal(x[0], 1)) But I don't get the correct result, since it sends me back x[0] Someone to help me ?
I finally resolved it: a = tf.convert_to_tensor([1, 2, 1, 1, 5, 5, 9, 12]) b = tf.convert_to_tensor([1, 2, 3, 8, 4, 5, 9, 12]) data_set = tf.data.Dataset.from_tensor_slices((a, b)) subset = data_set.filter(lambda x, y: tf.equal(x, 1))
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "tensorflow, filter" }
Should comments have the possibility of being voted down? > **Possible Duplicate:** > Should downvoting be allowed on comments? People can answer a question with a comment and they can be voted up but not down. Someone just answered something (in the comment section) and was upvoted 4 times but is downright wrong. Should comments have the possibility of being voted down? Or shouldn't it be a sort of flag, not for "spam" but for 'this is an answer not a comment'?
Voting a comment up does nothing. So who cares if they get voted up? Comments != Answers, this should be very clear. The proper thing to do in this situation is to reply to the comment and state why you think the comment is wrong, and ask the person to remove it.
stackexchange-meta
{ "answer_score": 2, "question_score": 1, "tags": "feature request, questions, comments" }
Marketing Cloud Cloning to another instance? What is the easiest way to clone a marketing cloud instance? including journeys, cloud pages, automation rules, data extensions. I do not see ANY functionality based around this.
There is currently no “out of the box” functionality readily available. You can use API to fetch assets, such as emails, journeys, etc., store the output locally, and create same assets on the new environment. Even though it is technically feasible - this indeed is quite a time consuming task, just to get an overview of all the development around the SFMC APIs. If this is a one-off task, I will advise you to reach out to Salesforce. Their architects have access to internal tools, enabling them to migrate such assets more easily (and hence faster). This is a billable service, but compared to how much work a manual (or evenAPI based) migration might take, this could be a good investment.
stackexchange-salesforce
{ "answer_score": 4, "question_score": 1, "tags": "marketing cloud" }
I am getting an error that "Post 404 [conversation update]" in microsoft bot ? how to resolve that? POST 404 [conversationUpdate] I am getting the error only when I have used web API, else working properly.
You get this code error in the Bot Framework Channel Emulator when you enter wrong the endpoint. I think you are entering wrong the endpoint. I had the same error in this case, when I entered "server + /api/messages", it worked. For example: < If this solution doesn`t work, please give more information, your post is very general.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -2, "tags": "botframework" }
Difference between [Noun]する vs [Noun]をする vs [Noun]だ I've never really understand the difference between these 3 structures : > ... > > **** **** ... > > **** **** ... I wouldn't be surprised if the first 2 were totaly interchangeable, but what about the third? Does it have a particular nuance or is it virtually the same as the others?
It is mostly just different ways of saying the same thing. In english the difference might be something like this: > 1. (subject) attacked with an amazing speed. > When the noun signifying the action () is directly tied with the verb , you can interpret the compound as a verb. ie. "attacked". > 2. (subject) made/performed an attack with an amazing speed. > In normal usage these ways of saying the sentence is as you say interchangeable. Grammatically you disconnect the noun signifying the action from the verb , thus you "do an attack" instead of just "attacking". > 3. It was an attack with an amazing speed. > Here, since you end the sentence with / instead of , you've moved from "doing" to "being", hence "It was". Hope that answers your question.
stackexchange-japanese
{ "answer_score": 6, "question_score": 5, "tags": "grammar, nuances" }
Groovy: Extracting numbers from file I have a list with lots of numbers like: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ... How can I extract them line by line and do some calculations? Something like (pseudocode): def f = new File("data.txt") f.eachLine() { println(it.findAll( /\d+/ )*.toInteger()*2) } I need to get rid of the comma and the whitespaces.
How about this? def fileContent = new File('data.txt').text def matches = fileContent =~ /\d+/ matches.each { println new Integer(it)*2 } Gives 2 4 6 8 10 12 14 16 18 20
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "groovy" }
Is there a DisplayName attribute in CakePHP as there is in ASP.NET MVC? I'm aware of the "conventions over configurations" philosophy beyond CakePHP. The "bake all" command generates automatically Models, Controllers and Views by using english language conventions. The problem is that the website I'm making needs to be in spanish. I can code the back-end (database and MVC stuff) in english but the automatic view it's rendered in english too and I need it in spanish. In MVC I can just add a DisplayName attribute to the model (anyway, I never had problems with writing the names in spanish) so the view will show it, instead of the name of the field in the database/model. So, Does CakePHP have a easy way to do the same? Do I have to modify each automatic view or create my own?
There is no such property, no, however baked view templates are by default using translation functions for all output, so you could simply create proper spanish translations and you should be good. See * **Cookbook > Internationalization& Localization (CakePHP 3)** * **Cookbook > Core Libraries > Utilities > Internationalization& Localization (CakePHP 2)**
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "cakephp" }
AngularJS integration with D3.js Could someone describe a simple strategy of integration AngularJS and D3.js? Both libraries seem to work so differently. D3 wants all the data bound to DOM elements and Angular wants to keep it in the ViewModel ("controller"). I am having hard time thinking of how to approach writing a UI in D3 that is interactive while still keeping things in AngularJS. Any help would be appreciated.
Use Angular directives for almost everything. Use of controllers should be minimal. In your d3 code, only interact with the `element` that the directive provides in its link function. e.g. .directive('myDirective', function() { return { link: function(scope, element, attrs) { d3.select(element[0]).append('svg'); } }; });
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, angularjs, d3.js" }
If col 2 has q then print the val in col 1 and if col 2 does not have q then print the same val in col 2 A01_106367192 A01_106367192 A01_106359962 A01_106359962 A01_106106644 A01_106106656 A01_106045906 A01_106045909 A01_105865211 A01_105865216 A01_105877866 q B01_114451441 q A01_105801529 A01_105801532 A01_105803107 A01_105803079 A01_105803074 A01_105803079 A01_105061789 A01_105061763 A01_105408577 A01_105408577 A01_104975080 A01_104975074 A01_104994687 A01_104994690 A01_104983310 q A01_104542183 A01_104542186 A01_104652672 q A01_104652685 A01_104652679 A01_105006416 A01_105006421 A01_105136838 A01_105136837 A01_104359686 q A01_104359660 A01_104359665 awk '{if ($2 == q) print $1; else print$2 }' input_file |less Returns col 2 as it is.
Your code: awk '{if ($2 == q) print $1; else print$2 }' input_file This will print `$1` if `$2` is equal to the `awk` variable `q`. This variable is uninitialized, so the test is not likely to ever be true, unless you define `q` as _the string_ `"q"` on the command line: awk -vq="q" '{if ($2 == q) print $1; else print $2 }' What you probably want is to compare with `"q"` in the code itself: awk '{if ($2 == "q") print $1; else print $2 }' input_file Or, in a more idiomatic way of saying the same thing: awk '$2 == "q" { print $1 } $2 != "q" { print $2 }' or, awk '$2 == "q" { print $1; next } { print $2 }' or, as RomanPerekhrest's solution shows, using the ternary `?:` operator.
stackexchange-unix
{ "answer_score": 1, "question_score": 0, "tags": "awk" }
How to tell how many hashes/sec the bitcoin core app on osx is running? I'm curious how many hashes per sec my cpu is able to perform, is there some way to check this? This is a follow-up to this question.
Most CPUs will do a few megahash per second, which is completely worthless for anything other than testing and has been for several years now. It may be possible to improve performance in the future as Skylake Intel x86 processors include specific instructions for SHA256, but only by a few percent. Even with improvements it is a waste of time and power attempting to use anything but the most efficient dedicated hardware. A large portion of ASIC miners are effectively obsolete due to their power requirements outstripping their output, and they are orders of magnitude more efficient than mining on a CPU.
stackexchange-bitcoin
{ "answer_score": 3, "question_score": 3, "tags": "bitcoin core, hashpower, solo mining, cpu mining" }
How to Trigger animation in WPF using C# I want to play animation using c# when i press Crtl private void rtb_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl) { //lstBox1.Opacity = 1; //here i want to play fadeIn animation } }
Assuming `listBox1` is declared in XAML and you want to apply _Fade-In animation_ on it. You can _toggle opacity from 0 to 1_ like this: DoubleAnimation animation = new DoubleAnimation(0.0, 1.0, new Duration(new TimeSpan(0,0,1))); listBox1.BeginAnimation(ListBox.OpacityProperty, animation); * * * You can achieve that with Storyboard as well (but definitely no use when you can achieve that simply using double animation): DoubleAnimation animation = new DoubleAnimation(0.0, 1.0, new Duration(new TimeSpan(0, 0, 2))); Storyboard storyBoard = new Storyboard(); storyBoard.Children.Add(animation); Storyboard.SetTarget(animation, listBox); Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity")); storyBoard.Begin();
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, wpf" }
jquery update class of the same name throughout page I am trying to do a foreach on class ajax-link so i can load text from an ajax call but the code is only upsating on the first ajax-link on the page. All the others in the page are not being updated. What am I doing wrong? $(document).ready(function(){ $(".ajax-link").each(function(){ var href = $(this).attr('href') + '?request=ajax&boo=' + $(this).text(); //URL alert(href); // Is It working? $(this).load(href); //Create the xmlHttpRequest return false; //Stop the HTTP request }); });
`return false;` will break you out of the `each()` statement. You need to remove that.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "jquery, ajax, each" }
pyspark: create column based on string contained in another column How can one reduce noise in a column by extracting a certain string using Pyspark. Please check the table below. Instead of having 2 categories only, additional text (in duration) screws up any grouping. The column duration1 created by the UDF below is supposed to solve this issue, but an operator as like "value.contains()", "Like" or "in" is missing. duration|duration1| Full day|Full day| Full day x|other| Half-day|Half day| Half-day morning|other| def duration_simple(value): if value == "Full day": return 'Full day' elif value == "Half-day": return 'Half day' else: return 'other' udfduration_simple = udf(duration_simple, StringType()) new_df= old_df.withColumn("duration1", udfduration_simple("duration"))
you can use like() function, similar to SQL from pyspark.sql import functions as F new_df= df.select( df.duration, F.when(df.duration.like("%Full day%"),"Full day").when(df.duration.like("%Half-day%"),"Half day").otherwise("other").alias("duration1")).show()
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "pyspark" }
Cartesian Product in Element Method I'm trying to do proofs using element method, but a few problems popped up with Cartesian products in them. How do these fit in? For example, I know I can break (A $\cap$ B) into $\ [x \in A] \wedge [x \in B]$ How do I work Cartesian products into this? One example problem I'm working on is: $$ (A\times B)-(A\times C) \subset A\times(B-C) $$ Can someone help step me through this? Thank you!
You know that the elements of any Cartesian Products is of form $(x,y)$. Now let $$(x,y)\in(A\times B)-(A\times C)$$ so as $(A-B)=A\cap B'$ so $$(x,y)\in(A\times B),~~(x,y)\notin(A\times C) $$ so $$(x,y)\in(A\times B)\to x\in A,~y\in B$$ and $$(x,y)\notin(A\times C)\to x\in A,~y\notin C$$ These two latter ones mean that $x\in A, y\in B, y\notin C$.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "elementary set theory" }
How can I use a Linux box's display as a third display for my MacBook Pro? At work, I have a MacBook Pro that I use as my primary machine. I also have a RHEL6 box that has a dual-head graphics card. When my KVM is switched to the Mac, the second display that is hooked to the Linux box is not being used. I know there is software the enable other computers to act as displays over a network without an additional physical display connection. Is there software that supports a Linux workstation being the third display for my Mac?
I'm not 100% sure if it'll meet your needs, but Synergy works very well as a software KVM and it supports any mix of OS X, Linux and Windows.
stackexchange-apple
{ "answer_score": 2, "question_score": 4, "tags": "macbook pro, display, unix" }
How can I plot a style like gnuplot's 'with impulses' with matplotlib? I'd like to create a plot like the one below with python/pandas/matplotlib. The upper clip is no problem, but I haven't been able to get a plot like the lower clip to work. I can do it in gnuplot where the equivalent plot style is 'with impulses'. Is this possible with matplotlib? If it is not possible with matplotlib is there another python graphics package that would work? ![The gnuplot style for the lower clip is 'with impulses'](
The easiest way to create such a plot is to use `pyplot.stem`. An example can be found here. import matplotlib.pyplot as plt import numpy as np x = np.linspace(0.1, 6*np.pi, 50) plt.stem(x, np.cos(x)+1, linefmt='g-', markerfmt=' ') plt.stem(x, -np.sin(x)-1, linefmt='r-', markerfmt=' ', basefmt="gray") plt.show() ![enter image description here]( Another option is to use `pyplot.vlines`.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 4, "tags": "python, pandas, matplotlib, plot" }
Save a new row based on existing activerecord object, setting id to nil didn't work I am trying to save 2 rows, the 2nd row based on the 1st row: user = User.new(....) user.save! user.id = nil user.name = "different name" user.save! This doesn't create a 2nd row, what should I do?
The problem is that Rails thinks you're trying to change an instance that is already saved to the database, rather than create a new one. What you want to do is clone the original record, and it should work. Here are the Rails docs on using clone. # First instance user = User.create(...params...) # New instance (no need to set id = nil) user2 = user.clone user2.name = "different name" user2.save!
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "ruby on rails" }
What if I delete a class instance in Blazor? Scenario: 1. I create a new class instance (in my case a Player for a game, including their points this session, their chosen avatar graphic, etc.) 2. I add a reference to a Singleton service (the game server) 3. The player leaves Question: **Would that reference be maintained by Blazor, since it is still active somewhere (the server), or would the creating object, if disposed, take down the reference, leading to a null error in the server?** I've tried just doing it, but the page seems to be maintained even after the user leaves. I'm worried that an untimely garbage collection could lead to null exceptions, but I'm curious if Blazor (C#?) is smart enough not to dispose references that have been passed to other objects.
Is the class instance just a class or a service? If it's just a class then it remains active while it is referenced. As soon as the last reference is destroyed, it's up for garbage collection. In your instance, as long as the singleton service holds a reference, then it remains active.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, blazor" }
Decode Inputsteam with CP1252 encoding in java The Inputstream that i receive from a post request through ExtJS is in CP1252 encoding. How do i decode the Inputsteam so that i can use the json string and convert it to the appropriate java bean. I found out the encoding by using the InputStreamReader's getEncoding() method. ExtJs sends the data in the following format: recordsToSend=%5B%7B%22StartDate%22%3A%222011-03-23T00%3A00%3A00%22%2C%22EndDate%22%3A%222011-03-23T01%3A00%3A00%22%2C%22IsAllDay%22%3Afalse%2C%22CalendarId%22%3A1%2C%22Title%22%3A%22saved%22%7D%5D Need to convert it to: [{"StartDate":"2011-03-23T00:00:00","EndDate":"2011-03-23T01:00:00","IsAllDay":false,"CalendarId":1,"Title":"saved"}]
That's not a character encoding in the normal chars-to-bytes sense. It's some form of escaping. Probably URL escaping. See if java.net.URLDecoder helps. The InputStreamReader.getEncoding() method only tells you the encoding the reader is using to decode the bytes from the underlying input stream, and this is specified at construction time, or set to the platform default if omitted. It doesn't tell you anything about the actual encoding of the characters in the underlying byte stream.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, ajax, encoding, extjs, cp1252" }
restrict the function input to be float32 NumPy array Is there a way to restrict the type of function input in python or I should always convert the input NumPy array to be float 32 array if I want? I am trying to restrict the function input argument type to be a float 32 NumPy array. I have try something like below: import numpy as np def f(input : np.float32): return input*2 However, if I give an int NumPy array, the function is still work and return an int array.
Read more about Python Annotations here PEP3107. Annotations doesn't force the function to accept input as the specified type. Access annotations by, `print(f.__annotations__)` in your case. You can use `yourlist.astype(np.float32)` to force the list argument to be NumPy float32. def f(input : np.float32)-> np.float32: return input.astype(np.float32)*2
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, arrays, numpy, types" }
Splitting the total time (in seconds) and fill the rows of a column value in 1 second frame I have an dataframe look like (start_time and stop_time are in seconds followed by milliseconds) ![enter image description here]( And my Expected output to be like., ![enter image description here]( I dont know how to approach this. forward filling may fill NaN values. But I need the total time seconds to be divided and saved as 1 second frame in accordance with respective labels. I dont have any code snippet to go forward. All i did is saving it in a dataframe as., df = pd.DataFrame(data, columns=['Labels', 'start_time', 'stop_time']) Thank you and I really appreciate the help.
>>> df2 = pd.DataFrame({ >>> "Labels" : df.apply(lambda x:[x.Labels]*(round(x.stop_time)-round(x.start_time)), axis=1).explode(), ... "start_time" : df.apply(lambda x:range(round(x.start_time), round(x.stop_time)), axis=1).explode() ... }) >>> df2['stop_time'] = df2.start_time + 1 >>> df2 Labels start_time stop_time 0 A 0 1 0 A 1 2 0 A 2 3 0 A 3 4 0 A 4 5 0 A 5 6 0 A 6 7 0 A 7 8 0 A 8 9 1 B 9 10 1 B 10 11 1 B 11 12 1 B 12 13 2 C 13 14 2 C 14 15
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, pandas, dataframe, time" }
How to measure the period between the peaks or lows of waves? I want to measure the period between the **peaks/lows of the adjacent waves** shown in the figure. ![enter image description here]( This is an oscillatory behavior of calcium concentration in a cell. The peaks are not the same, hence I would need to **calculate the peak/lows for each wave** , **obtain the corresponding time associated with the peaks/lows** , and **find the difference between adjacent peaks/lows**. I have stored the calcium concentration values for every time "`0.01`". Can anyone suggest me how I should code it? I would prefer to use smaller lines of code.
Look into the inbuilt findpeaks function that can return you the index of peaks in your signal. You could use this to also find the lows in your signal by first squaring your signal. Something like this could work (I haven't tried this in MATLAB so there could possibly be some syntax issues): % Square the signal so that the lows become peaks signal = signal .^ 2; % Get the location of the peaks in terms of t (your time vector) [~, peaksAndLows] = findpeaks(signal,t) % Find the difference between consecutive peaks/lows periodsBetweenPeaksAndLows = diff(peaksAndLows);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "matlab, period" }
What rate should I set taxes at in a medium sized city? I have a city hall with a Department of Finance letting me set the tax rates individually for Residential, Commercial, Industrial and for low, medium and high-wealth individuals. I'm currently at 75% approval so happy and growing - my intuition is that I could tax the poor at a higher rate than the default 9% and get away with it, but seems a bit regressive. What will make me the most money without killing growth?
Along with what mizipzor said, I think you might find this useful: !SimCity Tax Rates As requested by JonathanJ, here's some other Prima guide information:
stackexchange-gaming
{ "answer_score": 5, "question_score": 7, "tags": "simcity 2013" }
Disable switching between different desktops with mouse scroll I just upgraded from 20.04 to 22.04 and so far I am loving the new update. After changing the dock to auto hide I found that when you move your mouse to the left side of the screen and scroll it switches between different desktops. All though this is a nice addition it does not work well with auto-hide dock. Especially when there is a lot of apps on the dock and I have to scroll down to access them I always accidentally move my mouse close to the edge and then instead of scrolling the dock I scroll to a different desktop. You can already change to next desktop quickly by going to activities overview and scrolling so is there anyway to disable the scroll between desktops at the left side of the screen?
As vanadium put in his answer, the extension setting is not exposed in UI. But you can install dconf-editor and change the `scroll-option` to `do-nothing` setting under the `dash-to-dock` extension. Or you can change in command line itself by, gsettings set org.gnome.shell.extensions.dash-to-dock scroll-action 'do-nothing' Thanks!
stackexchange-askubuntu
{ "answer_score": 4, "question_score": 5, "tags": "dock, scrolling, 22.04, multiple desktops" }
Mercurial clients and GitLab? Is there a good way to let both git and hg clients use one repo system, like GitLab? Pretty much like bitbucket. Should we just use <
One (commercial) solution (developed by the same company behind Stack Exchange) is Kiln, which can managed a repo with Git or mercurial. See kiln Harmony. If you use a git hosting service, then you need to manage a conversion system like hg-git yourself.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 11, "tags": "git, mercurial, gitlab" }
How do I log only received information in RealTerm I am trying to test a sensor circuit I'm working on. Essentially, I am using `RealTerm` to send commands to the µcontroller and it is returning the value read by the sensor. When logging to a file in `RealTerm`, I noticed the commands being sent were showing up as well as the data being returned. I was wondering if anyone knew a way to record only the incoming data using `RealTerm`, and not the outgoing commands. Any suggestions would be greatly appreciated. Unfortunately, there is no way around using `RealTerm` specifically because of a company policy.
I just downloaded RealTerm and did some testing: * "Half Duplex" (strangely enough) appears to be the equivalent of "local echo", however that only works to turn off outgoing data for screen display (although see the last item below). * The diagnostic log file seems to capture incoming and outgoing data regardless. If you need to use this method you might look at "Diagnostic Files: Trace and Log", but I don't know if that will help. * With "Direct Capture" enabled, the "Capture" option appears to only capture incoming data and you can include a time stamp if the data from your sensor is terminated with a carriage-return and line-feed. It does not seem to include all the diagnostic data of the log file. * If you only need to capture incoming data, use the "Capture" option and turn off "Direct Capture". This will capture everything that goes to the screen display; therefore to only capture incoming data, un-check "Half Duplex" on the "Display" tab.
stackexchange-electronics
{ "answer_score": 1, "question_score": 1, "tags": "serial" }
Changing div to a different color, wait 3 seconds, before changing color back using jQuery I have a jQuery code that is suppose to make a div blue, and then wait 3 seconds, before making it back to black. But it's just staying at its original color, black, and not changing to blue at all, before changing back to black. What am I doing wrong? <div id = "div" style="width:250px;height:250px; background-color:black;"></div> $(function(){ $("#div").css({"background-color" : "blue"}) .delay(3000) .css({"background-color" : "black"}); }) //end of $(function()) Here's a fiddle: <
Please use `animate()` and also include `jQueryUI` for animating colours. $(function () { $("#div").animate({ "background-color": "blue" }, 1000) .delay(3000) .animate({ "background-color": "black" }, 1000); }); **Fiddle:< Well, if you don't wanna add the whole jQueryUI, you can also add a custom plugin for just animating the colours. $("#block").animate({ backgroundColor: $.Color({ saturation: 0 }) }, 1500 );
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, html, css" }
Reviews: Handling invalid -yet good to be added as comment- edits # The problem I come across a lot of edits where people trying to point out something to the OP. Sometimes it contains useful information that would benefit everyone reading it. Still it is invalid because it radically change the post / modify the code. Mostly they come from new users but what triggered me to start this is that I found similar edits coming from users with 1k+ rep. # Example This edit; the user modified the code and added this warning: > be careful, in case `NAME` is `NULL`, then `anything + NULL` will generate `NULL` # Suggestion: Add reject reason: **Rejected because it is a comment**. This will send the users a notification with a link to redirect them to the post with their edit/comment entered in the comments box to review and post it correctly. # Other examples: This edit
Owners already get notifications about any edits to their post -- both suggested edits and normal edits. The notification persists even if the suggested edit is approved: !enter image description here This ought to do the trick.
stackexchange-meta
{ "answer_score": 1, "question_score": 3, "tags": "discussion, feature request, comments, review, suggested edits" }
Proof of an inverse Matrix I am very raw at proofs, this is only my first semester learning them and I am having trouble with this problem. How would I approach this ? If $$ is an $ × $ matrix that satisfies the equation $ $ is $A^3 -4A^2 +3A -5I_n = 0$, Find the $A^{-1}$
$$A^3 -4A^2 +3A -5I_n = 0$$ Or, $$5I_n = A^3 -4A^2 +3A$$ Pre-multiplying both sides by $A^{-1}$ and dividing by $5$, $$A^{-1} = \frac{1}{5}(A^2 -4A +3I_n)$$
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "matrix equations" }
Show list of users based on taxonomy term (D7) I have a taxonomy vocabulary "Department". In the user account I have a taxonomy term reference field with this vocabulary. So each user can be assigned to one or more departments. I used the module Taxonomy Meny to show the taxonomy terms in my main menu. Now I want to show a list of users when I click on a department in the menu. Does anybody have an idea how I could do this? Thanks.
You're right Mohammed, I should be using views. Use a view with a filter on the department field and then create a link to the view page in my main menu. I was overthinking this way too much.
stackexchange-drupal
{ "answer_score": 0, "question_score": 0, "tags": "7, views, taxonomy terms, users" }
How to split a list into 2 unsorted groupings based on the median I am aiming to sort a list into two subsections that don't need to be sorted. Imagine I have a list of length 10 that has values 0-9 in it. arr = [50, 30, 20, 10, 90, 40, 100, 70, 60, 80] I would want to sort it in a way that indices 0 through 4 contain values 10, 20, 30, 40, and 50 in any ordering. For example: # SPLIT HERE V [40, 30, 20, 50, 10, 70, 60, 80, 90, 100] I've looked into various divide and conquer sorting algorithms, but I'm uncertain which one would be the best to use in this case. My current thought is to use quicksort, but I believe there is a better way to do what I am searching to do since everything does not need to be sorted exactly, but sorted in a "general" sense that all values are on their respective side of the median in any ordering.
to me this seems to do the trick , unless you exactly need the output to be unordered : arr = [50, 30, 20, 10, 90, 40, 100, 70, 60, 80] sorted_arr = sorted(arr) median_index = len(arr)//2 sub_list1, sub_list2 = sorted_arr[:median_index],sorted_arr[median_index:] this outputs : [10, 20, 30, 40, 50] [60, 70, 80, 90, 100]
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, sorting, partitioning" }
Javascript local scoped variable names While using variables internal to a function I often use smaller keywords, e.g.: function (descriptiveParameterArray) { var inArr = descriptiveParameter; var frstVal = inArr[0]; var secVal = inArr[1]; } But some approaches might suggest that var names should be more descriptive. What is the best practice in this regard?
Yes, use descriptive variable names wherever you can, no matter whether you're in a function you consider to be self-contained or not. Maybe a good name for them would be `xCoord` and `yCoord`. Maybe `key` and `value`. Maybe `name` and `age` \- and so on. There's no correct _generic_ answer for what they should be named, just that they _should_ be named descriptively. (The variable name doesn't have to be long as long as there's no ambiguity or vagueness)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript" }
Register your Django router When I use `route.register` without `base_name` like; `route.register(r'codes', SmsCodeViewset)` An error occurred; `AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute.` When I use `route.register(r'codes', SmsCodeViewset, bose_name="")` there is no error, may I ask why?
I was checking my endpoints and I don't have base name in any of them. from app import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'states', views.StateSet) urlpatterns = [ url(r'^', include(router.urls)), ] class StateSet(viewsets.ModelViewSet): queryset = State.objects.all() serializer_class = StateSerializer
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "django, django rest framework, django rest viewsets" }
How can I check to see if a value is a float in javascript I want to check to see if my input is a float. Sooo something like... if (typeof (input) == "float") do something.... What is the proper way to do this?
Try `parseFloat` > The **parseFloat()** function parses an argument ( _converting it to a string first if needed_ ) and returns a floating point number. if(!isNaN(parseFloat(input))) { // is float }
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 3, "tags": "javascript, floating point, typeof" }
Git log pretty format, newline after placeholder if non-empty I've got a git alias for a log using the pretty format: `lg = log -10 --graph --abbrev-commit --pretty=format:'%C(auto)%d%Creset%n %C(bold yellow)%h%Creset - %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'` Which gives the following: ![enter image description here]( I can't seem to find a way to make a new line after the reference names only if the placeholder is non-empty. The pretty formats wiki page has operators to add or remove (+ or -) the newline coming before the placeholder but not after.
This is not supported natively by Git: you would have to process/parse the output to get the right result) But this could also be the opportunity for a simple patch, much like the one which originally introduced the Pretty-format: `%[+-]x` mechanism: commit 9fa708d, git 1.6.6-rc1, Oct. 2009. Maybe `%[*/]x`, for adding line-feed _after_ the expansion of `%x`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 9, "tags": "git, logging, newline, placeholder" }
Android - Hijack clicks In one of my projects i want to collect something like a click heatmap. Is there any way to do this in Android? I was thinking about adding a transparent layout above the original layout and "hijack" clicks there and then pass it to the underlying layout. But I can't figure it out. So, any ideas on how to do this?
i just found the solution myself. It lies in the `onInterceptTouchEvent()` function. You can override it to intercept all touch events before being handed over to the child views. So i created a layout extending FrameLayout. Surrounded my layout with this layout and thats it :)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "android, click, heatmap" }
How to set high resolution on external monitor? I have Samsung Galaxy S3. I connect my phone to 29 inch monitor using HML + HDMI wires. Also I connect it to Apple bluetooth keyboard and magic mouse. I get a very nice experience of Desktop. However S3 has maximum resolution of 1280x720 which does not give a nice look on big monitors. I have following questions: * Can I extend my monitor screen from mobile screen so I can drag and drop apps from one to another? * Can I change resolution of apps running on my monitor to higher than 1280x720. Thanks Note: External monitor does not have touch functionality.
Having a different external display was one of the new features with Jelly Bean 4.2 You will need a siutable update for your S3 to stand a chance. What level of support you will get then is still in doubt depending upon the real hardware capabilities and what support Samsung put in.
stackexchange-android
{ "answer_score": 3, "question_score": 5, "tags": "screen resolution, external display" }
Parallel computing in .NET Since the launch of .NET 4.0 a new term that has got into the limelight is parallel computing. Does parallel computing provide us some benefits or is it just another concept or feature? Further is .NET really going to use it in applications? Further is parallel computing different from parallel programming? Kindly throw some light on the issue in perspective of .NET and some examples would be helpful.
It is not exactly a new term, just a new emphasis. And yes, more programmers will have to create more parallel code if they want to profit from new hardware. See "the free lunch is over" > Further is parallel computing different from parallel programming ? No And here are some samples on MSDN (The PLINQ raytracer is cool)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "c#, .net, parallel processing" }
Does Google store and use data used for googleVis visualisations? I'd like to create some interactive charts using googleVis package in R but I am a bit hesitant as I am not sure if Google will store the data I want to visualize. I have read their terms and conditions [< ] (particularly the 'Content' section) and it seems to suggest that they can but I was never any good at legal jargon. Does visualizing my data through the API mean I submitted 'content' to Google and they can subsequently store and use it? If so, are there any alternatives i.e. r packages that can create interactive dashboards and motion charts?
< Bottom of the page -> Data policy All code and data are processed and rendered in the browser. No data is sent to any server.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r, google api, google visualization, privacy, googlevis" }
How to search & replace within a cell value? I have a cell A and its value is `122abb12`. In another cell B, I want its value to be the value in cell B but all `1` should be replaced by `I` \- value in cell B should be `I22abbI2`. What is the function to use in this case?
I believe you are looking for the Substitute function: =SUBSTITUTE(A1,1,"I")
stackexchange-superuser
{ "answer_score": 5, "question_score": 5, "tags": "microsoft excel, find and replace" }
writing to file: the difference between stream and writer Hi I have a bit of confusion about the stream to use to write in a text file I had seen some example: one use the PrintWriter stream PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fname))); out.println(/*something to write*/); out.close(); this instead use: PrintStream out = new PrintStream(new FileOutputStream(fname)); out.println(/*something to write*/) but which is the difference?both write in a file with the same result?
`PrintWriter` is new as of Java 1.1; it is more capable than the `PrintStream` class. You should use `PrintWriter` instead of `PrintStream` because it uses the default encoding scheme to convert characters to bytes for an underlying `OutputStream`. The constructors for `PrintStream` are deprecated in Java 1.1. In fact, the whole class probably would have been deprecated, except that it would have generated a lot of compilation warnings for code that uses `System.out` and `System.err`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "java, file, stream, writer" }
How to pass Laravel editable settings to Vue I have some settings in my app that can by changed by admin (like categories of products that every user can choose from when creating new product). I'm storing them in database 'settings' table that consists of 'name' and 'value' columns. I also added a Service Provider that adds those settings to config and caches them. I can access them from Laravel easily, but not from frontend (using Vue). Is there any way to access Laravel config values from Vue? I've tried this answer but with no success. Should I make request for settings with every API call?
If your setting is dynamic you must request them each time on a API call. If not you can get those setting once when you deploy your fronted code.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "laravel, vue.js" }
Connect oracle database to another database I am trying to connect oracle db to oracle db I tried to create database link on toad like this. CREATE DATABASE LINK boston CONNECT TO admin IDENTIFIED BY 'mypassword' USING 'host=192.168.1.65 dbname=sales'; It is created with no error but not working properly. I need working "create database link" format with using ip address and service name. Oracle Host to connect ip: 192.168.1.65 oracle version: 10g Service name: xe Table name: sales
You need to provide the proper connection string as follows: CREATE DATABASE LINK boston CONNECT TO admin IDENTIFIED BY mypassword USING '(DESCRIPTION= (ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.65)(PORT=1521)) (CONNECT_DATA=(SERVICE_NAME=sales)) )'; The best practice is to add the connection string in the **tnsnames.ora** SALES = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.1.65)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = sales) ) ) then use this **tns alias** in the `DB link` as following: CREATE DATABASE LINK boston CONNECT TO admin IDENTIFIED BY mypassword USING 'SALES'; Cheers!!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "oracle" }
What is "reload()" for in MongoEngine I have a statement like: `jsonify_ok(data=mytag.reload().as_dict())` What role does reload() play? what's the normal situation for us to use reload()?
`Document.reload()` will check the database and update your data (I think in this case `mytag` but I can't see what this is) with any attributes that have been modified. This could be useful if the data could or has changed before calling `jsonify_ok`. Breaking down your `data=mytag.reload()` this says: "For document `mytag`, go to the database and fetch the latest version of this document, assigning this to variable `data`" Relevant documentation link
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "mongodb, mongoengine" }
Залить фигуру SVG фотографией Фот есть такая SVG фигура, но в ней нет картинки получается только черный фон. <svg xmlns=" xmlns:xlink=" width="387px" height="345px"> <path fill-rule="evenodd" fill="rgb(0, 0, 0)" d="M161.274,11.653 C284.691,-58.441 387.000,207.816 387.000,287.027 C387.000,366.237 248.739,246.359 101.691,329.480 C-13.835,394.783 -17.026,224.521 23.776,148.193 C61.106,78.357 92.468,50.731 161.274,11.653 Z"/> </svg> Нужно сделать по макету вот так ![введите сюда описание изображения]( Как это сделать?
<svg xmlns=" xmlns:xlink=" width="387px" height="345px"> <defs> <clipPath id="cp"> <path fill="rgb(0, 0, 0)" d="M161.274,11.653 C284.691,-58.441 387.000,207.816 387.000,287.027 C387.000,366.237 248.739,246.359 101.691,329.480 C-13.835,394.783 -17.026,224.521 23.776,148.193 C61.106,78.357 92.468,50.731 161.274,11.653 Z"/> </clipPath> </defs> <image x="0" y="0" width="100%" height="100%" href=" clip-path="url(#cp)" preserveAspectRatio="none"/> </svg>
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "html, css, svg, clip path" }
position div to bottom of containing div How can i position a div to the bottom of the containing div? <style> .outside { width: 200px; height: 200px; background-color: #EEE; /*to make it visible*/ } .inside { position: absolute; bottom: 2px; } </style> <div class="outside"> <div class="inside">inside</div> </div> This code puts the text "inside" to the bottom of the page.
.outside { width: 200px; height: 200px; background-color: #EEE; /*to make it visible*/ } Needs to be .outside { position: relative; width: 200px; height: 200px; background-color: #EEE; /*to make it visible*/ } Absolute positioning looks for the nearest relatively positioned parent within the DOM, if one isn't defined it will use the body.
stackexchange-stackoverflow
{ "answer_score": 145, "question_score": 126, "tags": "css, position" }
Oracle SQL: Encountered the symbol "BEGIN" Why is it that I get this error when executing this code? CREATE OR REPLACE PROCEDURE evenorodd(X IN NUMBER) IS BEGIN IF MOD(X,2) = 0 THEN DBMS_OUTPUT.PUT_LINE('even'); ELSE DBMS_OUTPUT.PUT_LINE('odd'); END IF; END; BEGIN evenorodd(15); END; /
You need a `/` at the end of the procedure to terminate the statement and before the PL/SQL anonymous block: CREATE OR REPLACE PROCEDURE evenorodd(X IN NUMBER) IS BEGIN IF MOD(X,2) = 0 THEN DBMS_OUTPUT.PUT_LINE('even'); ELSE DBMS_OUTPUT.PUT_LINE('odd'); END IF; END; / BEGIN evenorodd(15); END; / _db <>fiddle here_
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "oracle, plsql" }
How to return a tuple in Haskell type Record=([Char],[Char],[Char],[Char],[Char]) createAccount::IO()->Record createAccount=do putStrLn "Enter First Name" fname<-getLine putStrLn "Enter Last Name" lname<-getLine putStrLn "Enter State" state<-getLine putStrLn "Enter City" city<-getLine putStrLn "Enter House No." hnum<-getLine let hnumInt = read hnum :: Integer putStrLn "Enter Contact" contact<-getLine return (fname,lname,state,city,contact)
The error message is saying that the type signature for `createAccount` is actually: createAccount :: IO ([Char],[Char],[Char],[Char],[Char]) not `IO() -> Record` as you declared it to be. Options to fix it: * Change the type signature to `IO ([Char],[Char],[Char],[Char],[Char])` (or equivalenly: `IO Record`) * Remove the type signature - you don't need it as Haskell can figure it out.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": -3, "tags": "haskell, tuples" }
javascript download audio/mpeg content from different server with different origin Is it possible to download audio/mpeg content from different server with different origin(like my server is www.a.com and the file is in www.b.com) with javascript on the browser. ps: like download and get 3rd byte of the file
JS doesn't really have any file-based operators, and you'd be running up against the same-origin security policies. You might be able to get the browser to download it by inserting an `<object>` or similar tag into the DOM and have its source be the other server. But then you'd be stuck with a DOM object that wouldn't give you access to the raw bytes of the audio.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, file, html, download" }
Redundancy in the definition of Dedekind domain? > Is there a domain which is noetherian and whose nonzero prime ideals are maximal, but which is not integrally closed? This may be a silly question to experts. I ask because I think I have found proofs for the following implications: 1. Noetherian domain whose nonzero prime ideals are maximal $\implies$ 2. Every fractional ideal is projective/invertible $\implies$ 3. Fractional ideals form an abelian group under multiplication $\implies$ 4. _Integrally closed_ noetherian domain whose nonzero prime ideals are maximal But I can't find an error on first inspection.
Yes, there are such domains: for instance, $\mathbb Z[\sqrt{-3}]$ or $k[X^2,X^3]$. These are not integrally closed, but they are noetherian of dimension one.
stackexchange-math
{ "answer_score": 2, "question_score": 3, "tags": "ring theory, commutative algebra, dedekind domain" }
SQLite Adding a Calculated Column I have a table named "Combined_Bike_Ride" with the below sample data in SQLite started_at | ended_at ---|--- 27/05/2020 10:03 | 27/05/2020 10:16 25/05/2020 10:47 | 25/05/2020 11:05 I want to add a new calculated column "ride_length" where ride_length = (ended_at) - (started_at) in that table. I used the below sql code but getting a syntax error near AS. ALTER TABLE Combined_Bike_Ride ADD COLUMN ride_length AS (ended_at) - (started_at) Am I missing a date calculation? Any help is much appreciated.
First you must change the format of your dates to `YYYY-MM-DD hh:mm` because this is the only text date format that you can use with SQLite's datetime functions if you want to perform operations such as calculation of time difference. For this purpose you can use the function `strftime()`. With `strftime('%s', datetimecolumn)` you get the number of seconds between `1970-01-01 00:00:00` and the value of `datetimecolumn` The correct syntax to add the new column is this: ALTER TABLE Combined_Bike_Ride ADD COLUMN ride_length GENERATED ALWAYS AS ((strftime('%s', ended_at) - strftime('%s', started_at)) / 60)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "sqlite, calculated columns, alter table, calculated field" }
Get path of importing module I have two python files: main.py and imported.py. I want to import imported.py into main.py but I want access to the path of main.py in the file imported.py. That is I want access to the path of the importing module. For example: #main.py import imp imported = imp.load_source('imported', "/absolute/path/to/imported.py") #imported.py pathToImportingModule=os.path.??? doSomethingWithPath(pathToImportingModule)
Solution received in comments from ekhumoro: #main.py import imp imported = imp.load_source('imported', "/absolute/path/to/imported.py") #imported.py pathToImportingModule=os.path.abspath(sys.modules['__main__'].__file__) doSomethingWithPath(pathToImportingModule)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, import, python import" }
Is it better to roll all work into one loop or break it into several loops? I am parsing a folder structure that is quite heavy (in terms of the number of folders and files). I have to go through all the folders and parse any files I come across. The files themselves are small (1000-2000 characters although a few are bigger). I have two options: > 1. Go through all the folders and files and parse any that I come across in one big recursive loop. > 2. Go through all the folders and store the paths of all the files that I come across. The in another loop, parse the files by referring to the stored file paths. > Which option would be better and maybe faster (the speed will most likely be I/O bound so most likely will not make a difference, but I thought I'd ask anyway)?
How about one thread that creates the list of file names to process, and another thread that reads through that list of files and uses one of a handful of worker threads to do the processing? I don't know how many directories there are, but just guessing that's not the big time sink. I'd say you'd get the best performance by having a thread pool, each thread in the pool parsing a file (once you have the list of them.) Because that stuff is gonna be so IO bound, the threading will probably make things far more efficient.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "c++" }
Compare crm id sdk early bound issue I try to compare 2 Guid in Linq to Crm request and it's not working. I don't see why: Guid IdThematique = new Guid(ddlThematique); Sollicitations = Sollicitations.Where(i => i.Sollicitation.SubjectId.Id == IdThematique); This is the catched: > System.NullReferenceException: La référence d'objet n'est pas définie à une instance d'un objet. à XXX dans XXX 74 à System.Linq.Enumerable.WhereListIterator`1.MoveNext() à System.Linq.Buffer`1..ctor(IEnumerable`1 source) à System.Linq.OrderedEnumerable`1.d__0.MoveNext() à System.Linq.Enumerable.CountTSource à xxx dans xxx 200 Thank you
I'll agree with Mario, but I'd make it an extension method: More concise version: public static class EntityReferenceExtensions{ public static Guid GetIdOrDefault(this EntityReference entity){ return (entity ?? new EntityReference()).Id; } } Arguably more readable version: public static class EntityReferenceExtensions{ public static Guid GetIdOrDefault(this EntityReference entity){ if(entity == null){ return Guid.Empty; } else { return entity.Id; } } } But with the extension method, you could handle any Entity Reference of any Entity object (early or late bound) Sollicitations.Where(i => (i.Sollicitation.SubjectId.GetIdOrDefault() == IdThematique)) Although now that I think about it, I don't think that this works for linq to CRM. Just Linq to Objects.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, linq, dynamics crm 2011, guid" }
zero divisors in polynomial Ring $R[x]$ How can I find all zero-divisors in the ring $GF(3)[x]_{x^2 + 2x}$? I know for sure that is a ring and not a field because $x^2+2x$ is reducible. What I tried is to take: if the $gcd(m,n)$ not equal $1$ then you get a zero-divisors. I'm really lost and I don't know how to approce the problem. Is someone that can help me?
Well, the nonzero elements in the quotient ring $\Bbb Z_n$ are either units or zero divisors. The elements $m$ with $gcd(m,n)=1$ are units and the remaining nonzero elements are zero divisors. The same holds for the quotient ring $GF(3)[x]/\langle x(x+2)\rangle$. Those elements which have gcd 1 with $x(x+1)$ are units, the others are zero divisors - bar $0$ which is neither nor. You can list all elements of $GF(3)[x]/\langle x(x+2)\rangle$ and start from there.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "abstract algebra, polynomials, ring theory, field theory, roots" }
gitlab unable to access 'mygitlab.addr' failed connect to 'mygitlab.addr' Protocol not available I created three virtual machines A, B, C. The three virtual machine networks are connected to each other ,can ping pong In A , I created a GitLab private server by docker. I can pull and push in IDEA But In B, I want to `git clone` from A's gitlab server, and the SSH key is generated I have put the public key on the gitlab server. And I configured user Name and user.email. ![git clone](
First, if you use an SSH key, you should use an SSH URL git clone [email protected]:<user>/java_project.git Second, this assumes: * GitLab is on 192.168.56.100 the A machine * GitLab manages (hosts) the java_project.git created under the GitLab user account * GitLab user account SSH setting has the public key from the key pair created on B (which is hopefully what you mean by "I have put the public key on the gitlab server", because adding the public key directly on the A `~git/.ssh/authorized_keys` would not work) You can test from B your SSH connection to GitLab A server with: ssh -Tv [email protected]
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "git, gitlab" }
Can Access generate CREATE TABLE script code like SQL Server can? I have a MS Access file containing hundred of tables, I should create these tables using C# at runtime. So I should generate a script and use that query inside C# to create the tables. Is there a way that MS Access can generate this SQL script automatically? Best regards
No, Access itself cannot automatically create DDL (CREATE TABLE ...) code like SQL Server can. It is entirely possible that some third-party product might be able to scan through an Access database and write DDL statements for each table, but recommendations for such a third-party product would be off-topic on Stack Overflow. Also, as mentioned in the comments to the question, creating an empty database file and then creating each table "from scratch" via DDL is not really necessary for an Access database. Since an Access database is just a file you can distribute your application with a database file that already contains the empty tables (and other database objects as required).
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 5, "tags": "database, ms access, auto generate" }
How can shared references be described? I am trying to understand shared references in the best way and i'm not sure i have fully understood it. My understanding of shared references is when i have a collection and there exists two or more references to that perticular collection in the code, if it is changed in one of those references the other's will not be the same and generate errors, correct? Regards
> if it is changed in one of those references the other's will not be the same and generate errors, correct? Right but partially. if contents of the collection is changed through one reference, other reference will also point to the updated contents. Your other part says, that it will generate errors. well, it depends on logic. class A { public static void main(String[] args) { A a1 = new A(); A a2 = a1; A a3 = a2; } } Here, all the references are pointing to same object. So, if object is modified by `a1`, other reference `a2`, `a3` will also see the modifies state.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "java" }
Is there a way to create an array of an element that contains a specific CSS style? I'm trying to capture the elements that do not contain a display type of none. let pfCard = document.getElementsByClassName("PortfolioCard").style.display = 'block'; This doesn't seem to be working as I believe it is attempting to modify the style type instead of retrieve it.
You can do this by getting all your elements by class name and then using `filter` on that list. const blockElements = [...document.getElementsByClassName("PortfolioCard")].filter(x => x.style.display == "block"); console.log(blockElements.length); <div class="PortfolioCard" style="display:block">block</div> <div class="PortfolioCard">not block</div> <div class="PortfolioCard" style="display:block">block</div>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript" }
How do I add a shortcut to the Show Applications menu in Ubuntu 17? I'm pretty new to Linux in general and I'm curious how the programs I install with `apt` get shortcuts in the Show Applications menu. Additionally, I would like to learn how to add my own application to the menu. Which directory manages the shortcuts in the Applications menu? I'm using Ubuntu 17.10.
I was looking for a solution to do something similar - I installed an app from source and wanted to have it available in the "Show Applications" menu. Found a way to do that by running a grep for the name of one of the applications already shown in that menu. So, The obscure directory you're looking for would be: `/usr/share/applications`. Just have a look at the `*.desktop` files there, choose one that doesn't have too much cruft, copy it to a new `.desktop` file and edit to reflect your app. HTH... One thing that I _don't_ yet know how to do is how to have the "Add to Favorites" option available for it... ps. once I know the solution, by rephrasing the question, I was able to find this thread that gives a few more solutions to a similar question: <
stackexchange-superuser
{ "answer_score": 28, "question_score": 23, "tags": "linux, ubuntu, filesystems, user interface" }
Camera manipulation Recently, I've been thinking about working on a mini-project, which is to change the live camera feed. For example, if you go into Skype, the camera records what's in front of it, before sending the input to Skype. Is it possible, to somewhat change the input with Python? This may be impossible or relatively easy, but I'm new to Python, and any help would be appreciated. .
You want to manipulate live video before passing it to the actual target. **Yes it is possible** and can be classified in the category of deepfake. I would recommend you to analyze the code base for faceit_live and reverse engineer it, to know more about how it can be done.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python" }
ld: duplicate symbol on osX machine [libpmk] I'm try to compiling the libpmk library < following the documentation here < . I'm running on osx and after the "make libpmk" i've got this error: > ld: duplicate symbol __ZN6libpmk10SparseTreeINS_3BinEE4rootEv in pyramids/pyramid-maker.o and histograms/multi-resolution-histogram.o for inferred architecture x86_64 Does anybody know how to solve this? I tried to compile on Ubuntu and it works!
I got it to compile, though I haven't had a chance to test it all out yet. Removing or commenting out the following lines (files are under the libpmk directory): clustering/hierarchical-clusterer.h:27: template class Tree<PointTreeNode>; histograms/multi-resolution-histogram.h:18: template class SparseTree<Bin>; should fix the problem and allow it to compile. These line numbers are for v2.5.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, compilation, duplicates, ld" }
Practical Implementations of QECCs in IBM Q Experience I am learning how to program the IBM Q Experience quantum computers in order to learn more about how does it work and in order to perform some experiments in it. By doing so I was wondering what are the most advanced things that have been done in such computers that actually are an advance for quantum technologies. More specfically, I am interested in what have been done in quantum error correction code implementation and testing in those, and if some papers about those implementations and techniques used are available.
The publicly available IBM devices don't yet have the connectivity to realize quantum error correcting codes that both detect and correct a full set of quantum errors. But we can certainly do proof-of-principle experiments on the tools and techniques required. Here are the experiments I know of **Error correction experiments done (or doable) on a 5 qubit device:** * Detecting arbitrary quantum errors via stabilizer measurements on a sublattice of the surface code * Is error detection helpful on IBM 5Q chips? * Experimental demonstration of fault-tolerant state preparation with superconducting qubits * Protecting quantum memories using coherent parity check codes **Error correction experiments on the 16 qubit device.** * A repetition code of 15 qubits Disclosure: The last one is mine.
stackexchange-quantumcomputing
{ "answer_score": 4, "question_score": 8, "tags": "error correction, resource request, ibm q experience" }
How to ping a pc through an ICS I'm trying to ping a PC that is connected to the network through an ICS. For example, I'm trying to ping PC02 from PC03. How would I do that? And is this even possible? PC01(192.168.178.2)---ICS---PC02(192.168.137.85) | | PC03(192.168.178.3) | | R0/DHCP | | internet
Nope. I'm pretty sure you cannot ping the PC02 from PC03. This is because PC01 and PC02 form one local network and PC01 and PC03 form another local network. So actually, PC02 and PC03 are not part of the same network. This can also be seen by checking the 3rd number in it's IP. Also, if you go to PC01 and check it's local IP, it'll actually have 2 local IPs. So in short, no, I don't think it's possible to ping the PC02 from PC03
stackexchange-superuser
{ "answer_score": 0, "question_score": 1, "tags": "networking, ping, ics" }
Kubernetes deployment multiple replicas - how to pass replica number to pod A new Kubernetes Deployment with 2+ replicas for high availability. I want to be able to execute a command on the first pod only, let's say create a DB, and let the other replicas wait for the first one to complete. To implement this, I just want to know in the pod if this is replica #1 or not. So in the pod's entry point I can test: if [ $REPLICA_ID -eq 1 ]; then CreateDB else WaitForDB fi Can this be done in Kubernetes?
in Kubernetes a `Deployment` is considered stateless and therefore doesn't provide the feature you're looking for. You should rather look into `StatefulSet` and their features. A `StatefulSet`e.g. supports ordered creation and when combined with the generally available `readinessProbe` for you pods you could create the desired behaviour. Also the pod name is stable within a `StatefulSet` so your test could then be done with the `hostname` of the `Pod`.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "kubernetes" }
jquery Form validation for Housenumber How to validate the below Housenumber using jquery Form validation? 1 1b 12 12b 123 123b 1234 1234b the letter should be always last position , but not required. Please help me to create regular expression.
The following RegExp will do: /^\d+[a-zA-Z]*$/ * `^` _Must start with_ * `\d+` _Any number_ (`\d`), _at least once_ (`+`) * `[a-zA-Z]*` Some letters `[a-zA-Z]` (optional: `*`) * `$` _Must end here_
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 4, "tags": "jquery, regex" }
How do I make a Quartz job wait for another task that is fired by ApplicationListener? So, I have a Quartz job, and an ApplicationListener that gets fired when the Quartz job is done. My problem is that any finalization that I do in the listener will create a race condition for the code that polls to check if the Quartz job is done. Basically I want either make the Quartz job wait for the ApplicationListener to start and finish before considering itself done. Is this even possible? Am I mixing frameworks?
Turns out my issue was lack of familiarity with the code base. Everything was wired correctly, but I used the wrong JobKey to search for listeners before allowing the main job to shut down. Sorry to waste your time guys.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "spring, quartz scheduler" }
Why did Kai believe that Oogway betrayed him in Kung Fu Panda 3? In Kung Fu Panda 3, when we learn the history between Kai and Oogway, we see that they used to be brother in arms and when the later was seriously injured, Kai took him to the secret Panda village where the Pandas taught Oogway how to give chi. Kai wanted the power for himself and they fought, Oogway won and banished Kai in the spirit realm. But later into the movie, Kai says that it was Oogway that betrayed him. Why did Kai say that? Did Oogway actually betray him?
Because when Kai was trying to Destroy the Pandas & the panda village, Oogway took the side of Pandas to protect them. Oogway took the right side. So, while kai was like a Brother to Oogway, the latter chose to fight Against Kai even he Helps Oogway So much. That's why kai said to betray you betrayed me.
stackexchange-movies
{ "answer_score": 1, "question_score": 2, "tags": "plot explanation, kung fu panda 3" }
Is there a program to show which folders on my hard drive take up the most space? I have about 2/119 GB left on my SSD and was wondering if there's a good way to get an overview of which folders contain the largest files so I can move it over to my HDD. Win7.
I always use the program 'treesize free'. Does the job perfectly. !enter image description here
stackexchange-superuser
{ "answer_score": 2, "question_score": 0, "tags": "windows 7" }
Set Color for individual Treeview items based on data not bound to the treeview WPF I am trying to figure out the best way to approach this. I have a treeview that is using Hierarchal data from sql server tables. Using linq to generate the dbml and then binding the data to the treeview. Here is the part I am having trouble with. Say the treeview starts and goes Categories----->Authors----->Books------>CheckedOut So If I wanted to color each item(red) and all the parent nodes(red) where the item is overdue based on a view I created in sql server (I have four different categories to highlight based on dates stored in the db) what would be the best approach for this in C# WPF?
you can use a style trigger to trigger action when item in your tree view item meets certain condition <Style TargetType="TextBlock"> <Style.Triggers> <DataTrigger Binding="{Binding Highlight}" Value="True"> <Setter Property="Background" Value="youcolor" /> </DataTrigger> </Style.Triggers>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, wpf, treeview, hierarchicaldatatemplate" }
XElement.Descendants doesn't work with namespace I have a simple XML, <S xmlns=\" I want to find all "H" nodes. XElement x = XElement.Parse("<S xmlns=\" IEnumerable<XElement> h = x.Descendants("H"); if (h != null) { } But this code doesn't work. When I remove the namespace from S tag, the code works correctly.
Your element has a namespace because `xmlns` effectively sets the _default_ namespace for that element and its descendants. Try this instead: XNamespace ns = " IEnumerable<XElement> h = x.Descendants(ns + "H"); Note that `Descendants` will _never_ return null, so the condition at the end of your code is pointless. If you want to find _all_ `H` elements regardless of namespace, you could use: var h = x.Descendants().Where(e => e.Name.LocalName == "H");
stackexchange-stackoverflow
{ "answer_score": 53, "question_score": 19, "tags": "namespaces, xelement" }
Phase plot of a system of differential equations using Matlab Assume the system: \begin{align} \begin{pmatrix} x \\\ y \\\ \end{pmatrix}' &= \begin{pmatrix} 7x+10y+3 \\\ -5x-7y+1 \\\ \end{pmatrix} \end{align} By changing the variables so that $(0,0)$ is the equilibrium point, the system transforms to: \begin{align} \begin{pmatrix} x_1 \\\ x_2 \\\ \end{pmatrix}' &= \begin{pmatrix} 7x_1+10x_2\\\ -5x_1-7x_2 \\\ \end{pmatrix} = A \cdot \begin{pmatrix} x_1\\\ x_2\\\ \end{pmatrix} \end{align} After that, all we have to do in order to determine the equilibrium point's type and stability is to examine $A$'s eigenvalues. Now, I would like to plot this system's solutions and its behavior near the equilibrium point using **Matlab**. Do I have to use the **ode45** command to solve the system and then graph its solutions or is there a quicker way to obtain the phase plot? Could someone provide me with the code which does that?
You can use quiver for this [x1, x2] = meshgrid(-1.0 : 0.2 : 1.0, -1.5 : 0.2 : 1.5); u = 7 * x1 + 10 * x2; v = -5 * x1 - 7 * x2; figure quiver(x1, y1, u, v) From this representation you can see that solution will circle around $(x_1, x_2) = (0, 0)$, clockwise ![enter image description here](
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "ordinary differential equations, graphing functions, matlab" }
How can I access the root element of a geb module I want to test that a double click on a list item in my page opens the corresponding item for editing. Here's the structure of my page: <ul class="list"> <li class="item" ondblclick="jQuery(this).find('.edit-button').click();"> ...some content... </li> </ul> I have the following geb page defining the items using a geb `moduleList` of `ListItem` modules: class ListPage extends Page { static content = { items { moduleList ListItem, $("li.item") } } ... } In the `ListItem` module I want to access the root `li` element to trigger the double click on it. How can I access the `li` in the `ListItem` module? The correct jQuery selector would probably be `$(this)` but in the module `this` point to the module instance and not to the root element.
After posting my question I recognized a related question providing the answer. `$()` refers to the root element of a geb module.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "jquery, geb" }
Merge two models - Keras I was reading through many blogs and understood the relevance and scenario of having merging two model. But, how to decide the Merge mode for two models. ie. concat, sum, dot, etc. For eg. I am working on the task of Auto Image captioning. So, captions and Images are 2 kinds of input that I need to handle and merge them at certain point for model to let know which caption is for which image. I am learning the text representation and Image representation by 2 different network designs. Now, at the state after learning representation for both the inputs, how do i decide what ways(concat, add, etc) to use to join/merge two representations.
Generally, I'd say its the same way as finding your "best" feature list, pre-processing methods and algorithm - you'd find most answers starting with "give it a try and compare", "check which combination gives you a better cross-validation?" etc.. More specifically, when there is no farther documentation (and its an open source project) I usually take a look at the code for more intuitions. In this case concat, dot, average and the like where strait forward implemented as it sounds (concatenating date, averaging, etc..), but it does imply about the amount of processing needed: some of the merging functions **adds** to the input needed to be processed (concat, add) and some **reduces** it like an aggregation function (average, min, max) Beyond that the resulted tensor object will perform a bit different for different datasets. Please give it a try and let us know what merging combination worked best for you, and the dataset type :)
stackexchange-datascience
{ "answer_score": 0, "question_score": 1, "tags": "neural network, deep learning, keras" }
How do you parse Trump's Tweet? Trump recently tweeted: > ...peace treaty with Israel. **We have taken Jerusalem, the toughest part of the negotiation, off the table, but Israel, for that, would have had to pay more.** But with the Palestinians no longer willing to talk peace, why should we make any of these massive future payments to them? How do you parse the sentence in bold? "We have taken... but Israel for that..." seem to be contradictory. Or perhaps there's a 'would' missing before the first have?
The phrase is ambiguous (surprise surprise). There are two units of information being presented here: 1. We have taken Jerusalem, the toughest part of the negotiation, off the table, 2. but Israel, for that, would have had to pay more. In the first instance Trump is asserting that Jerusalem is no longer open for discussion (it has been removed from the table), this is something that America wanted. However Israel is still on the table, meaning it is still open for discussion. The concessions required of America to take Israel off the table, were too expensive. An alternative reading could be: 1. Jerusalem is no longer up for discussion, we have removed it from the table. 2. If Israel wanted to achieve this same outcome, it would have cost them more than America had to concede.
stackexchange-english
{ "answer_score": -1, "question_score": 1, "tags": "grammaticality, syntactic analysis, trumpism" }
Return the range within an array Excel I need to retrieve a range delimited by indexes from a specific array I cannot use OFFSET because it doesnt use an array as a parameter. And the range will then be use for a secondary calculation The example: ![example data]( I want to calculate the SUM of the 4th to the 11th value in the column Numbers. So at the end the formula should look something like: `=SUM(Numbers[4:10]) = 36 ` 4 and 10 being the desired indexes. I tried with OFFSET and INDEX but cant figure out how to do it.
Use INDEX and SEQUENCE: =SUM(INDEX(FILTER(Numbers,Numbers<>0),SEQUENCE(8)+3))
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "arrays, excel, indexing, excel formula, range" }
How to get IP address of hostname inside jinja template Our saltstack is based on hostnames (webN. _, dbN._ , etc.). But for various things I need IPs of those servers. For now I had them stored in pillars, but the number of places I need to sync grows. I tried to use publish + network.ip_addrs, but that kinda sucks, because it needs to do the whole salt-roundtrip just to resolve a hostname. Also it's dependent on the minions responding. Therefore I'm looking for a **way to resolve hostname to IP in templates**. I assume that I could write a module for it somehow, but my python skills are very limited.
You could use a custom grain. Create file _grains/fqdn_ip.py in the state tree directory: import socket def fqdn_ip(): return { 'fqdn_ip': socket.gethostbyname(socket.getfqdn()) } In template: {{ grains.fqdn_ip }} Another way is use dnsutil module (requires dig command on minion): {{ salt'dnsutil.A'[0] }}
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 12, "tags": "python, jinja2, salt stack" }
Reset input field's value with a ref? I have a reference (created with `useRef()` ) that points to an input field, but when the user presses on "space" once, i get the following in my ref: <input autocomplete="off" type="search" aria-expanded="false" aria-haspopup="true" placeholder="Unit" title=" " value=" "> Which means that the input field's placeholder doesn't show.. How can i detect if there's just one space entered, and if there is, reset the field to the following? (so that the placeholder shows) <input autocomplete="off" type="search" aria-expanded="false" aria-haspopup="true" placeholder="Unit" title value>
You could e.g. prevent user from entering a whitespace and the beginning of the input. value={value.replace(/^\s+/, '')} ' some text' --> 'some text' ' ' --> ''
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "reactjs, jsx" }
Is there a CONCAT_WS method in JPQL? I am wondering if there is something like the `CONCAT_WS` method in `JPQL` as I found it in the `MYSQL documentation` here: < Anyone ever stumbled over anything comparable?
No, there is not. JPQL does have following String functions: CONCAT, LENGTH, LOWER, SUBSTRING, TRIM, and UPPER. Only way in with older JPQL versions is to simply repeat separator between each value in CONCAT: SELECT CONCAT(se.string1, ';', se.string2) FROM SomeEntity se With JPQL in the JPA 2.1 specification implementations it is possible to call database functions as follows (first arguments is name of the function, others are arguments to function): SELECT FUNCTION('CONCAT_WS', ';', se.string1, se.string2) FROM SomeEntity se Older EclipseLink versions have same functionality via `FUNC` keyword.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "mysql, sql, jpql, concatenation, concat ws" }