INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
What does "he" in "he back" refer to? In _Harry Potter and the Deathly Hallows Part 1_ (2010), Harry says to Ron, who was upset about Harry being closer to Hermoine: > Harry: What part of this isn't living up to your expectations? Did you think we were gonna he staying in a hotel? Finding a Horcrux every other day? Thought you'd **he** back by Christmas? What does "he" in "he back" refer to?
It looks like a typo. The text should probably read: > Well then, I'm sorry, but I don't quite understand. What part of this isn't living up to your expectations? Did you think we were gonna be staying in a five-star hotel? Finding a Horcrux every other day? You thought you'd be back with your mum by Christmas?
stackexchange-scifi
{ "answer_score": 5, "question_score": -9, "tags": "harry potter" }
Define one-off Typescript interfaces I've been using React for a while and I'm starting to incorporate Typescript into it. In my previous projects, I was used to creating large "container" objects like this: const theme = { colors: { primary: '#00f', accent: '#f70', }, sizes: { base: '16px', }, }; How could I define a type for such an object? It seems awkward that I have to define the interface by typing (pardon the pun) every single member of it, then repeat it all over to assign the values: interface ThemeType { colors: ThemeColors, sizes: ThemeSizes } interface ThemeColors { primary: string, accent: string } interface ThemeSizes { base: string } const theme : ThemeType = { // ... }; Is there another way to do it? At least a more compact way?
Just declare the constant with no type annotation; its type will be inferred as: { colors: { primary: string; accent: string; }; sizes: { base: string; }; } If you need to use its type as an annotation elsewhere, you can write: type ThemeType = typeof theme Then you can use `ThemeType` as an alias for the above type. If you want to refer to the types of the nested objects, they are `ThemeType['colors']` and `ThemeType['sizes']`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "typescript" }
placement new with memory pools I've recently read about placement new and i would like to use it in one of my assignments. I am not allowed to use the stl containers so i would like to make a vector like container. So lets say i preallocate 10 slots in an array to store my objects and then the user adds 11 items. How could i use placement new to store the first 10 objects just by copying them into the array and then initialize a new object and add it into the vector? The current code i am using for the extra allocation space is this: template <class T> void Vector<T>::allocMem(int objects) { T *_new_data = new T[2*capacity]; for(int i = 0; i < size(); i++) { _new_data[i] = _data[i]; } delete [] _data; _data = _new_data; capacity = 2*capacity; } And in the place of that i would like to add the use of placement new.
T *_new_data = (T*)new char[sizeof(T)*2*capacity]; for(int i = 0; i < size(); i++) { new (_new_data + i) T(_data[i]); } See also C++ placement new
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++" }
Sending email programatically using the DEFAULT app I am developing an app that send programatically an email, Im using stoxk LG mail Intent i = new Intent(Intent.ACTION_SEND); i.setType("message/rfc822"); i.putExtra(Intent.EXTRA_EMAIL , new String[]{XXXXXXX}); i.putExtra(Intent.EXTRA_SUBJECT, "XXXXXXXXXX"); i.putExtra(Intent.EXTRA_TEXT , (" XXXXXXXX")); try { startActivity(Intent.createChooser(i, "Sending mail...")); } catch (android.content.ActivityNotFoundException ex) { Toast toast = Toast.makeText(getApplicationContext(), "Not found ", Toast.LENGTH_LONG); toast.show(); finish(); } It opens the LG mail and pastes the SUBJECT, the TEXT and the MAIL BUT it doesn't send it , how can I achieve it? Anny suggestion will be apreciated!
With intent you can't do this. But look at the link, there is an answer for your question. Sending Email in Android using JavaMail API without using the default android app(Builtin Email application)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, email, default, send" }
background property on div issue I want this markup: <div style="background:url('Untitled.jpg');height:50px;width:50px;"></div> to behave as this markup: <img src="untitled.jpg" width="50" height="50"/> The difference between the 2 is that the div doesn't fit the full image. It just crops it if the full image can't be fit inside the container. However img tag as we know shows full image. It scales down the image but shows it fully. How can I achieve the same thing in div in background property of css? If possible, please do not suggest css3 because I need this to work on IE8. However it's fine. You can still suggest.
You'll have to reset the div completely: <div style="border: 0; margin: 0; padding: 0; background: url('Untitled.jpg'); background-size: 100%; width: 50px; height: 50px;"></div>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html" }
Trying to understand readable streams in node.js In my `module.js` I have var Stream = require('stream'); module.exports = function () { var stream = new Stream(); stream.readable = true; stream.emit('data', 'some stuff') stream.emit('end') return stream; } and in my `index.js` var module = require('./module') module().pipe(process.stdout) substack's example from the stream handbook is working just fine. Why doesn't my code show anything in the command line?
Because you are emitting data before calling `pipe`, and 'data' listener is attached after first 'data' event is fired EventEmitter's calls are synchronous (as almost everything else non-IO in node.js) A bit simplified version of stream.emit('data', 'some stuff') stream.pipe(process.stdout) without EventEmitter could be rewritten as stream.listeners = []; // 'emit' call var ondata = stream.listeners.data; if (ondata) { // only one listener case in the example ondata('some stuff'); } // 'pipe' call stream.listeners.data = function(buff) { process.write(buff); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "node.js" }
Hadoop -mkdir : - Could not create the Java Virtual Machine I have configured the Hadoop 1.0.4 and started the following without any issue: 1. $ start-dfs.sh : -Works fine 2. $ start-mapred.sh : - Work fine 3. $ jps (Output is below) **Out put:** rahul@rahul-Inspiron-N4010:/usr/local/hadoop-1.0.4/bin$ jps 6964 DataNode 7147 SecondaryNameNode 6808 NameNode 7836 Jps 7254 JobTracker 7418 TaskTracker **But facing issue:** While issuing command rahul@rahul-Inspiron-N4010:/usr/local/hadoop-1.0.4/bin$ hadoop -mkdir /user Getting following error Unrecognized option: -mkdir Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit. I applied the patch : **HDFS-1943.patch** but not use full
Should be: `hdfs dfs -mkdir /user` Consult documentation at <
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "hadoop, hdfs" }
OCaml - Modify array values I want to modify an existing array with this function but for a reason I don't understand once I apply the function to the array the values do not change. What am i missing ? Thanks in advance let test v (a,b) = for i=a to b do if ((Array.get v i)>(Array.get v i+1)) then let tmp = (Array.get v i) in v.(i)<-(Array.get v i+1); v.(i+1)<-tmp; done;;
The error is in Array.get v i+1 : this infers that v is an int array, and that you add 1 and make the condition always false. Just put i+1 in parenthesis : v will be an array of any type, and it will solve your issue. let test v (a,b) = for i=a to b do if Array.get v i > Array.get v (i+1) then let tmp = (Array.get v i) in v.(i)<-(Array.get v (i+1)); v.(i+1)<-tmp; done;; You could have written using v.(i) > v.(i+1).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "arrays, ocaml" }
Angular 6 rxjs 6 return Observable nested element I would like to return a child element of an observable as this. Say I have a HttpClient that gets an observable of people: export class People{ public Name: string; } and a service that gets a single one as abservable: public get(id: number): Observable<People> { return this.http.get<People>(' + "people/" + id); } Now I would like to get the name from my observable as observable: public get(id: number): Observable<string>{ this.peopleService.get(id) .... ? } How could this be done?
You can use map() function to transform people observable: const nameObservable = this.peopleService.get(id).pipe( map(people => people.name) );
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "angular, observable, rxjs6" }
Homotopy equivalence between $M$ and $M-\partial M$ One of my professors assigned this problem last semester and I recently looked back at it and am still a bit confused. Let $M$ be a topological n manifold with boundary, which means, a second-countable, Hausdorff space such that for every $x \in M$, there is a neighborhood $U \ni x$ which is homeomorphic to either $\mathbb{R}^{n}$ or $\mathbb{R}^{n-1} \times [0,\infty)$. Also, assume that $\partial M$ has countable many components. We have to prove that the inclusion $i : M - \partial M \to M$ is a homotopy equivalence. I guess if one assumes compactness, you can use the Proposition 3.42 of Hatcher to get a collar neighborhood of $\delta M$ but I am not sure how to proceed from there, if this approach even works.
Once you have a collar neighborhood $N(\partial M) \approx \partial M \times [0,1)$ in your hands, you have to guess how to use it to define a homotopy inverse $g : M \to M - \partial M$. But that's pretty natural. First let $k : [0,1) \to [.5,1)$ be a homeomorphism which is constant on $[.75,1)$. Outside of the collar neighborhood define $g$ to be the identity. Inside the collar neighborhood, define $g$ to be the composition the map $$\partial M \times [0,1) \xrightarrow{\text{Id} \times k} \partial M \times [.5,1) \hookrightarrow \partial M \times (0,1) $$ And finally you have to prove that the map $g : M \to M-\partial M$ is homotopic to the identity. But again that's done in pretty much the same way, starting with a homotopy from the composition $$[0,1) \xrightarrow{k} [.5,1) \hookrightarrow [0,1) $$ to the identity in such a way that the homotopy is stationary on $[.75,1)$.
stackexchange-math
{ "answer_score": 4, "question_score": 5, "tags": "algebraic topology, differential topology, homotopy theory, manifolds with boundary" }
Possible ways to format a specific century in LaTeX? I'm writing I little bit of history in my report and I wonder which are the possible ways to format a century in LaTeX (e.g XX century) and in typography which is the most used and accepted. This is actually what I'm using: `XX$^{\circ}$` so I have something like XX° but I don't like it very much, the circle is too low...
The ordinal indicators º/`º` and ª/`ª` can be typeset with `\textsuperscript{o}` and `\textsuperscript{a}` respectively. While the `french` option of `babel` actually uses a `\realsuperscript` macro that aligns the superscripts a little bit lower, the `italian` option doesn’t have this. An alternative offers the input of Unicode characters with the `utf8` option of the `inputenc` package (of course, you need to have your documents UTF-8 encoded). The `textcomp` packages defines `\textordmasculine` and `\textordfeminine` which do look a little different and are underlined. ## Code \documentclass{article} \usepackage[utf8]{inputenc} \usepackage[italian]{babel} \let\up\textsuperscript \begin{document} 20\up{o} secolo\par 20º secolo \par 20\up{a} Vespa\par 20ª Vespa \end{document} ## Output !enter image description here
stackexchange-tex
{ "answer_score": 9, "question_score": 11, "tags": "typography, datetime" }
Replacing Middle Part of String Occurring Multiple Times I have a file, that has variations of this line multiple times: `source = "git:: I am passing through a tag name in a variable. I want to find every line that starts with `source` and update that line in the file to be `source = "git:: This should be able to be done with awk and sed, but having some difficulty making it work. Any help would be much appreciated! Best, Keren Edit: In this scenario, the it says "develop", but it could also be set to "feature/test1" or "0.0.1" as well. Edit2: The line with "source" is also indented by three or four spaces.
This should do: sed 's/^\([[:blank:]]*source.*[?]ref=\)[^"]*\("\)/\1'"$TAG"'\2/' file
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "bash, awk, sed" }
Are Turkey's customs fees for international mail high? I had someone send me a valuable but small item from my old home in the States, to Turkey. I had them insure it for $1000 and the postage cost them $50. When it arrived today in Turkey, PTT (mail carrier) asked for $200 in customs fees. Is this typical for international mail? I haven't had this problem in other countries.
This is absolutely normal. Every country has a maximum amount allowed to be received in a country without the customs duty. The amount you have listed obviously exceeded that amount. And when you mail at least from the US your declared value of the merchandise/gift has to match the amount you're insuring the parcel for. So since your amount exceeded maximum allowed import duty free you will pay whatever duty is imposed and any fines or penalties that laws will allow. So 20% import duty is quite normal. You can look at Borderlinx for the information on the maximum amount (though information for Russia is no longer accurate).
stackexchange-expatriates
{ "answer_score": 5, "question_score": 1, "tags": "turkey, customs, postal system, imports" }
QGIS print composer: Transparency in legend symbols Is there a way to make the legend in the QGIS (v2.0.1) print composer reflect the same degree of transparency as set in the Style box in the main window? The legend symbol colours are shown with no transparency but these look very different to the transparent colours on the map... Doing a search of this question on a different website I found the following answer: "There are two transparency sliders in the style dialog. Altering the big one at the top doesn't affect the transparency of the legend symbol or the style preview in the dialog, but the small transparency slider below the size unit selector does." However, I only see one transparency slider in the style dialog. Or am I looking in the wrong place? Any ideas? Thanks!
!Layer Transparency versus Symbol TransparencyYou can set transprency at two levels, the "Layer Transparency" and/or the "Symbol Layers". Selecting Style in the Layer Properties you should see Layer Transparency under the Style heading on the right. This affects the layer but does not affect the symbol in the legend. (Long transparency slider and box) Selecting Style and going to the Symbol Fill properties you should have access to another level of transparency. This will affect layer fill transparency for the selected symbol and will show up in the legend. (Transparency Slider only, assuing Single Symbol mode)
stackexchange-gis
{ "answer_score": 7, "question_score": 5, "tags": "qgis, legend" }
Best Framework for building Social Networking sites with twitter like security I am looking for framework for building social networking site. Features: 1) Users can make tweets. Tweets or messages should be available according to security settings such as if user selects only to friend then those tweets should be for only friends. (or) Instead of tweets and messages I should say security like public, private, only to friends should be provided. 2) Profile , images, videos should be displayed as per security constraints(only to friends or public). I found Elgg is best voted in stackoverflow. But I don't know if Elgg provides such kind of features. Does Elgg framework provides Features mentioned above? (or) You would suggest any other best framework with such kind of features. Please give suggestions.
Elgg has most of the features you need. The wire plugin coming with elgg package lets you create the tweet like system.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "social networking" }
Including a GPL-licensed library through a CDN I'm planning to use Flickity in my MIT-licensed open-source JavaScript project. The license for open-source usage is GPL. Can I link the file via a CDN into my project, or is this considered a "derivative work?"
By calling into the Flickity library from your project, you are creating a derived work as far as the GPL is concerned. However, this does not mean that your code must be under the GPL license as well. Your code must be under a license that is compatible with the GPL (which the MIT license is) and people who make changes to your code have to comply to the rules of the GPL license. This means effectively that it is not allowed to make a closed-source (derived) version of your project without removing the dependency on Flickity.
stackexchange-softwareengineering
{ "answer_score": 3, "question_score": 0, "tags": "javascript, licensing, gpl, mit license" }
Оператор сравнения NOT IN Допутим я хочу вывести новости из БД но не учитывая определенных пользователей. Пример: SELECT news FROM posts WHERE id NOT IN (4,6,7...6000); Вот в чем заключается вопрос, какова максимальная длинна выражения в скобках? и как это будет сказываться на производительности БД? P.S. пример выдуманный, и новости нужных пользователей я знаю как по другому вывести, мне нужно понять все насчет оператора
Длина выражения в скобках не имеет значения. Имеет значение длина запроса в целом. Длина запроса задается настройкой max_allowed_packet в конфиге.
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "php, mysql" }
Assignment statement stored in a variable causes command not found error in Bash For example: #!/bin/bash sss='ls -l' $sss ttt='a=100' $ttt The output of `ls` is correct, however, the assignment statement will output an error message: > line 5: a=100: command not found Why the difference? If assignment is not command, what is it? I mean what is the difference between explicit `a=100` and `a=100` expanded from variable, I mean, the bash sees the same thing `a=100`, right? Why they got different interpretation?
That's because the output from variable expansion is run as a command, precisely get replaced in the command line as if you have inserted the content literally. Here, you have `ttt='a=100'`, so when you do `$ttt` next, it will be simple expanded as `a=100` and as this would be the command to run being the only parameter present. And the error is due to the obvious fact that this is not a valid command. You can tack the expansion with some actual-valid command to get the expansion as that command's argument (e.g. `echo $ttt`), as you can imagine. * * * If you ever need to do assignments like that, leverage `declare`: $ ttt='a=100' $ declare "$ttt" $ echo "$a" 100
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "bash" }
IDA Pro variable declaration I'm quite new to x86 assembly and reverse engineering and have a question about this piece of code I obtained through IDA: ; LRESULT __stdcall WndProc(HWND, UINT, WPARAM, LPARAM, UINT_PTR, DWORD_PTR) WndProc proc near Rect= tagRECT ptr -34h var_24= dword ptr -24h var_20= dword ptr -20h var_1C= dword ptr -1Ch var_18= dword ptr -18h prc= RECT ptr -14h var_4= dword ptr -4 hWnd= dword ptr 8 uMsg= dword ptr 0Ch wParam= dword ptr 10h lParam= dword ptr 14h Am I correct that var_18, var_1C and var_20 are actually pointing to prc.top, prc.right and prc.bottom?
No; if `prc` is a `RECT` instance then it occupies the _following_ 16 bytes of memory (so offset -14 through -5 inclusive, four 32-bit words).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "assembly, reverse engineering, ida" }
Undefined Variable even if I passed it already I'm getting Undefined Variable error. Here is my controller: Controller: public function index() { /**$englishgrades = StudentHistory::select('date', 'student_id', 'grade') ->where('subject', 'English') ->groupBy('student_id') ->orderBy('date','desc') ->first() ->get(); */ $englishgrades = StudentHistory::where('subject', 'English') ->get(); $englishgrades = []; return view('home', $englishgrades); } I'm calling it to my blade using {{ $englishgrades }} > Undefined variable: englishgrades (View: /home/vagrant/Code/projects/DYK/resources/views/home.blade.php)
you should use compact $englishgrades = StudentHistory::where('subject', 'English') ->get(); $englishgrades = []; // remove this so it will not overwrite the above declaration .. return view('home', compact('englishgrades')); > it will return an empty array since you're overwriting the original value ..
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, laravel, controller" }
how do i access lists values stored in a dictionary key? I have got a dictionary of lists. Lets say it looks like this : dictionary1 = { 'key1':[10000,20000], 'key2':[30000,40000], 'key3':[50000,60000], # and so on... } I want to access these two values from each key and use it with `sys.argv` It should work like this : `python command key1` to get values 10000 and 20000 from key1 and use it in a `for loop` and `python command key2` to get 30000 and 40000 from key2 and use it in the same `for loop` How do access these two list values from each key ?
Which part are you confused about? can't you just do lower, upper = dictionary1[key]
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "python" }
How to set a cell value in a multi header/multi index pandas Dataframe I have a Dataframe that looks like that: SPY Open High Low Close Bid Ask Bid Ask Bid Ask Bid Ask Date 2010-01-01 NaN NaN NaN NaN NaN NaN NaN NaN 2010-01-02 NaN NaN NaN NaN NaN NaN NaN NaN 2010-01-03 NaN NaN NaN NaN NaN NaN NaN NaN 2010-01-04 NaN NaN NaN NaN NaN NaN NaN NaN I want to set a specific cell value, for example open bid for date 2010-01-04 so I tried this: df.ix['2010-01-04', 'SPY']['Open']['Bid'] = 10 but nothing has happened to the dataframe. When I remove `['Bid']` at the end values for both bid and ask change but I don't know how to change only one value at a time.
* Use a `tuple` to get at the MultiIndex element * `.ix` has been deprecated. In this case, use `.at`. `.loc` would also work, but `.at` is more efficient if getting at a particular cell. * * * df.at['2010-01-04', ('SPY', 'Open', 'Bid')] = 10
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, pandas, dataframe" }
Is there a mind mapping software that can handle latex? I run Lubuntu 12.04 and after several terrible experiences with libre office I downloaded core and have not touched it since april. I find kile ok and have been learning to use that and writing with latex. I am hoping there's a mind mapping program that I could use that is not too "bubbly" but most importantly can handle maths (i.e. latex). I don't need it to be able to integrate with kile but anything extra is a bonus! Tips? Edit: The latex is needed for writing mathematical equations. Edit: I thought they were all useful suggestions but on balance, the selected answer was my personal favourite out of them. Though it was tough to decide. Dia particularly does look like a good shout with ekee.
Have you seen: < and < ? Both suggest < < ...although the provided mindmaps feature is quite "bubbly" As far as handling Maths: < ... Graphics in LATEX using TIKZ ... TIKZ and PGF examples ... and < will also prove helpful.
stackexchange-askubuntu
{ "answer_score": 6, "question_score": 15, "tags": "software recommendation, latex" }
Hiding console when running an Ocra executable? I have successfully made an executable using Ruby's Ocra gem, however, when I run the executable the console displays along with my program. Is there any way to hide the console on launch? Any help is appreciated! Thanks!
from ocra readme: > .rb files will become console applications. .rbw files will become windowed application (without a console window popping up). Alternatively, use the “--console” or “--windows” options.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby, console, hide, executable, ocra" }
Распарсить массив из json Есть json файл с названием example.json { "name":"John", "age":31, "pets":[ { "animal":"dog", "name":"Fido" }, { "animal":"cat", "name":"Felix" }, { "animal":"hamster", "name":"Lightning" } ] } Пытаюсь вывести названия животных <p id="demo"></p> <script> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name + "," + myObj.pets; } }; xmlhttp.open("GET", "example.json", true); xmlhttp.send(); </script> На выходе получаю > John,[object Object],[object Object],[object Object] А как получить такое Имя: Джон, Животные: Собака - Фидо, Кот-Феликс, Хомяк - Лайтнинг.
Вам нужно в строку массив питомцев преобразовать. Как-то так: document.getElementById("demo").innerHTML = myObj.name + ", Животные: " + myObj.pets.map(pet => pet.animal + " - " + pet.name).join(',');
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript" }
Ignoring items that have fewer than three words Let's say we have a list of strings: List1 = ['I am a man', 'I am a woman', 'I am', 'I', 'Ian'] How do I remove the items that have fewer than three words? The result should be: ['I am a man', 'I am a woman'] I tried using the `len` function but it wouldn't remove the list.
Using a list comprehension can filter your List1: List2 = [i for i in List1 if len(i.split())>2]
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "python, python 3.x" }
How to replace siding around deck The previous owners of my house installed a small deck off the back of the house. The deck was built flush against the siding. I am going to replace the siding on the house, so I’m wondering what to do around the deck. Do I remove the deck so that I can remove the siding between it and the sheathing? **Or** Do I cut the siding around the deck to remove it, then put the new siding around the deck ( _instead of behind it_ )? The new siding will be vinyl. ![deck image 1](
The type of siding shown in your picture is most often used to serve as both the siding and sheathing all in one. A common term for this plywood material is T-111 plywood. You would do well to check your house construction to see if there really is a second sheathing layer. If you find that the T-111 is nailed directly to the outside of the studs you may want to reconsider removing it. Because if you do you would have to come back at more expense to install sheathing as vinyl siding cannot be mounted directly to studs. The better strategy is to just install the new siding right over the T-111. If you do that you can then just use the pocket trim at the vinyl ends just butted up to the deck and caulked at the join.
stackexchange-diy
{ "answer_score": 1, "question_score": 2, "tags": "deck, siding, vinyl siding" }
Can't access custom template field data in Sitecore I can't figure out why my template fields don't show anything in Sitecore. My template content is as follows: ![enter image description here]( `@Html.Sitecore().Field("Title")`, `@Html.Sitecore().Field("Sub-title")` and `@Html.Sitecore().Field("Description")` give the correct values but when I try these new fields I just added: `@Html.Sitecore().Field("Banner Image")` or `@Html.Sitecore().Field("Test")` \- they're just blank. Any ideas?
Sitecore template fields are items in Sitecore content tree. If you want to use them in the client facing site, you need to publish them as you publish all the other items. Simplest way of checking if that's the problem is to open your page in Experience Editor and check if the fields work there.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "sitecore" }
SQL extracting text between characters I am trying to extract a string between two characters. The length could change for any of the numbers. The values I am trying to extract is only e.g. 0001A, 0002BB, 0003C etc. Using `select SUBSTRING(ordtxt,7,4) as ordtxt`, I would be able to only extract x amount of characters from the left which isn't really something I am looking for. 100/0/0001A/001 101/000/0002BB/001 102/00/0003C/0001 Thank you for any help.
You could use a simple XML approach, which would isolate values from a delimited string SELECT convert(xml,'<x>'+replace(YourColumn,'/','</x><x>')+'</x>').value('/x[3]','varchar(100)') FROM YourTable The solution breaks down the string into positions denoted by a numeric index, simply select the required element you need. For example if you need 0001, 0002, 0003 then use a position of 3 in the function above. The syntax is based on SQL Server
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "sql, sql server, tsql, substring" }
Image not getting displayed from the "if" clause I want a particular image to be displayed for a corresponding text So I tried like below in my increase() TextView hedng = (TextView) findViewById(R.id.singleitemheading); if(hedng.getText() == "HEADING OF THE TOPIC"){ ImageView lvlm = (ImageView) findViewById(R.id.levelimg); lvlm.setImageResource(R.drawable.ic_launcher); } But the image is not being displayed
TextView hedng = (TextView) findViewById(R.id.singleitemheading); if(hedng.getText().toString().equalsIgnoreCase("HEADING OF THE TOPIC")){ ImageView lvlm = (ImageView) findViewById(R.id.levelimg); lvlm.setImageResource(R.drawable.ic_launcher); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, textview, imageview" }
What is a 'dough spatula'? I got a new baking book for Christmas; in it, I found the following sentence: > [To bake this bread] you will need the following kitchen tools: a digital scale for metric measures, a small scoop for flour, a thermometer, a wide bowl for mixing, a rubber spatula, **a dough spatula** , and a bench knife (emphasis mine) What is a dough spatula and how does it differ from a rubber spatula? What do I look for when I go to the store? Google shows me many products, all of which look entirely different from one another. ETA: The first mention I see of it indicates I use it to... clean my hands? "Use a dough spatula to clean the clumps [of flour and water] off your hands and tidy the inside of the bowl"
My first thoughts are this which is actually a scraper but I wouldn't use a metal scraper in a bowl. Being flexible plastic, it flexes and molds itself to the inside of a bowl and allows easy removal of dough. !enter image description here
stackexchange-cooking
{ "answer_score": 13, "question_score": 9, "tags": "baking, equipment" }
Some letters reordered My native English speaking friend gave me a piece of paper with the this on it. > A H R B Q D W E F L M N S X G I J K O P C T V Y U Z And he said: "Here is the alphabet. This is how it should be". I was a bit puzzled, because I couldn't understand what he means, but I agreed with him after he explained his reasoning. > What was his reasoning for putting the letters like this? note: I didn't come up with this, but I cannot disclose the source for now because I would spoil it. I promise to do it after I get the answer. Second note: This already got answered so here is the source: > From one of my favorite people in the world: <
Solution: > The letters are sorted by its name sound alphabetically
stackexchange-puzzling
{ "answer_score": 4, "question_score": -1, "tags": "lateral thinking, letter sequence" }
Generating function of $1 + x^k + x^{2k} +\cdots$ I know that the generating function of $1 + x + x^2 + \cdots$ is $\frac{1}{1 - x}$. But what is the generating function of $1 + x^k + x^{2k} + x^{3k} + \cdots$ ?
If $$\frac{1}{1-x} =1+x+x^2+x^3+x^4+\ldots, \tag{$|x|<1$}$$ then $$\frac{1}{1-x^k} =1+(x^k)+(x^k)^2+(x^k)^3+(x^k)^4+\ldots \tag{$|x^k|<1$}$$ Note that $|x|<1$ and $k\in \mathbb{N}$ implies $|x^k|<1$.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "abstract algebra, combinatorics" }
What does あえて mean? I would like to know what does exactly mean: to dare to do sth (like )? On purpose (like )? Another meaning? In jisho.org, seeing the definitions and example sentences, it supposedly means 1. to dare to / 2, on purpose, but on the Internet I've found sentences where these two meanings don't match, like this one: If translated: "I'm sorry, I dared to lose the last train." Or "I'm sorry, I lost the last train on purpose." It doesn't make much sense to me. Or for example, in this another sentence: (It is not so dark as to turn on the lights.), what function has ? Could you please tell me how many meanings has and give me an example sentence for each meaning? Thank you so much in advance for your help!
The most common meaning of is 'dare to' whereby someone expresses some kind of desire while acknowledging there could be some adverse consequences. > **** The department head dared to express his opposing view to the company president. It can also have a nuance of 'force myself to do something'. Your example is in line with that meaning. > **** It's not so dark as to have to bother myself with turning on the light. As for , the context is needed. Is it someone defying an order to get the last train, for example? Maybe it's an apologetic husband who 'dared' to stay out drinking late or something. It depends on what came before it.
stackexchange-japanese
{ "answer_score": 6, "question_score": 2, "tags": "meaning, words" }
MSMQ: What is the best way to read a queue in a non-blocking fashion? If a queue is empty and you don't want to block for too long, you risk getting a System.Messaging.MessageQueueException. How would you tell the difference between a timeout on waiting for a message and a real error?
Try this: MessageQueueException.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout See < for a sample similar to what you're trying to do.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "msmq" }
Gradient of loss containing multiple max functions I have the following loss I want to minimize: $L=(y-(max(0,w^Tx_1) + max(0,w^Tx_2) + max(0,w^Tx_3)))^2$ Now I want the gradient w.r.t. my weight vector $w$: if $w^Tx_1>0$ & $w^Tx_2>0$ & $w^Tx_3>0$ $\rightarrow$ $2(y-(w^Tx_1 + w^Tx_2 + w^Tx_3))(-(x_1 + x_2 + x_3))$ if $w^Tx_1<0$ & $w^Tx_2>0$ & $w^Tx_3>0$ $\rightarrow$ $2(y-(w^Tx_2 + w^Tx_3))(-(x_2 + x_3))$ So the terms are removed if $w^Tx_i < 0$. This means that if all terms are $<0$: $w^Tx_1<0$ & $w^Tx_2<0$ & $w^Tx_3<0$ $\rightarrow$ $2y$ So in that case I get a scaler as gradient, while in the other cases I get a vector. Are my derivatives correct? If so, is it applicable to have a vector of size len(x) of y's as gradient? Edit: After checking again I think that the derivative in case all $w^Tx_i<0$ wrt $w$ is 0? So the minimum will be to predict always predict negative?
Note that the gradient wrt $w$ is actually a vector consisting of $\frac{\partial L}{\partial w_i}$, where $w_i$ is the $i$th element of $w$. If all $w^Tx_i<0$, then $\frac{\partial L}{\partial w_i} = 0$ for all $i$, i.e. the gradient is a vector of length $\text{len}(x)$ with each entry equal to $0$. But this does not mean that the minimum is achieved when all $w^tx_i<0$. This is because the function is non-convex. As an example consider scalars $y = 2, x = 1$. Then $L = (2-\max(0, w))^2$. If you plot this function (see a plot here\)%5E2)), you'll notice that there is a flat region with gradient $0$, but the minimum occurs at $w=2$.
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "derivatives, optimization, gradient descent" }
Open a link of Excel with the dialog popup window in quick launch SharePoint 2010 I have a Excel document in the Library SharePoint 2010. And I set **"Open in the client application"** in Library setting. Every time I open this document, there is a **popup window** with a question **"How would you like to open this file?"** Then I can choose **Read Only** or **Edit**. !enter image description here I copy the link of Excel to quick launch. But there is no popup window when I open this Excel from quick launch. Further more, **Excel is Read only**. I cannot edit it. And there is no button "Edit this workbook". And my site is a publishing site, I cannot add JavaScript to quick launch. At beginning, I though I can add the link of **"Open in the browser"**. But the members of team will make a mistake in this view. They would like use the popup window. How could I open Excel document in quick launch with a dialog popup window? Is it possible to add JavaScript? Thank you in advance.
You can use following JavaScript for achieving this var stsOpen = new ActiveXObject("SharePoint.OpenDocuments.3"); stsOpen.ViewDocument3(window," If your site is non-publishing then you can place JavaScript in the Quick Launch. Check this blog <
stackexchange-sharepoint
{ "answer_score": 0, "question_score": 0, "tags": "2010, sharepoint enterprise, excel" }
301 Redirect with Major Changes to Path and File Name I have an old blog website that I've recently rebuilt in Wordpress. I'm trying to 301 redirect the old blog posts to the new Wordpress posts. **The old URL structure:** **The new URL structure:** I've tried the following code Redirect 301 /blog/phones/101/The%20Post%20Title However, this results in redirecting me to the following page: < Can anyone please help me with the correct way to redirect these pages? Thanks for your help!
Use `RedirectMatch` like this : RedirectMatch 302 /blog/phones/101/([A-Za-z]+)(?:.*?)([A-Za-z]+)(?:.*?)([A-Za-z]+) /blog/$1-$2-$3 **Note:** clear browser cache then test .
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "wordpress, .htaccess, redirect, http status code 301" }
Cannot get databinding to work I am having difficulty binding to a property on my object. This is my property: private int? Tid; private int? innerTenantID { get { return Tid; } set { Tid = value; innerTenant = (value.HasValue)? Tenant.GetTenantByID(value.Value) : null; } } And this is my attempt to bind: this.DataBindings.Add(new Binding("innerTenantID", tblCashReceiptsBindingSource, "TenantID")); I get, ArguementException, "Cannot bind to the Property 'innerTenantID' on the target control. Prameter name: PropertyName; The TenantID value is a nullable integer.
The first thing I see, is that the getter and setter is not public. Probably this is the problem. private int? Tid; public int? innerTenantID { get { return Tid; } set { Tid = value; innerTenant = (value.HasValue)? Tenant.GetTenantByID(value.Value) : null; } }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c#, winforms, .net 3.5" }
Does case matter in HSTS header Strict-Transport-Security? In http response there can be header Strict-Transport-Security. I was sure that it must be written in Train-Case, like it is on dropbox.com: $ curl --silent --head | grep -i strict Strict-Transport-Security: max-age=15552000; includeSubDomains But on one site I saw it written in kebab-case (this site is not publicly accessable, thats why I don't give link to it): $ curl --silent --head | grep -i strict strict-transport-security: max-age=31536000; includeSubDomains Is it correct to use all lower case letters in Strict-Transport-Security header?
The HTTP specification RFC 7230 section 3.2 says header names are case-insensitive. So you can send them as lower case if you like. However it is traditional to send them using the specification documents casing. If only to make life easier for people troubleshooting the traffic.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "https, http headers, hsts" }
Get information from button I have a WPF application with a grid. There are rows and columns, at the end of each row I have a "Click me" button. How can I get information where pressed button? I want to display information from row, after the button has been clicked.
Simplest way is to attach all buttons to the same event and then but give them a unique name. private void btn_Clicked(object sender, RoutedEventArgs e) { Button cmd = (Button)sender; string name = cmd.name; switch(name) //{ do some stuff based on the button name} }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, .net, wpf, button, grid" }
Choose which partition to format when installing Windows 8 When installing Windows 8 I got this error message: Windows cannot be installed to this hard disk space. Windows must be installed to a partition formatted as NTFS. Windows cannot be installed to this hard disk space. The partition is of an unrecognized type. I know I got this because I've got Ubuntu on it, but I really want to be sure before I mess up my computer. Do I need to format partition 2 or do I need to do something else? These are the partitions I have: !enter image description here
Do you have any data left on your hard drive? If so, then be **absolutely sure** to create a backup! * * * 1. **Delete that partition** That's the only option you have, according to your screenshot. 2. **Create a new partition** A new list item called "Unallocated space" should appear. Click "New" and create a new partition. You should choose about 25 GB minimum space. 3. **Format** Select the created partition and hit "Format". As far as I can remember, this step is not absolutely necessary since Windows will automatically perform it if you haven't done yourself.
stackexchange-superuser
{ "answer_score": 0, "question_score": 1, "tags": "windows 8, partitioning" }
Decreasing sequence in subgroup Can someone clarify the following statement: _Let $H\subset\mathbb{R}$ be a subgroup $\neq 0$. Let $a = \text{inf} \lbrace x\in H \vert x >0 \rbrace$_. If $a\notin H$ then there exists a decreasing sequence in $H$ converging to $a$. What guarantees this decreasing sequence?
Whenever the infimum $a$ of _any_ non-empty subset $S$ of the real numbers that is bounded below has $a\notin S$, one must have $(a,a+\varepsilon)\cap S\neq\emptyset$ for all $\varepsilon>0)$, by the definition of infimum. Now choosing $s_n\in(a,a+2^{-n})\cap S$ for $n\in\Bbb N$ ensures that $\lim_{n\to\infty}s_n=a$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "lie groups" }
Finding the limit of a contractive sequence I've been trying to solve an exercise. I am given the recursive formula of a sequence and I am asked to prove that it is converging and then find its limit. Given $x_0=a$ and $x_1=b$, with $a,b \in R$, the recursive formula is $\displaystyle x_{n+1} = \frac{x_{n-1} +(2n-1)x_n}{2n}$. For my solution, I showed that the difference of two successive terms is: $|x_{n+1} - x_n| = \frac{1}{2n}|x_{n-1}-x_n|\leq\frac{1}{2}|x_{n-1}-x_n)|$ and thus the sequence is contractive. If it's contractive, it is Cauchy and if it is Cauchy then it converges. However, I am unable to figure out how to calculate its limit. Since $a,b$ are parameters, I'm sure there is a closed formula that gives the limit and it depends on those two parameters but I can't find it. Any ideas?
Hint: Show by induction that for $n\geq 0$ $$x_{n+1}-x_n=(-1)^n\frac{b-a}{2^n n!}$$
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "limits, recurrence relations, cauchy sequences" }
Any way to shorten this if statement? PHP I'm trying to keep my code nice and elegant. Any way to make this if statement shorter? if(strlen($cname) > 100) { } if(strlen($cowner) > 100) { } if(strlen($cemail) > 200) { } if(strlen($cpassword) > 100) { } I can't do this because I want to print out a specific message for each if statement: if(strlen($cname) > 100 || strlen($cowner) > 100 || strlen($cemail) > 200 || strlen($cpassword) > 100) { // I want to print out a message like email is too long not just one of these strings is too long }
Frankly, I think you've got the most elegant solution for what you are trying to do.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, if statement" }
Can Dell SonicWall NetExtender record urls visited My company is in geographical different area and I am in a different area. They have asked me to install VPN client **Dell SonicWall NetExtender** I want to know if I am connected to it can they track which websites I am visitingr or is this not possible? I did a tracert and my packets are going to appropriate locations without being sent to them. However, I want to know if this is really possible.
It's certainly possible to _set it up_ they way you're asking about, but the tracert shows they're not doing this. With almost any VPN, there is a choice between sending **all** traffic through the VPN, or sending only necessary traffic through the VPN. Bandwidth costs money, and none of the companies I've serviced care what websites employees visit when out of the office. If they have an IT guy/gal/team, you could just ask one of them. Unless they're socially inept or you're a jerk, they'll be straight with you.
stackexchange-serverfault
{ "answer_score": 1, "question_score": -1, "tags": "vpn, dell, sonicwall" }
Indent in floating toc (.Rmd) I want to have the same indent in a wrapped line of a floating table of content entry when I create a html file from a .Rmd file in RStudio, but I cant't find the right place in the .css. ![enter image description here](
Fixed by RStudio immediately, thank's.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "css, r markdown" }
Different analytic branches of $\sqrt{z-z_0}$ on a region have disjoint images. Let $D$ be a region and $f_1(z),f_2(z)$ be two different analytic branches of $\sqrt{z-z_0}$. Show that $f_1(D)\cap f_2(D)=\varnothing$. **My Attempts.** Prove by contradiction. Say $f_1(z_1)=f_2(z_2)$, then easy to see $z_1=z_2:=w$. Note that $(f_1(z)-f_2(z))(f_1(z)+f_2(z))\equiv 0$. Let $h(z)=f_1(z)-f_2(z)$. If $h(z)$ is constant then we are done. If not, $w$ must be isolated as a zero point of $h(w)$, i.e. there exists $D_0(w,\delta)$ such that $\forall z\in D_0,f_1(z)+f_2(z)=0$. Using isolation of zero points again, $f_1(z)+f_2(z)\equiv 0$. But I don't know how to proceed (or maybe there'll be a better solution). I would be extremely appreciative of any assistance!
You are on the right track. First note that $w \ne 0$ because there is no analytic branch of $\sqrt{z-z_0}$ in a neighborhood of $z=z_0$. From $$ (f_1(z)-f_2(z))(f_1(z)+f_2(z))\equiv 0 $$ it follows that one of the factors must have an accumulation point of zeros in $D$, and therefore is identically zero. (Here we use that $D$ is a _region,_ i.e. a connected open set.) So we have $f_1 \equiv f_2$ or $f_1 +f_2 \equiv 0$. The latter is not possible because $f_1(z_1) + f_2(z_1) = 2w \ne 0$. * * * In the same manner one can show that two holomorphic branches of $(z-z_0)^{1/n}$ ($n\ge 2$ an integer) on a (connected) domain are either identical, or have disjoint images.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "complex analysis, analytic functions" }
como executar um botão especifico numa lista de 5 botões identicos Estou a fazer uma dashboard com utilizadores e preciso de um botão editar. Quando o botão editar é executado ele apenas faz aparecer e desaparecer código, mas queria saber se é possível executar código jQuery e seleccionar o id do botão. ![inserir a descrição da imagem aqui]( <a id="1" class="edit">E</a> <a id="2" class="edit">E</a> <a id="3" class="edit">E</a> $('.edit').on('click',function(){ var id = $('.edit').id; alert(id); });
O teu html `<a id="1"edit">E</a>` está mal formatado, mas partindo do principio que o teu seletor funciona, dentro da callback do jQuery podes usar `this.id` para saber o ID do elemento que originou o evento. $('a.edit').on('click',function(){ var id = this.id; alert(id); });
stackexchange-pt_stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "javascript, jquery, jquery select2, javascript eventos" }
Can the operating system tell me when a new file is created? I want to know when a new file is created on a specific directory, instead of scanning the directory from time to time. I understand that there is a way to make the operating system tell my program that a new file was created. How does it work? As noted, this has similarities with How to be notified of file/directory change in C/C++, ideally using POSIX
Depends on which OS. On Windows, the base API would be Directory Change Notifications.aspx). Since you mention Linux in the tags, this would be the inotify API. To add to the OS X answer, as of 10.5, you want the FSEvents API.
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 6, "tags": "windows, linux, file, operating system" }
SQL on how to list of customers who have placed more than 30 orders in a single year select CustomerKey, FirstName, LastName from DimCustomer where CustomerKey in (select distinct CustomerKey from FactInternetSales where year(OrderDate) = 2005 or year(OrderDate) = 2006 or year(OrderDate) = 2007 or year(OrderDate) = 2008); Where am I supposed to add 'more than 30 orders' section?
try like below by using join and aggregation filter select DimCustomer.CustomerKey, DimCustomer.FirstName, DimCustomer.LastName,year(FactInternetSales.OrderDate),count(*) from DimCustomer join FactInternetSales on DimCustomer.CustomerKey=FactInternetSales.CustomerKey group by CustomerKey, FirstName, LastName,year(FactInternetSales.OrderDate) having count(*)>=30
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql" }
Right to Left English for left handed people I have a big phone (Moto G). I'm left-handed, so everything on the left of the screen would be so much more convenient on the right, and vice versa. But wait, Android 4.2 introduced Right-to-left (RTL) layouts! The problem is that I don't speak any RTL languages, just English. My understanding is that Android sets whether it's LTR or RTL, and any app can read this setting) to display an appropriate layout. Can I set my Android device to be right to left while still using English?
Yes you can do that. Firstly enable the The developer mode by tapping the build number in About Phone Then go in developer options and then check force RTL layout
stackexchange-android
{ "answer_score": 1, "question_score": 3, "tags": "screen, localization, accessibility" }
ArgumentError: Unknown key: :order. Valid keys are: :class_name, :anonymous_class in Rails 4.2.6 I am getting the following error while running rake db:migrate: > ArgumentError: Unknown key: :order. Valid keys are: :class_name, :anonymous_class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type This is the model where I am getting error: class Report < ActiveRecord::Base belongs_to :user has_many :icons, :order => 'position_id ASC' #showing error here.. has_many :photos, :dependent => :destroy end Please help.
has_many :icons, -> { order('position_id ASC') }
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 9, "tags": "ruby on rails" }
Pandas - count distinct values per column I have a dataframe that looks like this: Id ActivityId ActivityCode 1 2 3 1 2 4 1 3 2 I need to get a count of the distinct Activity IDs that the Id is related to. In the example above, id 1 would return 2 since there're 2 distinct activity ids for that id. The SQL would look this way: SELECT COUNT(DISTINCT ActivityId) FROM table GROUP BY Id How do I do this in pandas? (And if possible, I'd like to know if there's a way to get the result in a dictionary, without iterating manually)
I think you need `groupby` with `nunique` : print (df) Id ActivityId ActivityCode 0 1 2 3 1 1 2 4 2 1 3 2 3 2 8 7 df = df.groupby('Id')['ActivityId'].nunique() print (df) Id 1 2 2 1 Name: ActivityId, dtype: int64 And for `dict` add `Series.to_dict`: d = df.groupby('Id')['ActivityId'].nunique().to_dict() print (d) {1: 2, 2: 1}
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 3, "tags": "python, pandas, dictionary, group by" }
Is it possible to customise react-native-media-controls styling? I have a video component that uses react-native-video with react-native-media-controls, I want to be able to customise the Styling of the controls. Is this possible to do on react-native-media-controls? <MediaControls duration={this.state.duration} isLoading={this.state.isLoading} mainColor="orange" onFullScreen={this.onFullScreen} onPaused={this.onPaused} onReplay={this.onReplay} onSeek={this.onSeek} playerState={this.state.playerState} progress={this.state.currentTime} toolbar={this.renderToolbar()} />
I've checked the @react-native-media-controls library. The author just made the "mainColor" style is customizable. Actually it could be customizable if you really need an emergency issue I can fork it and make it customizable, however, this PR takes time to merge. However, you can install it with my fork. Do you need it? ## **UPDATED:** I've updated the library and opened a PR. < If someone needs to use it with updated version, it is available on my repo until this PR will be merged.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "react native" }
nServiceBus with Distributor in a web farm I am not sure where the distributor/s should run when there is a number of clients and a number of servers. If I have a single distributor which all clients send to and all servers get work from then surely it is a single point of failure. Is there a way to remove this weak point?
You'd likely run a distributor on a cluster for high-availability. That being said, you can go so far as to have a separate distributor for each message type and configure your clients to send each message type to its designated distributor. Then you can allocate servers to distributors based on the amount of resources you want to allocate per message type. Does that answer your question?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "msmq, nservicebus" }
How to improve the performance of an SQLite+UITableView app? We have an app with sqlite which has morethan 10,000 rows and above 10MB and in our first view we have two buttons clicking on first button will take to another view which has a tableview, we need to show all these 10,000 records in that tableview for searching. Since we are loading all items at a time, its taking some time to load that view when clicked on button in first view. is there any option to avoid the delay? like any lazy loading option or showing 100-1000 rows first then appending all other rows at bottom. **THIS IS WHAT APPLE HAS WRITTEN:** We found the following issue with the user interface of your app: * Your app responded very slowly. For example, when we tapped the Movies or Albums button, it took 5 seconds.`
You can try loading the data in multiple batches using the LIMIT and OFFSET clauses. See the sqllite docs. E.g. on page load you request the first 100 result rows and when that request completes you can request the next 100 etc.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "iphone, sqlite, uitableview" }
Pass values to a trigger function in coffee script I have some existing code where I want to make some changes. Here it is calling a trigger function $('table.fields tr:last').find('.options').trigger('click', [$this.data('id')]) and here is the function receiving two params, $(document).on 'click', 'form .options', (event, time) -> I have to pass another variable `index` What I am trying is something like: index = 1 $('table.fields tr:last').find('.options').trigger('click', [$this.data('id')], index) And receiving like: $(document).on 'click', 'form .options', (event, time, index) -> console.log index but I am getting index `undefined` in function.
Pass time params in array while Function call $('table.fields tr:last').find('.options').trigger('click', [$this.data('id'), index]) Function defination will remain same as you are doing $(document).on 'click', 'form .options', (event, time, index) -> console.log index
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, coffeescript" }
Brackets with dot, regular expressions I want delete brakets that ends on a dot from string. I use regular expresion - `@"\([^)]+\)\."` it works with string like this - `some text (some text) some (text).`, after regular expression I have string - `some text (some text) some` But this not work with string like that - `some text (some text) some (text (text) some).` How to fix it?
Just change your regex like below to match the brackets which ends with `.` @"\((?:[^()]*\([^()]*\))*[^()]*\)\." DEMO **Regular Expression:** \( '(' (?: group, but do not capture (0 or more times): [^()]* any character except: '(', ')' (0 or more times) \( '(' [^()]* any character except: '(', ')' (0 or more times) \) ')' )* end of grouping [^()]* any character except: '(', ')' (0 or more times) \) ')' \. '.'
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, regex" }
Flex mobile - How do I move to the next data in List.selectedItem when moving to next page? When I move page01 to page02, I pass the same data along with it using the following code: navigator.pushView(Page02, data); How do I move to page02 with passing the next row of data (instead of the same data)? In other word, how to increment to the next row of data with pushView? Thanks.
If you have access to the List component which displays the data you want to pass into views, you can do something like this: myList.dataProvider[myList.selectedIndex+1] You'll want to do some checking to make sure that you're trying to reference an index that actually exists: var mySelectedObject :Object; if(myList.selectedIndex+1 < myList.dataProvider.length){ mySelectedObject = myList.dataProvider[myList.selectedIndex+1] } else { // do some other behaviour; such as selecting the first one in the list mySelectedObject = myList.dataProvider[0] } navigator.pushView(page02, mySelectedObject );
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "apache flex, flex4, flexbuilder, flex4.5" }
run callback function with its parent in jquery I want to run animations for the links (q2 ul li a) while showing (q2) in same time, q2 will be hidden on page load. $('.q2').fadeIn(function(){ $('.q2 ul li a').animate({ borderSpacing : 1 }, { step: function(now,fx) { $(this).css('-webkit-transform','rotate('+(-1*200*now+200)+'deg) scale('+(now)+')'); $(this).css('-moz-transform','rotate('+(-1*200*now+200)+'deg) scale('+(now)+')'); $(this).css('transform','rotate('+(-1*200*now+200)+'deg) scale('+(now)+')'); }, duration:1500 }, 'linear') }); }); and in css : ul li a { border-spacing: 0; }
In your code, animation will be execute after `$('.q2')` visible because you put this animation in the callback of fadeIn function. Maybe it should like this: $('.q2').fadeIn(1500); $('.q2 ul li a').animate({ borderSpacing : 1 }, { step: function(now,fx) { $(this).css('-webkit-transform','rotate('+(-1*200*now+200)+'deg) scale('+(now)+')'); $(this).css('-moz-transform','rotate('+(-1*200*now+200)+'deg) scale('+(now)+')'); $(this).css('transform','rotate('+(-1*200*now+200)+'deg) scale('+(now)+')'); }, duration:1500 }, 'linear') });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, jquery animate, fadein, jquery callback" }
Является ли в данном предложении "кроме того" вводным, нужна ли запятая после него? _Кроме того можно проверить учеников нашего учителя._
Конечно же это вводное сочетание, и запятая нужна. Ведь у нас значение _вдобавок._ Если бы это был член предложения, тогда под "тем" подразумевался бы ученик _(Кроме того ученика можно проверить и учеников учителя),_ но тут явно не такой смысл, потому что, если бы был такой, нельзя было бы так запросто опустить этого "ученика" в этом случае.
stackexchange-rus
{ "answer_score": 3, "question_score": 1, "tags": "пунктуация" }
Android lifecycle - are my ideas correct? I have read about android life cycle in a couple of books and official documentation, but still am unable to get my thoughts in one place and understand it completely. I am developing simple app, in which I use fragments, so this makes it even harder, as fragments have separate life cycle from applications. So I would like to ask you a couple of questions: My application is a simple logger of various data, so basically user only needs to enter data and look at it. As I understand, cycles like onPause, onResume, onStop I shouldn't worry about? I guess my real question is which android life cycle methods are essential for every application? Is it considered to be a very bad practice if you are (fragment vise) calling all methods and managing all views in onCreateView? Do you know any simple and yet good guides which could help me to understand how to manage android life cycle correctly?
OnResume and onPause are very important part of the lifecycle, and you should worry about it. Whenever a user change from you App to another, o goes to the notifications, or whatever, always will be calling onPause() when it goes to another app, and onResume() when it came back. You have to understand that you Activity may be killed, (if the system don't have enough resources), in that case onCreate will be called first, but if not, then will jump the onCreate and goes to onResume(). onStop is mostly no necessary, as you should free all your resources in onPause() because after the onPause call, you don't know if your activity will be killed by the system. Fragments includes the same Activity lifecycle callbacks plus their own callbacks.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, android fragments, android activity, android lifecycle" }
Using the mgf of a distribution to find expected values of an estimator Suppose that $Y_1, ..., Y_n$ is a random sample from a Poisson distribution with unknown mean $\theta$ and let $T = \sum_{i = 1}^n Y_i$. Find the constant $c$ such that the estimator $e^{-cT}$ is unbiased as an estimator of $e^{-\theta}$. To show that the estimator is unbiased, I want to show that $E_\theta(e^{-cT}) = e^{-\theta}$, where $T$ has a Poisson($n\theta$) distribution. The m.g.f. of the poisson distribution with mean $\theta$ is given as $M(t) = e^{\theta(e^t - 1)}$ I understand that $E(Y) = M'(0)$ $E(Y^2) = M''(0)$ But what is $E(e^{-cT})$? So the solution points out that "note that $E(e^{-cT}) = e^{n\theta(e^{-c} -1)}$ (the mgf of a Poison$(n\theta)$ distribution at $c$. But why?
In general, we can compute $E(e^{-cT)}$, where $T$ is Poisson with mean $\mu$, directly by using the formula $f(t)=e^{-\mu}\mu^t/t!$ for the pmf of $T$: \begin{align*} E(e^{-cT}) &= \sum_{t=0}^\infty e^{-ct}f(t)\\\ &=\sum_{t=0}^\infty e^{-ct} e^{-\mu} \mu^t/t!\\\ &= \sum_{t=0}^\infty e^{-\mu} (e^{-c} \mu)^t/t!\\\ &= e^{\mu(e^{-c}-1)}\sum_{t=0}^\infty e^{-e^{-c}\mu} (e^{-c} \mu)^t/t!\\\ &= e^{\mu(e^{-c}-1)} \end{align*} where the last step comes from identifying $e^{-e^{-c}\mu}(e^{-c}\mu)^t/t!$ as the pmf of a Poisson with mean $e^{-c}\mu$.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "moment generating functions" }
lodash - Remove columns from datatable (2D matrix) if all values are null I have a 2D matrix like this one where the first row is the columns names and other rows are values. var datatable = [ ["a", "b", "c", "d"], //first row are columns names [ 1, 0, null, 3 ], //other rows are values [ 6, null, null, 8 ] ]; I would like to remove columns when all values are `null` as the expected result below: var datatable = [ ["a", "b", "d"], //first row are columns names [ 1, 0, 3 ], //other rows are values [ 6, null, 8 ] ]; The numbers of rows and columns can vary. If there is a compact and fast way to achieve it with lodash that's perfect.
Here you have my approach using `map()`, `filter()` and `some()`. var datatable = [ ["a", "b", "c", "d"], [ 1, 0, null, 3 ], [ 6, null, null, 8 ] ]; let res = datatable.map( x => x.filter((_, idx) => datatable.slice(1).some(arr => arr[idx] !== null)) ); console.log(res);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, lodash" }
python 3.4.3 unable to write to a file in a desktop folder I have a simple code to write a file in a specific folder. System creates the file in the folder but couldn't write on it. It is on windows and I checked the IDE write access (Pycharm) they seems fine. File is empty. Following with code is to read whether I could write or ensure the previous one is finished. It is not writing the short string to the file. I have tried it on command line but it didn't work there also. with open ('C:/Users/***/Desktop/***/output.log',mode ='w', encoding ='utf-8') as a_file: a_file.write ="test" with open ('C:/Users/***/Desktop/***/output.log', encoding ='utf-8') as a_file: print(a_file.read())
The `write` is a method (function), you need to call, instead of assigning to it. with open ('C:/Users/***/Desktop/***/output.log', mode='w', encoding='utf-8') as a_file: a_file.write("test") # <---
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, python 3.x" }
Can you convert this to VB? static RelatedPosts() { Post.Saved += new EventHandler<SavedEventArgs>(Post_Saved); } static void Post_Saved(object sender, SavedEventArgs e) { if (e.Action == SaveAction.Update) { Post post = (Post)sender; if (_Cache.ContainsKey(post.Id)) _Cache.Remove(post.Id); } } I converted to: Shared Sub New() Post.Saved += New EventHandler(Of SavedEventArgs)(AddressOf Post_Saved) End Sub Private Shared Sub Post_Saved(ByVal sender As Object, ByVal e As SavedEventArgs) If e.Action = SaveAction.Update Then Dim post As Post = DirectCast(sender, Post) If _Cache.ContainsKey(post.Id) Then _Cache.Remove(post.Id) End If End If End Sub But it give me an error: Public Shared event Saved() is an event and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.
Use this AddHandler Post.Saved, AddressOf Post_Saved instead of Post.Saved += New EventHandler(Of SavedEventArgs)(AddressOf Post_Saved)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "c#, vb.net" }
Join and explode nested list and dictionary in pandas dataframe I'm struggling to normalize a dataframe with columns containing nested list and dictionary. I've tried combinations of zip, json_normlize and explode without success. Here's code to create example of current layout with nesting: d = { 'user_id': 'user1', 'user_emails': [['[email protected]', 'user1@home_email.example']], 'user_emails_data': [[{'type': 'emailAddress', 'id': 1}, {'type': 'emailAddress', 'id': 2}]] } df = pd.DataFrame(data = d) ![Current Output]( ![Desired output
in two steps, we can use `.explode` and `pd.json_normalize` and `.join` to re-create your df. uid = df.set_index('user_id')['user_emails'].explode().reset_index() df1 = uid.join(pd.json_normalize(df['user_emails_data'].explode())) print(df1) user_id user_emails type id 0 user1 [email protected] emailAddress 1 1 user1 user1@home_email.example emailAddress 2
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, pandas" }
Como adicionar o grupo BUILTIN\\Administrators no SQL Server para Sistemas Operacionais que não estão em Inglês? Durante a instalação da minha aplicação em um servidor, a seguinte linha é executada: using (var com = con.CreateCommand()) { com.CommandText = "CREATE LOGIN [BUILTIN\\Administrators] FROM WINDOWS"; com.ExecuteNonQuery(); } Esse código funciona bem quando executado em sistemas operacionais em Inglês, mas quando eu tentei executar em um sistema operacional em Português não funcionou. Qual seria, então, o comando correto, de forma que esse código possa ser executado em qualquer sistema operacional, independente do idioma?
Consegui resolver esse problema da seguinte forma: Para grupos conhecidos, como Administradores (Administrators) e Convidados (Guests), é possível recuperar o nome baseado no SID (Secutiry Identifier). Uma lista de SIDs conhecidos está disponível aqui: Para esse caso específico, o grupo de Administradores possui o SID = "S-1-5-32-544". Assim, segue abaixo a solução final: string sidBuiltinAdmins = "S-1-5-32-544"; string builtinAdmins = new System.Security.Principal.SecurityIdentifier(sidBuiltinAdmins).Translate(typeof(System.Security.Principal.NTAccount)).ToString(); using (var com = con.CreateCommand()) { com.CommandText = string.Format("CREATE LOGIN [{0}] FROM WINDOWS", builtinAdmins); com.ExecuteNonQuery(); }
stackexchange-pt_stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "c#, sql server, segurança" }
Problem with binomial coefficients? I am trying to find the sum of $$\sum_{x=0}^{n-2}\left (\frac{1}{x+1}{2x \choose x} \cdot \frac{1}{n-x-1}{2n-2x-4 \choose n-x-2}\right)\;.$$ I am told the answer is $$\frac{1}{n}{2n-2 \choose n-1}$$ Could someone show me how this is derived? I applied the binomial coefficients but am not getting anything near the answer. Attempt: $$\frac{1}{x+1}{2x \choose x} = \frac{(2x!)}{(x!)(x!)(x+1)}$$ $$\frac{1}{n-x-1}{2n-2x-4 \choose n-x-2} = \frac{(2n-2x-4)!}{(n-x-2)!(n-2-x)!(n-x-1)}$$ I then tried to sum the product but it seems too complicated to be reduced. Please help.
This is the recurrence formular for the Catalan numbers. Let $C_x=\frac{1}{x+1}\binom{2x}{x}$ be the x-th Catalan number. Then what we want to show is $C_n=\sum_{x=0}^{n-2}C_{x}C_{n-x-2}$, and this has been treated in, for example see this wiki article.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "sequences and series, number theory, binomial coefficients, binomial theorem" }
MapServer symbology: how to draw a line inside polygons following the outline? Is it possible to create a symbology in MapServer/Mapfiles that would draw a line following the outline of the polygon, inside the polygon? Example with a simple rectangle: ![enter image description here]( I can't find any info in the doc for this kind of symbology...
The closest hit is probably geomtransform-buffer < Unfortunately it does not work for you because by the documentation > GEOMTRANSFORM buffer returns the buffer of the original geometry. The result is always a polygon geometry. > > GEOMTRANSFORM (buffer ([shape], buffersize)) > > Note Negative values for buffersize (setback) is not supported. If your data comes from spatial database a workaround could be to duplicate the layer and use negative buffer in the SQL of the DATA line of the new LAYER.
stackexchange-gis
{ "answer_score": 1, "question_score": 2, "tags": "mapserver, mapfile" }
Not able to set Launch Image in iOS I am a newbie in iOS. I want to set Launch Image in my app. And I'm using Asset Catalog. And I know I have to drag and drop the image to the boxes that shows up when I'm using Asset Catalog. But a weird thing which is happening at that time is when I'm trying to drag-drop, it just comes back . As if Xcode is telling me NO PLACE HERE. Xcode doesn't let me set my Launch Images. I'm not able to DROP my images in those boxes. And I know the sizes of my images are quite correct. 640*960, 640*1136, 750*1334, 1242*2208.(And I don't want to use LaunchScreen because it only supports iOS 8 and later.) It's even more weird that people are down voting without even telling the reason. (If you are not good enough to help at least don't discourage newbies)
Got the solution. Just answering my question so that if anyone is having same problem then here is the solution. My problem was because by mistake I was using images of "jpg" format where in fact I should have used "png" . Now I'm using "png" and it works perfect.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, objective c, xcode, launchimage, launch screen" }
How to add month or year or day to the selected date in c#? DateTime ct = DateTime.Now.Date; ct.AddMonths(5); I am trying to get next 5th month from the current date. This code is not working for me.
`AddMonths` does not affect the original object, it returns a new object (MSDN.aspx)). You need to assign the result: DateTime ct = DateTime.Now.Date; DateTime future = ct.AddMonths(5);
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": -1, "tags": "c#, asp.net" }
To Find Colors Different in Two Images? I want to find the color group of blue removed from Image 2 compared to Image 1. Image 1 and Image 2 ![enter image description here]( ![enter image description here](
i just did it manually ... another way to detect the colors is to make any shape - brush . etc and color this thing with the eyedropper ( normal eyedropper ) and the difference will be that you can zoom in as much as you want to detect any colors you want .. like this example i made a various blue brushes and chose them with the mask then inverted the mask ...![enter image description here](
stackexchange-graphicdesign
{ "answer_score": 1, "question_score": -1, "tags": "adobe photoshop, image processing" }
issue with sum of values for similar keys in ruby I have the following array [["a", " 3"], ["a", " 5"], ["b", " 5"], ["c", " 2"], ["a", " 5"], ["a", " 5"], [ "b", " 4"], ["c", " 1"], ["c", " 2"], ["d", " 3"]] I am looking to get the following output [["a", "18"], ["b", "9"], ["c", " 5"], ["d", "3"]] 18 for key 'a' and the sum of all values 3+5+5+5 I have the following code ary.group_by{|a, b| a} and I am getting the following output {"a"=>[["a", " 3"], ["a", " 5"], ["a", " 5"], ["a", " 5"]], "b"=>[["b", " 5"], [ "b", " 4"]], "c"=>[["c", " 2"], ["c", " 1"], ["c", " 2"], ["c", " 3"]]} I tried doing the merge after grouping them by the keys and then sum the values after the merge, but I am getting an error! Could you point me in the right direction.. Thank you!
With a functional approach: pairs.group_by(&:first).map do |key, groups| [key, groups.map { |k, v| v.to_i }.reduce(:+)] end #=> [["a", 18], ["b", 9], ["c", 5], ["d", 3]] Using Facets: require 'facets' pairs.map_by { |k, v| [k, v.to_i] }.map { |k, vs| [k, vs.reduce(:+)] }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "ruby, arrays, hashmap" }
Can't correctly save a Pandas dataframe that contains a column with sets I have a dataframe that contains a column with sets. When I save the dataframe using `.to_csv()` and then re-open it with `pd.read_csv()`, the column that contained sets now contains strings. Here is a code example: df = pd.DataFrame({'numbers':[1,2,3], 'sets':[set('abc'),set('XYZ'),set([1,2,3])]}) print(type(df.sets[0])) # Type = set df.to_csv('xxx/test.csv') df = pd.read_csv('xxx/test.csv', header=0, index_col=0) print(type(df.sets[0])) # Type = str Is there a way to avoid the type changing ? I can't find which parameter from either `.to_csv()` or `pd.read_csv()` controls this behavior. The only way I found to get around this problem is by using pickle but I'm guessing there is a way of doing it with Pandas.
Do you know what a csv file is? It is just a text file. You can open it with vi or notepad to make sure. That means that what is saved in a csv file is just a text representation of the fields. `read_csv` does its best to convert back integer and floating point values. It can even find date if you use the `parse_date` parameter. Here you could use `ast.literal_eval` as a custom converter: import ast ... df = pd.read_csv('xxx/test.csv', header=0, index_col=0, converters={'sets': ast.literal_eval})
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, pandas" }
Float:left e float:right em resoluções menores Eu tenho o componente 1 em `float:left` e o componente 2 em `float:rigth`, , porém o problema ocorre quando em resolução menores o componente 2 fica a baixo do componente 1 voltado pro lado direito e o componente um 1 voltado pro lado esquerdo. Meu objetivo é que em resoluções menores o componente 2 ficar alinhado com o outro ao lado esquerdo. Esclarecendo melhor o componente fica abaixo do outro, em resoluções menores um voltado pro lado esquerdo o outro pro lado direito. Também lembrando que não posso dar `float:left` pros 2, se não vai ficar 1 abaixo do outro em resolução maiores.
Essa questão se deve ao fato de que a soma do tamanho dos dois elementos é grande demais para caber na largura da tela, e por isso há essa quebra de espaço. Já que seu problema está na exibição em uma tela de celular, eu sugiro que você use media queries para aperfeiçoar o seu sistema em relação a exibição na tela de celulares. body { margin: 0; } .left { float: left; background-color: green; } .right { float: right; background-color: red; } @media only screen and (max-width: 480px) { .right, .left { display: block; float: none; } } <div> <div class="left"> Left is the left choice :D </div> <div class="right"> Right is the right choice :3 </div> </div>
stackexchange-pt_stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "css" }
Bash - Put process in the background How can I put a process into the background in a script? I tried this but it does not work: !#/bin/bash vi &
Vi has to be called to the foreground to interact with it: #!/bin/bash vi & pid=$! fg for times in {1..600} do kill -0 "$pid" || break sleep 1 done kill "$pid" reset Also, in this case, we have a loop 600 times to wait 1 second so that we can check if `vi` is still running. If not, then we can stop waiting and continue with the script. In addition, this explains why `reset` is used at the end.
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 1, "tags": "bash, process" }
Can someone explain hashes in Perl? Main Function: my %hash = {'inner1'=>{'foo'=>5}, 'inner2'=>{'bar'=>6}}; $object->State(0, %AMSValues); Sent to: sub State { my ($self, $state, %values) = @_; my $value = \%values; From what I know one should be a hash and the other is a pointer, but... !Hash Values It doesn't look like the picture is working so, $value = $value->{"HASH(0x52e0b6c)"} %values = $values->{"HASH(0x52e0b6c)"}
`use warnings;` always. Your: my %hash = {'inner1'=>{'foo'=>5}, 'inner2'=>{'bar'=>6}}; is incorrect; `{}` generates an anonymous hash reference, and %hash gets a single key (that hash reference stringified) and a value of undef. You wanted: my %hash = ('inner1'=>{'foo'=>5}, 'inner2'=>{'bar'=>6}); As far as passing to subroutines goes, you can't pass hashes; code like you show flattens the hash into a list and then reassembles a hash from `@_`, but that will be a separate copy. If you actually want the same hash, you must pass a hash reference instead.
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 3, "tags": "perl, function, pointers, hash" }
Change vertical position of strike-through? I'm applying the strikeout tag: <s>$5,000,000</s> But the line is too low.. .it's about 1/4 from the bottom rather than through the middle. Any way I can modify this so it goes a bit more through the middle?
You can't do it with the strike tag OR the `text-decoration:line-through` style. The line position is built-in. You could roll your own style for that, but it would be a huge PITA.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 23, "tags": "html, css, vertical alignment, strikethrough" }
Missing Master Pages when using Web Deployment Project I am trying to deploy an ASP.NET 3.5 Web Application to my production server and I am using the Web Deployment Project for this purpose. I have a folder named MasterPages in the root of the application which contains all the master page files. When I build this project in the release mode and deploy it on to the server I am getting the below error message: **Directory 'C:\inetpub\wwwroot\MasterPages' does not exist. Failed to start monitoring file changes.** I am using ASP.NET AJAX and the ToolkitScriptManager is on the master pages. I have noticed that the MasterPages folder is missing from the release build. Can anyone help me with this?
The actual problem was with the CombineScripts property of the ToolkitScriptManager. It was set to true but when I set it to false everything works.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "asp.net, master pages, web deployment project" }
Somar horas com o plugin Final Countdown Estou a fazer um sistema de contagem regressiva e estou a usar "The Final Countdown jQuery" $('#clock').countdown('2015/02/16', function(event) { $(this).html(event.strftime('%D dias %H:%M:%S')); }); <script src=" <script src=" <div id="clock"></div> O meu problema é que preciso de adicionar +21 horas a cada evento (ao resultado), mas não consigo adicionar da forma que esta função é feita.
Para adicionar horas ao resultado você pode usar `new Date`. Você pode usar diretamente o `new Date()` no primeiro parâmetro do `countdown` com um formato mais que seja reconhecido pelo `Date.parse` como o _ISO 8601_ , leia em < Mas se você quiser manter o formato de `string` para facilitar sem necessitar passar um parâmetro mais complexo (como o ISO por exemplo) então você pode usar os sua `string` combinada com `split` e `new Date(ano, mês[, dia[, hora[, minutos[, segundos[, milesegundos]]]]]);`: var endIn = '2015/02/16'; var sumHours = 21;//Soma 21 horas var endInV = endIn.split("/"); var withSum = new Date(endInV[0], endInV[1] - 1, endInV[2]); withSum.setHours(withSum.getHours() + sumHours); $('#clock').countdown(withSum, function(event) { $(this).html(event.strftime('%D dias %H:%M:%S')); }); <script src=" <script src=" <div id="clock"></div>
stackexchange-pt_stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "javascript, jquery" }
Gmail app: How can I view the email addresses? In the gmail app, how can I view the actual email addresses an email has been sent to, rather than just the name. Sometimes the person in question has more than one email address and it would be useful to see which email address was used. The only method I've come up with so far is to hit reply all and then scroll around the cc: field, but that is clunky, particularly if there are quite a few recipients. Any better options? I am using Android 1.5 on a T-Mobile Pulse (aka Huawei U8220).
The latest version of the Gmail app (it has not been released yet, but you can find a copy of a leaked official APK floating around somewhere) has this feature. It adds a "more details" link on every email header so you can see the actual email addresses used. I'm not sure whether this version will work on 1.5 and up, as Google hasn't said anything yet. I know that part of their work in 2.2 was better separating the Google apps like Gmail from the rest of the platform, so that they could ship updates through the Market. So it's possible that this will only become available for 2.2.
stackexchange-android
{ "answer_score": 7, "question_score": 6, "tags": "email, gmail, 1.5 cupcake" }
Regular expression value update I had written the below regular expression string validnumber = @"^[a-zA-Z]{2}[0-9]{7}(?:-[0-9]{5})?$"; This will allow the numbers like "AA1234567" and "AA1234567-12345". I want to allow below all formats AA1234567? AA1234567?? AA1234567??? AA1234567???? AA1234567-? AA1234567-?? AA1234567-??? AA1234567-???? Can anyone please help me how can i write that
Try this: ^[a-zA-Z]{2}\d{7}(?:-?\d{1,4})?$ Explanation Updated as per the comments
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, regex" }
Button_to scroll down to specific section At the top of the user's profile I have this button: <%= button_to 'Make a detailed enquiry', user_path(@user), :class=>"enquirySection", :method => :get %> Then at the very bottom of the page I am rendering a form in which the viewer can make an enquiry: <div class="enquirySection"> <%= render "enquiries/form" %> </div> I want the user to be scrolled down to this form when (s)he clicks on the button so I added the ":class=>"enquirySection"" and "div class="enquirySection"". It doesn't work. I tried something similar to that but I think it does not related to my case. Any clue of how is this done in Rails with button_to? Thank you.
You don't need a class, but an `id` try <%= button_to 'Make a detailed enquiry', user_path(@user, anchor: :enquirySection), :method => :get %> or simply <%= link_to 'Make a detailed enquiry', user_path(@user, anchor: 'enquirySection) %> and then <div id="enquirySection"> <%= render "enquiries/form" %> </div> would do the job.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, ruby on rails" }
How to add conditionally a `Button` to a `Toolbar` `Form` `Component`? I have created a `Form` that is set to function as the `Toolbar` `Component` of a mobile application that I am working on. I want to add a `Button` to it conditionally, depending on which `Form` screen is the `Toolbar` being added to. I have tried the following but does not work: `if(aForm.getTitle().equals("Target Form Screen's Title"))` `aForm` is the `Form` to which the `Toolbar` is currently being added to. It is supposed to trigger the conditional when the `Form` title matches the target `Form` screen.
You can compare to the title in this way and it could work but generally it's a good practice to separate the UI and specific strings from the state. So you should have a separate class that controls the application state and decides what should be added. If you need some state within the UI you can use `putClientProperty` and `getClientProperty`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "codenameone" }
Why does a filter base uniquely define a filter? Why does a filter base uniquely define a filter? We define the filter base $\mathcal B$ of the filter $\mathcal F$as: $\forall F \in \mathcal F \ \exists \ B \in \mathcal B: B\subset F$ So why can $\mathcal B$ be the filter base of at most one filter?
Let $\mathcal{F}_1$ and $\mathcal{F}_2$ be two filters that have $\mathcal{B}$ as a base. Recall again that $\mathcal{F}$ has $\mathcal{B}$ as base iff $\mathcal{B} \subseteq \mathcal{F}$ and $\forall F \in \mathcal{F} \exists B \in \mathcal{B} : B \subseteq F$ Then $F \in \mathcal{F_1}$ means there exists a $B \in \mathcal{B}$ such that $B \subseteq F$. But as $\mathcal{B} \subseteq \mathcal{F_2}$ as well, the filter axioms imply $F \in \mathcal{F}_2$ as well. This shows $\mathcal{F}_1 \subseteq \mathcal{F}_2$ and the reverse inclusion is proved symmetrically. Hence equality ensues.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "elementary set theory, filters" }
Android - Unit testing using Instrumentation Framework I have recently started testing for my android application using Instrumentation framework. I have an Activity A which calls out an AsyncTask in its onCreate() method. So the problem is, all of my test-cases executes one after the other and does not wait for AsyncTask to get completed. So how can I implement the thing that waits until the thread has been finish and then continue with other test cases? Thanks
Depends a lot on how you're doing things. You could set the test thread waiting (using `wait()` or a `CountDownLatch`) and notify it when the AsyncTask finishes.. to do that simply call a protected method within the Activity after the AsyncTask is finished and override that method within your test case to notify the test thread.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, testing, instrumentation" }
How many Dogecoin-satoshis will ever exist? In Bitcoin, there will only ever be ~21,000,000 coins (slightly less, technically, but I'll just use 21 million for easy calculation). Each bitcoin is 10^8 satoshis. This means there be a maximum: 2,100,000,000,000,000 satoshis * What is the equivalent number for Dogecoin? * Is it larger than the maximum 64 bit unsigned integer?
Dogecoin has no maximum, because it mints 10k dogecoins per block, forever. But to answer the _spirit_ of your question, there are 100 million indivisible parts to a dogecoin. You can see that here. static const int64_t COIN = 100000000; There are currently 97 billion dogecoins. This is a bit more than 2^63 satoshis. > Is it larger than the maximum 64 bit unsigned integer? No, but it wouldn't matter if it was. There isn't a limit of 2^64 satoshis on the total money in Bitcoin (or altcoins). However, there is a limit of 2^64 satoshis _per output_.
stackexchange-bitcoin
{ "answer_score": 3, "question_score": 3, "tags": "dogecoin, satoshi, reward schedule" }
restart syslog in cloudlinux I've recently modified the /var/log/secure log to test a remote log aggregation tool and that, of course, prevented syslog from further writing to that log. **Question** : How do i restart `syslog` on this `CloudLinux` box I have? I'm used to syslog being under `/etc/init.d/syslog` for other Linux distros and just a simple restart command does it however on `CloudLinux` syslog is under `/etc/logrotate/syslog` and, as far as I could read, it's part of a cron job now or something like that.
On CloudLinux 6 (as well as CentOS6) it is /etc/init.d/rsyslog
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "linux, centos, cloud, centos6" }
Given matrix $A$, find the number of solutions of $X^2 = A$. > Given the matrix: > > $$ A = \begin{pmatrix} 0 & 0 & 1 \\\ 0 & 1 & 0 \\\ 1 & 0 & 0 \\\ \end{pmatrix} $$ > > Find the number of solutions (in $M_3(\mathbb{R})$) of the equation $X^2 = A$. I tried writing $X$ as: $$ X = \begin{pmatrix} a & b & c \\\ d & e & f \\\ g & h & i \\\ \end{pmatrix} $$ And then I multiplied $X$ by itself and created a system with the terms of $X^2 = A$, but $X^2$ is very messy and I got stuck. I couldn't solve this problem. Is there another (and possibly better) approach to this?
The determinant of $A$ can be seen to be $-1$, so if $X^2=A$, then $\det(X)^2=\det(A)=-1$, which is impossible.
stackexchange-math
{ "answer_score": 6, "question_score": 0, "tags": "linear algebra, matrices, matrix equations" }
why does $P(X) = X^3+X+1$ have at most 1 root in $F_p$? why does $P(X) = X^3+X+1$ has at most 1 root in $F_p$ ? I could fact check this on Sage for small values of $p$. For example $p=5$ or $7$ or $19$; there is no root. If $p = 11, 2$ is the only root. If $p = 13, 7$ is the only root. If $p = 17, 11$ is the only root. I also realize that there can't be only 2 roots a1 and a2 because a3 = -(a1+a2) will be a root as well.
It's not true. $3$ and $14$ are roots in $F_{31}$.
stackexchange-math
{ "answer_score": 4, "question_score": 2, "tags": "polynomials, finite fields" }
flash 10 orthographic projection I've been playing a bit with the new flash 10 3d possibilities, and found out that rotating a sprite in 3d is fairly easy: var card:Sprite = new MyCard() card.x = 100 card.y = 100 card.z = 200 card.rotationX = -60 addChild(card) Simple and effective, this shows the card rotated with perspective. Now I want to use an orthographic projection, and I have no clue where to start. DisplayObject does have a perspectiveProjection member, but that can only make perspective projections of course. Maybe I should use the transform.matrix3D? I'd think this should not be too hard, but I don't see how to tackle this issue. UPDATE: as one of the comments suggests: setting the perspectiveProjection.fieldOfView to something close to 0 (10 actually produces a nicer result in my setup than something like 0.1) you get a projection that is nearly orthographic, that might be good enough.
I finally got it working. var m:Matrix3D = new Matrix3D() var v3:Vector.<Vector3D> = new Vector.<Vector3D>(3); v3 = m.decompose(); v3[2] = new Vector3D(1,1,0); m.recompose(v3) transform.matrix3D.appendRotation( -90, Vector3D.X_AXIS ); transform.matrix3D.appendRotation( -45, Vector3D.Y_AXIS ); transform.matrix3D.appendRotation( 35.264, Vector3D.X_AXIS ); transform.matrix3D.append(m) Now any element added to the sprite that has this transform applied to it will show up in isometric projection. (that 35.264 number is an approximation see <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "flash, actionscript 3, projection, orthographic" }
Why is complex conjugate transpose the default in Matlab if A matrix has complex element and I want to transpose A to A' using the command `>>A'` Why it is design that `a+bi` be transformed into `a-bi` ? What it use for?
From here: > for complex matrices, it is almost always the case that the combined operation of taking the transpose and complex conjugate arises in physical or computation contexts and virtually never the transpose in isolation (Strang 1988, pp. 220-221). In matlab if you want to transpose without conjugating use `.'`.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 6, "tags": "matlab, matrix, transpose, complex numbers" }
Removing cached Query from Redis using django-cacheops I am using django-cacheops to cache a Query. And updating some in the same instance with some different API call now I want to remove this cached Query from Redis. This is **API-1** users = User.objects.cache().get(user_id = user_id) Now I am updating my user with API-2 user = request.user if user.is_sms_read: user.is_sms_read = False else: user.is_sms_read = True user.save() Now I am fetching the data with same API-1 and it is giving me the data cached data I want if I call the API-2 it should clear the cache and fetch new data.
The official documentation of **django-cacheops** states that it listens on model signals and invalidates "appropriate queries". But it won't invalidate queries that doesn't seem to be affected by the change. It looks like a bug to me as the queryset for API-1 should be affected by the change in API-2. But meanwhile you can also try invalidating the cache forcefully by using from cacheops import invalidate_obj user = request.user if user.is_sms_read: user.is_sms_read = False else: user.is_sms_read = True user.save() invalidate_obj(user)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "django, django cache" }
Get a list of all gitignore files in my current branch, unrelated to their tracking or modification state I asked this question already again, but it was closed prematurely, since the given link did not answer my question as explained. I have a Git repo and would like to get a list of files, which are ignored by Git in my current branch, and those which are not, unrelated to if they are tracked, or not, or what their state is. I found `git-check-ignore`, but my repository has a few thousand files, and checking it on a per file basis takes simply too long to spawn a process for each file. git check-ignore /file/to/foo Does Git have another command that allows me to get a list of files which are ignored by git?
I think the command you're looking for is `git ls-files -ioc --exclude-standard`. That command will list files using the standard exclude paths that are either tracked (in the index) or untracked. Even if that's not the exact invocation that you're looking for, `git ls-files` is the tool which is most likely to give you an efficient answer. It also has the `-z` option which is useful for odd filenames and scripting use.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "git, gitignore" }
Appropriate control for page like swiping I currently have a UIScrollView which has a content size equal to about 50 pages, each one the size of the application view. I have implemented scrolling by using paging and at all time keep current, previous and next page in memory, while the rest are created when required, e.g. when one swipes forward, the old 'previous' view is released and a new 'next' view is loaded. The new pages are loaded and old released when 'scrollViewDidEndDeaccelerate' is called. The disadvantage with this is of course that the page needs to settle completely before a new page swipe may begin. Is there a more efficient way of doing this with a different type of control? UITableView? I am looking for solutions with other type of controls - not UIScrollView implementations with e.g. placeholder images and loading high res on demand.
Sounds like you are on the right track as predictive caching is about the only idea I can offer...which you are doing. Maybe checking available memory and loading to a certain percentage of that might help, with caveat that you monitor the low memory warning and dump items that are the farthest from the current view location.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "iphone, cocoa touch, ipad" }
How i can copy reverse of a map to another map? For example map1 is gaving values 1 to 10 with some address(begin to end). i want to have values 10 to 1 with corresponding address in map2(begin to end) map<long , int* > v; map<long , int* > rv; int i,a[10]; for(i=0; i<10; i++) { a[i] = i+1; v.insert(pair<long, int *>(i+1,&a[i])); } itr = v.begin(); while(itr != v.end()) { cout << itr->first << " "<<itr->second; cout << endl; itr++; } rv.insert(v.rbegin(),v.rend()); cout << "copied array: "<<endl; itr = rv.begin(); while(itr != rv.end()) { cout << itr->first << " "<<itr->second; cout << endl; itr++; } i tried above one but am getting values 1 to 10 only..my expected values 10 to 1. please help me to find out....
STL map is an ordered container. The order of items that you get during the iteration is independent of the order in which you insert the items into the container. The order of iteration is determined by two things: * The value of the key, and * The `Compare` class passed as the template parameter to the `map` You can iterate the map in reverse order (your code snippet shows that you already know how it is done). The performance penalty for reverse-iterating a map, if any, is negligible. You can also provide a non-default `Compare` (`std::greater<long>` instead of the default `std::less<long>`) to have the default order of iteration altered.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 2, "tags": "c++, stl, dictionary, iterator, copy" }
Dynamic Type definition for a Char Field with variable length For internal usage I need to define a structured type with one of the fields being a char-field with a variable length. Something like this (I hope this example clarifies my problem): DATA: lv_type TYPE char7. lv_type = 'char128'. "The actual length will be determined during execution of the program TYPES: BEGIN OF ty_satzcounter, satza TYPE zedist, addit TYPE (lv_type), "<----- Something like this (obviously, it doesn't work like " this, but I think it clarifies my question) menge TYPE int1, END OF ty_satzcounter. DATA: lt_satzcounter TYPE TABLE OF ty_satzcounter, ls_satzcounter TYPE ty_satzcounter. ... ...
This kind of dynamic typing is not possible, but for your purpose, character type with dynamic length, there is the type `string`: TYPES: satza TYPE zedist, addit TYPE string, ...
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "dynamic, types, char, abap" }
Mounting a linux image built with "dd" on Mac OSX 10.7 I recently did a ssh root@myserver "dd if=/dev/xvda " | dd of=/<localpath>/myimage.img as instructed by my VPS server docs at linode. I did this before to another linux system and mounted it perfectly by doing sudo mount -o loop myimage.img mountdirectory But on my mac osx 10.7 I get the following error. mount: You must specify a filesystem type with -t. I tried -t ext, -t ext3, -t ext4 but all failed with an error like this mount: exec /System/Library/Filesystems/ext4.fs/Contents/Resources/mount_ext4 for /<mount directory>: No such file or directory How do I fix this?
Get VirtualBox and install Ubuntu on it. Pass the .img file to the VM as a disk. Edit the fstab in the VM to mount the disk image.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 6, "tags": "mac osx, filesystems, migration, dd, disk image" }