INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
SimpleDateFormat returning the wrong date in Java I'm having an issue with SimpleDateFormat in Java. My code is returning the wrong date. Help please. String date_str = "Tue Mar 08 09:44:55 EST 2022"; Date date = new SimpleDateFormat("EEE MMM D HH:mm:ss z yyyy").parse(date_str); // Output: Sat Jan 08 14:44:55 GMT 2022
`d`, not `D` for the day of the month. `D` is the day in the year, so 8 is the 8 of January. String date_str = "Tue Mar 08 09:44:55 EST 2022"; Date date = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy").parse(date_str); // ^---Here // Output: Tue Mar 08 15:44:55 CET 2022 Check the full list of patterns here.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, simpledateformat" }
Select Group based on condition - Crystal Report I have a report where the data is displayed based on the value of a combobox, how do I display all the data if the combox is empty? I have done the below: Under Select Expert -> Group if {?@Div} <> " " then {SP;1.Col1} = {?@Div} Thank you
Assuming the {?@Div} var contains an empty string "if combobox is empty" the condition could look like this: {SP;1.Col1} = {?@Div} Or {?@Div} = '' You might want to add an "All" group to the selection, then it would be something like: {SP;1.Col1} = {?@Div} Or {?@Div} = 'All'
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "visual studio 2010, crystal reports" }
Kotlin get string from resources by index I'm new to kotlin and i'm stuck at trying to access a string array from my resources. I have a string array in my strings.xml file and i want to extract a string from it by index. I'm using a spinner for selecting the index: override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, id: Long ) { titleTextView.text = R.array.content[position] } When i try to pass the position parameter as my array index, i get an error telling me i have no get method for array access. Any help would be appreciated.
Instead of using `R.array.content` take the whole string inside a string array. val stringArray = getResources().getStringArray(R.array.(your array name)); then make use of this stringArray to access individual elements using the position.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, arrays, kotlin" }
Map Search Results I am trying to provide useful information on an area to users based on a search term and their location. I thought googles geo api would return a best match list of results for a query such as "swimming+pool+'my location' that I could then place an annotation for each result in my map view but it only returns one best match location. How can I go about doing this?
The Google gecoder only handles addresses. Google provide a completely separate API which will geocode business names and categories, the Google AJAX Search API in Local Search mode
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "iphone, iphone sdk 3.0, google maps, mapkit" }
Supporting hyperplance theorem proof. I've read the proof of supporting hyperplane theorem here (page 5 in pdf) I have some questions regarding the proof, that are not clear for me now. Also I include the proof image here: ![enter image description here]( 1. Why $\\{x_k\\} \nsubseteq C : x_k \rightarrow x.$ exists? 2. Why the sequence $a_k = \frac{x_k -z^*_k}{||x_k - z^*_k||} \text{ for } k \ge 1.$ is bounded? 3. How from projection theorem result: $a^T_kz^*_k=a^T_k(z^*_k-x_k) + a^T_kx_k < a^T_kx_k \text{ } \forall k, $ we can say that $a^T_kz < a^T_kx_k \text{ } \forall z \in C.$?
1. Because $C$ is closed and either $x_0 \in \text{Bd}(C)$ (so all neighbourhoods of $x_0$ intersect $\Bbb R^n\setminus C$) or $x_0 \notin C$. In either case $x_0 \in \overline{\Bbb R^n\setminus C}$ and closure is sequential closure in metric spaces. 2. $\|a_k\| = 1$ for all $k$, so that's clear. 3. Combine the two equations: $a^T_kz^\ast \le a^Tz^\ast_k < a_k^Tx_k$ so $a^T_kz^\ast < a_k^Tx_k$ follows. ($a \le b < c$ implies $a < c$ in any linear order).
stackexchange-math
{ "answer_score": 1, "question_score": -1, "tags": "elementary set theory, optimization, proof explanation, convex optimization, compactness" }
Printing out array elements based on elements contents (Java) I have an array of String like so: array[0] = "1 4" array[1] = "2 0" array[2] = "2 1" array[3] = "4 2" and would like to process the array and print out the second part of the array element on the same line when the first part of the array element have duplicates, like this: 4 0 1 2 I've been trying ages to work this out but I keep getting more confused... Processing is based on consecutive lines.
It looks like a straight-forward Java coding problem to me: String lastKey = null; for (String str : array) { String[] parts = str.split(" "); if (parts[0].equals(lastKey)) { System.out.print(" "); } else if (lastKey != null) { System.out.println(); } System.out.print(parts[1]); lastKey = parts[0]; } System.out.println(); This assumes that your input file is ordered on the first field ...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java" }
Script de backup do cPanel movendo arquivos para pasta errada Euj tenho este script para backup full do cPanel que funciona bem: (< Eu segui exatamente as configurações da orientação, criei duas pastas `/backups/backup_daily` e `/backups/backup_monthly` e os cron jobs correspondentes. O problema é que o backup mensal está sendo sempre movido para a pasta do backup diário. E mesmo que eu mova manualmente o arquivo de backup mensal para a pasta correta dele, quando o script roda novamente o arquivo volta ser movido para a pasta diária, misturando-se assim com os demais arquivos, incorretamente. Eu achoque o problema está na linha 47 do **backup.sh** : `find $HOME -type f -name "backup-*" -exec mv {} $BACKUP_FOLDER/ \;` Alguém saberia me dizer como consertar isso?
Resolvido mudando a linha 47 para: find $HOME/* -maxdepth 0 -type f -name "backup-*" -exec mv {} $BACKUP_FOLDER/ \;
stackexchange-pt_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "bash, backup, cpanel" }
Por que o header User-Agent retorna sempre "Mozilla /5.0" independente do navegador? Sei que no PHP podemos acessar um `header` chamado `User-Agent` e, assim, descobrir informações sobre o sistema operacional e navegador, utilizado pelo cliente. A única coisa que não entendo é que sempre aparece "Mozilla /5.0" (mesmo que eu utilize outro navegador, que não o Firefox). Exemplo: print_r($_SERVER['HTTP_USER_AGENT']); Saída: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101 Firefox/39.0 Essa string acima foi retornada do PHP. Estava utilizando `Firefox 39.0`nos meus testes. Porém, se eu fizesse isso com outro navegador, me retornaria o "Mozilla/5.0" Então aqui vão duas perguntas (estarei satisfeito se apenas a primeira for respondida): * Por que é que esse header retorna o nome do navegador, também retorna "Mozilla /5.0"? É outra coisa que não tem relacionamento nenhum com Firefox?
Eu não sei responder em detalhes. Estou respondendo apenas para ter uma resposta que não é errada. O motivo dos navegadores usarem isto deve ser mais ou menos o mesmo motivo do que alegam o Windows 10 não chamar Windows 9. Programadores ruins ou preguiçosos ou maliciosos usam a _string_ `Mozilla` para fazer certas verificações em seus códigos e saber se pode executar alguma coisa. Se usasse o próprio nome, um monte de código existente que poderia rodar normalmente não funcionaria por um `if` mal colocado. Então todos navegadores fingem serem o Mozilla para não serem prejudicados por códigos ruins. Na verdade a coisa é pior porque eles gostam de por várias palavras para se passar por vários navegadores.
stackexchange-pt_stackoverflow
{ "answer_score": 4, "question_score": 5, "tags": "php, http, http headers, user agent" }
How to change hover color on bulk-action-selector-top and bottom on wordpress admin? i want to change this hover color !enter image description here i tried via css: #bulk-action-selector-top{ color:#FFF; } but this not working. How to change it? thank you
Sorry to disappoint you, but there is no easy way to do it and no possible way with css. Here is a similar thread in StackOverflow, that has the issue discussed: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Is it good programming to have lots of singleton classes in a project? I have a few classes in a project that should be created only once. What is the best way to do that?, 1. They can be created as static object. 2. Can be created as singleton 3. Can be created as global. What is the best design pattern to implement this? I am thinking of creating all classes as singleton, but that would create lot of singletons. Is it good programming practice to have lot of singletons? What are the pros and cons for using singletons?
Take a look at Steve Yegge's blog post about this - Singleton Considered Stupid
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 4, "tags": "c++, singleton" }
What is the equivalent of DataContext in entity framework? Linq to SQL has this very simple model: DataContext and attributes [Table] and [Column] and no need for a config file. But I understand Linq2SQL does not have a future. How do I do something equivalent in entity framework? (Equivalent = no config file)
In EF 4.1 Code-First you can configure your mapping in a fluent way as opposed to a config file. It is convention based so it will infer lot of thing from your model (eg: Table column are automatically mapped to properties if both names match).EF Code First Model
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "entity framework, linq to sql" }
IBM watson integration with instagram I'm trying to develope a chatbot to Direct Instagram. Anybody knows if is possible to integrate Watson Assistant (Chatbot) with Direct Instagram? I saw that I had a post from 3 years ago, but recently the telegram integrated the direct into the messenger. I would like to know if anyone has any solutions
you can try to do it via http on node red and pull this request through chatfuel
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "instagram, integration, ibm watson" }
How to access a class with protected constructor from another class I have a class with protected constructor. Is there any possibilities to access this class from another class Base Class : public class BaseClass { private static ClassA _classA = new ClassA(); private static ClassB _classB= new ClassB(); protected BaseClass(ClassA _classA, ClassB _classB) { _classA = classA; _classB= classB; } This is my Derived Class : public class DerivedClass : BaseClass { } Derived class require to pass parameter. How to solve it.
public class DerivedClass : BaseClass { public DerivedClass(ClassA classA, ClassB classB) : base(classA, classB) { } }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "c#, class, inheritance, parameters" }
Solspace Freeform: return to anchor in page when having inline errors I have a contact form set up with Freeform and when having inline errors, I would like to return to an anchor on the page, since my form is on the bottom of the page. I tried setting inline_error_return="#contact-form", but it doesn't even add the hash to the url. Hope someone can help me out.
I think inline_error_return is the way to go, but maybe you need a complete url there, not just the anchor. In a recent site I did, I have inline_error_return="{page_url}/#job-apply-form" which works.
stackexchange-expressionengine
{ "answer_score": 2, "question_score": 0, "tags": "solspace freeform" }
How to unhook event handlers in C# I am working on a C# application that has multiple forms. When I open one of the forms I add an event listener like this: `SomeClass.MotionCompleted += new EventHandler(HandlerMethod); `. The `MotionCompleted` event is a **static event**. I have noticed that after closing this form the `HandlerMethod` still gets called when the event occurs which then causes an exception because it tries to update something on the form which doesn't exist anymore. How can the event listener exist and respond to the event even though the form doesn't exist anymore? Once `form.Close()` or `this.Close()` is called shouldn't that automatically unhook the event listeners so that they do not get called anymore?
That's the evil of static events! :) You have a managed leak there. Override the OnClosing of your form and deregister you handler: protected override void OnClosing(CancelEventArgs e) { SomeClass.MotionCompleted -= new EventHandler(HandlerMethod); }
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "c#, winforms, event handling, formclosing" }
what is the output of this "10"+20+30 ? in javascript what will be the output of this when we run this on JavaScript and whats the reason behinds that ? And the concept of this logic ? 10 is a string it is in commas and the other two are digits 20 and 30
The answer to this question will be `102030`.In the process of concatenation if a '+' sign is encountered the elements to the right will be contacted as string console.log("10" + 20 + 30) //102030 console.log(20 + 30 + "10") //5010 console.log(20 + 30 + "10" + 20 + 30) //50102030
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -6, "tags": "javascript" }
Strongly monotone and cocoercive A map $f:\mathbb{R}^n\rightarrow\mathbb{R}^n$ is $m$-strongly monotone if $$ (x-y)^{\sf T}((f(x)-f(y)) \geq m \|x-y\|_2^2 $$ for $m > 0$ and is $\delta$-cocoercive if $$ (x-y)^{\sf T}((f(x)-f(y)) \geq \delta \|f(x)-f(y)\|_2^2 $$ for $\delta > 0$. I am working on a proof where I need instead the following property: $$ (x-y)^{\sf T}((f(x)-f(y)) \geq m \|x-y\|_2^2 + \delta \|f(x)-f(y)\|_2^2\,. $$ for $m, \delta > 0$. Is there a standard name for this property, or some results? I can see that it is implied by $f$ being both $2m$-strongly monotone and $2\delta$-cocoercive, but this ends up not being useful for my problem. Moreover, I can see that it is stronger than $f$ being both $m$-strongly monotone and $\delta$-cocoercive.
The property you stated is equivalent to $f$ being _strongly monotone and Lipschitz continuous_ ; searching for this combination of terms will bring up a number of papers. It doesn't have a single-word name, since "Lipschitz strongly monotone" is short enough, and self-descriptive. Here's a justification. If $f$ is $L$-Lipschitz and $m$-strongly monotone, then $$(x-y)^{\sf T}((f(x)-f(y)) \geq m \|x-y\|_2^2 \ge mL^{-2}\|f(x)-f(y)\|_2^2$$ hence $$(x-y)^{\sf T}((f(x)-f(y)) \geq \frac{m}{2} \|x-y\|_2^2 + \frac{m}{2L^{2}}\|f(x)-f(y)\|_2^2$$ Conversely, if $$(x-y)^{\sf T}((f(x)-f(y)) \geq m \|x-y\|_2^2 + \delta \|f(x)-f(y)\|_2^2\,$$ then $$\|x-y\|_2 \|f(x)-f(y)\|_2 \geq \delta \|f(x)-f(y)\|_2^2\,$$ hence $$\|f(x)-f(y)\|_2 \le \delta^{-1} \|x-y\|_2$$
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "convex analysis, convex optimization, monotone functions" }
Find the probability that 3rd, 4th and 5th tosses are identical A fair coin is tossed $10$ times, the tosses being indipendent of each other. I have to find the probability that 3rd, 4th and 5th tosses are identical. I have no idea how to calculate. please help.
**Hint:** Two possibilities (i) three heads and (ii) three tails. What is the probability of $3$ consecutive heads? Of three consecutive tails? Add. The fact that there were $10$ tosses is irrelevant. And the fact that $3$, $4$, and $5$ are next to each other s irrelevant. We would have the same answer to "what is the probability the the $2$nd, $5$th, and $10$th tosses are identical?"
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "probability" }
css chaning the z-index is not affectable This is the result: !enter image description here see how the link is over the numbers I tried changing the z-index of the `before` element and keep making it larger, but the line keep above the numbers, could u help please? the code of the line is #progressbar li:after { content: ''; width: 100%; height: 2px; background: black; position: absolute; left: -50%; top: 9px; z-index: 0; /*put it behind the numbers*/ } this is a jfiddle <
That is because your `::before` pseudo-element (by the way, you should use `::` for pseudo-elements and `:` for pseudo-classes) is being overlaid by the `::after` pseudo-element. The solution is to set the `::before` pseudo-element to be **relatively positioned** (if you don't use relative positioning, the z-index property will be ignored) with a z-index higher than the `::after` counterpart, i.e.: #progressbar li::before { content: counter(step); counter-increment: step; width: 20px; line-height: 20px; display: block; font-size: 10px; color: #333; background: white; border-radius: 3px; margin: 0 auto 5px auto; position: relative; z-index: 2; } See modified fiddle here: <
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "html, css" }
On linux is there a commonly used / conventional sub-directory that is used for user specific program settings On linux, many programs store user specific profile settings in a hidden dot file in the users home directory. Other programs create their own uniquely named hidden dot directory and put one or more files inside their to do the same job. Is there any existing or emerging convention / common hidden dot directory (such as .settings or .profile) where developers of new programs can put their user specific profile settings to minimise the home directory clutter?
By the convention, '.config' should contain settings for a local user. Follow this answer.
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "linux, filesystems, user profiles" }
Winter 18 Community - all custom components disappeared! On my sandbox I have winter 18 now. I have played around to see all new community features, and suddenly I realize that the component list does not have any custom components: ![enter image description here]( **As you can see - no section Custom Components** Also - my existing custom components (that where added before the Winter18 upgrade) exist in current pages, but when I click on any of them to see and edit their properties, I get the following error message: > We had trouble processing the request. We've reported the problem to Customer Support with error ID: 972428812 ![enter image description here]( Last thing - I have checked my production org, and over there I can see and manage my custom component: ![enter image description here]( Is this a bug or am I doing something wrong?
Now problem is solved - it works, I do not know what happened, I did not change anything, but I can see and use all my custom components in my communities. Maybe Salesforce fixed it in the background or something...
stackexchange-salesforce
{ "answer_score": 2, "question_score": 8, "tags": "lightning aura components, customer community, community builder, lightning community, winter18" }
Basic trigonometry - Find length of side when knowing one side length and the opposite angle I have this basic trigonometry question of finding the length of "x" in the triangle Finding X. I know one side of the triangle and the opposite angle, so I figured it should be a simple case of just filling in the equations of cosine. I've tried looking at other solutions of similar problems, but I can't wrap my head around how to apply their approach to my problem. Sorry if this is way too basic, I notice it's been too long since I've used trig..
$$\tan \theta =\dfrac{\text{side opposite }\theta}{\text{side adjacent }\theta}$$ Here the $\text{side opposite }\theta$ to the angle of $6^{\circ}$ is $x$ and $\text{side adjacent }\theta$ is $3$. $$\tan 6^{\circ}=\dfrac{x}{3}\implies x=3\tan6^{\circ}$$ You can leave it like that as $6^{\circ}$ is not a special angle, if however, you can use a calculator, simply feed in the expression to get $x \approx 0.315312705798$ and you're done.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "trigonometry" }
How to create makefile in cooja? I am trying to make program for rssi measurement in cooja. Recently, I found that the makefile is a must for running the programs, but the /contiki/examples has so many examples with different makefile contents. For instance, "collect" uses certain apps in makefile. How to understand the apps and tools needed for my work? Please explain.
I'm afraid that this is a too generic question to answer here. You'll have to spend some time to learn about makefiles. Google for "writing makefiles". Then you might want to do some research, instead of letting others do you homework and come across < Oh, and before you do RSSI-Measurements in Cooja you probably want to do some research on simulation of RSSI-values - with Cooja in particular, too.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "c, makefile, contiki, rssi" }
How to display headers on multiple pages using syncfusion I have a table report which will be exported as a word document. I can print out the header in the first page only. It doesn't seem to carry over to the next page. Can anyone tell me how I can show the header data on all the pages of the word document?
The solution to this was a lot easier than I expected. All I had to do was put the header data I wanted in the header of the **Word Ddocument Template** that I wanted to use. Also in order to have the header of a table to apear repeatedly when there are multiple pages, again we go to the **Word Document Template** , select the rows you want to use as headers then right click and go to Properties -> Rows tab -> enable(check) "Reapeat as header row at the top of each page" -> click OK and save. That should do the trick!! Then use syncfusion as you usually use it to populate the table. When the data exceed to more than one page the header will be repeated on the following pages.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, syncfusion" }
What's the opposite of a greeting? > **Possible Duplicate:** > What term is used for the closing of a letter? You use a greeting when you need to open communication with someone, but is there a word for when you need to close communication? for example, note a / indicates a physical action (not just spoken words): Greetings: Hey, Hi, /salute, /wave, etc. ???? : Bye, See ya, /wave, etc.
There is a host of words for this: > goodbye, farewell, leave-taking, adieu, arrivederci, au revoir, sayonara cornbread sums them up all in _valediction_.
stackexchange-english
{ "answer_score": 7, "question_score": 8, "tags": "single word requests" }
MVC Get and Post data Sorry for the really nooby question, but this is tripping me up hard. I have a controller Inspection, with method Configure which passes a model containing 3 lists. ![enter image description here]( I know that I'm supposed to use HiddenFor to retain the information, but I don't know how to do this with lists. ![enter image description here]( I have these HiddenFor fields but they don't seem to work in retaining the information @Html.HiddenFor(model => Model.inspection) @Html.HiddenFor(model => Model.assignedParts) for (int i = 0; i < Model.ConfigList.Count; i++) { @Html.HiddenFor(model => Model.ConfigList[i]) }
Every Razor directive gets converted into html to display in the browser. In this case, your directive for Model.assignedParts will probably look something like this in html: `<input type = "text" value="List<StevenHubs.Models.Part>" />` You can see exactly what it is by running your app and viewing the source. The text that is getting assigned to value is just `Model.assignedParts.ToString()`. The simplest way to fix your problem is to change your view to just use the pieces of the model that are actually getting changed. If you want to include the list in your View, you will need to do a foreach over the list, and if the member of the list has properties, you will have to have a `@Html.HiddenFor` for each property so something like: `@foreach(var part in Model.Part) { @Html.HiddenFor(part.Property1) @Html.HiddenFor(part.Property2) }`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "asp.net mvc, post, razor, get" }
How to join NSArray elements into an NSString? Given an NSArray of NSStrings, is there a quick way to join them together into a single NSString (with a Separator)?
NSArray * stuff = /* ... */; NSString * combinedStuff = [stuff componentsJoinedByString:@"separator"]; This is the inverse of `-[NSString componentsSeparatedByString:]`.
stackexchange-stackoverflow
{ "answer_score": 316, "question_score": 127, "tags": "cocoa, string" }
How to read from an external dictionary in LaTeX? I'm wondering how to define a LaTeX command `\x` that prints "def1" when I write `\x{name1}`, reading from an external (dictionary) file having a structure like {name1}{def1} {name2}{def2} etc.
If the external file `dict.dat` is organized as \entry{name1}{def1} \entry{name2}{def2} then \newcommand{\entry}[2]{% \expandafter\newcommand\csname entry@#1\endcsname{#2}} \newcommand{\x}[1]{\csname entry@#1\endcsname} \input{dict.dat} will do what you're looking for.
stackexchange-tex
{ "answer_score": 10, "question_score": 9, "tags": "macros, external files" }
Will this go in an infinite loop? I am starting in java, so please bear with me if this sounds stupid. I am trying the below code: **First.java** class First { public static void main( String[] args ) { First f = new First(); f.print(); } private void print() { System.out.println( "Hello, World!" ); } } Within the `main` function, i re-instantiate the same class as i need to call a non-static method from within the static main method. While this works, i am wondering is this a good way to do it? And how many instances of `f` are created. How can i make sure `f` would be a `singleton`. Thanks
About the first question: Only one instance of the class `First` is created. About the second question: The singleton pattern involves using a private constructor and a factory method. You cannot create a new instance of `First` without using the `getInstance` factory method, and all calls to `getInstance` will return the same instance. class First { private static First instance = null; private First() {} public static First getInstance() { if (instance == null) { instance = new First(); } return instance; } } class Second { public static void main(String[] args) { First f = First.getInstance(); //Always the same instance of First. } }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -1, "tags": "java, static" }
no funciona la API Fetch en javascript, cuando hago fetch a mi API REST en Heroku Tengo un problema con la **api fetch** de **js** cuando intento hacer una petición `get` a una `api rest` básica que realice en **node** y la desplegué en **heroku** , para probar esta api la corri en **postman** y funciona perfectamente cuando quiero hacer un `fetch` o intento llamarla con **axios** no funciona, el **api rest** no tiene ningún error, el código de la petición es el siguiente: fetch(' .then(function(response) { return response.json(); }) .then(function(myJson) { console.log(myJson); }); Sin embargo cuando uso la función con, por ejemplo, `jsonplaceholder` si funciona **(sin el`{mode: "no-cors"}` porque por algún motivo me demanda poner ese modo)**, no se si habrá que hacer alguna configuración en **heroku** o que, para que vean el código de **backend**. > Aquí mismo dejo el repositorio <
Parece ser un problema de cors. Puedes agregar en tu servidor: Opción 1 - para permitir todas las peticiones desde cualquier origen app.use(cors()) Opción 2 - para delimitar desde que url quieres que se hagan las peticiones app.use(cors({ credentials:true, origin:[<Lista de URLs de donde haras las peticiones>] }))
stackexchange-es_stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, nodejs, express, heroku" }
If I enter a new registration number delete button should be disabled in C# windows form application If I enter a new registration number delete button should be disabled in C# windows form application Visual studio. Form is student enrollment Registration form
You can disable the delete button on form load and on change of textbox check the registration number in your database whether the registration number is available if available then delete button will be active else delete button will be disabled. * Always disable the delete button if the registration number is modified in your form. * It will be active only if the registration number is found in your database.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, windows, forms, button" }
Image caption not working correctly I am using the SlidesJS JQuery plugin to display a sliding banner along the top of a webpage. However, I am having troubles adding image captions that overlay on the images. As per the website above I create a new p with the class caption and enter my caption in that, but from what I can tell the plugin is thinking that this caption div is another slide and showing just the caption text after each of the images. You can view the page here.
You might want to check the example SlidesJS with caption. A look into your html code and see right away that you are using one div block for all the images(slides). On the example code on the link, they split the images(slides) per div so that when you need to add a caption, you simply add a child inside div.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, jquery, slidesjs" }
Laravel 4.2 Migrations - Alter decimal precision and scale without dropping column I wish to increase decimal precision and scale for a decimal column. I am aware that I can drop the column, and re-create it, but doing so will mean losing the data in the column. Is there a way using Laravel Schema::table that I can alter the precision and scale of the column without dropping it? e.g. something like: Schema::table('prices', function(Blueprint $t) { $t->buy_price->decimal(5,2); });
Just create another `migration` and in the `up` method add following code: public function up() { // Change db_name and table_name DB::select(DB::raw('ALTER TABLE `db_name`.`table_name` CHANGE COLUMN `buy_price` `buy_price` decimal(10,2) NOT NULL;')); } Also in the `down` method just set the old value so you can `roll-back`: public function down() { // Change db_name and table_name DB::select(DB::raw('ALTER TABLE `db_name`.`table_name` CHANGE COLUMN `buy_price` `buy_price` decimal(5,2) NOT NULL;')); } Then migrate as usual from the `terminal/command prompt` using `php artisan migrate`.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "laravel, database migration" }
Using macros WIN32 or _MSC_VER cross-platform I am compiling under Linux (GCC 4.4.2) and Windows VS C++ Express Edition 2008 I am currently compiling under Windows XP Pro 32 bit, and have added this to my source code. #if defined( WIN32 ) /* Do windows stuff here */ #endif However, the code in the if statement is disabled (grayed out). However if I do the following: #if defined( _MSC_VER ) /* Do windows stuff here */ #endif The if statement code is enabled. I am just wondering, what should I be using. I have seen many programmers use WIN32. However, doesn't seem to work for me. Should I be using _MSC_VER instead? Many thanks for any advice,
There is no `WIN32`. If you've seen it being used elsewhere, it's either wrong or the code is explicitly defining that macro itself somewhere. You want `_WIN32`. See < for a list of predefined macros in Microsoft's compiler.
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 13, "tags": "c" }
How can I set visibily gone on scrolling downwards? I have kept a button in my scroll view which should be visible only when I am scrolling up and should get invisible as I scroll down like in paytm. It is a simple scroll view inside a fragment. scrollBtn.setVisibility(View.GONE); scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() { @Override public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { scroll.setVisibility(View.VISIBLE); } }); scrollBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { scrollView.scrollTo(0, 0); } }); * * *
This should help you. **Code** scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() { @Override public void onScrollChange(View view, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { //Scrolling down if(scrollY<oldScrollY){ scrollBtn.setVisibility(View.GONE); }else{ scrollBtn.setVisibility(View.VISIBLE); } } });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "android, scroll, scrollview" }
Splitting PDF files into Paragraphs I have a question regarding the splitting of pdf files. basically I have a collection of pdf files, which files I want to split in terms of **paragraph**. so to each paragraph of the pdf file to be a file on its own. I would appreciate if you can help me with this, preferably in Python, but if that is not possible any language will do.
You can use **pdftotext** for the above, wrap it in python subprocess. Alternatively you could use some other library which already do it implicitly like **textract**. Here is a quick example, Note: I have used 4 spaces as delimiter to convert the text to paragraph list, you might want to use different technique. import re import textract #read the content of pdf as text text = textract.process('file_name.pdf') #use four space as paragraph delimiter to convert the text into list of paragraphs. print re.split('\s{4,}',text)
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 7, "tags": "python, pdf, split, paragraph" }
How to interpret the sum of two series? I am confused a bit while I am recalling the infinite series. Thomas' Calculus says: Sum of two divergent series can be convergent by giving an example: $\sum1 + \sum-1 = \sum0=0$. We also know that $\sum(-1)^n$ is divergent. However, can not we think the series $\sum(-1)^n=-1+1-1+1\cdots$ equals to $\sum1 + \sum-1$? What distinguishes these series exactly?
Suppose that we have two sequences $\\{a_n:n\ge1\\}$ and $\\{b_n:n\ge1\\}$ and we want to find the limit of the sum of these two sequences. Then $$ \lim_{n\to\infty}(a_n+b_n)=\lim_{n\to\infty}a_n+\lim_{n\to\infty}b_n $$ provided that both of the sequences $\\{a_n:n\ge1\\}$ and $\\{b_n:n\ge1\\}$ converge. If this is not the case, the equality might not hold. Let us recall that a series is the limit of the sequence of the partial sums. What you are actually doing in your example is the rearrangement of the terms of the series, which does not necessarily give you the same limit unless the series is absolutely convergent. By rearranging a conditionally convergent series you could actually get anything. This is the famous Riemann series theorem. I hope this helps.
stackexchange-math
{ "answer_score": 6, "question_score": 5, "tags": "sequences and series, divergent series" }
Joining strings in a JArray with LINQ I have a JArray that looks like this: !enter image description here I'm using the code below to get the intended result: `6035940:8061090,6035940:8084337`. Can I clean this up with Linq? How? public static string GiveClientCampaignParam(JArray myArray) { StringBuilder sb = new StringBuilder(); foreach (var arrayItem in myArray) { string clientId = arrayItem["ClientId"].ToString(); string campaignId = arrayItem["CampaignId"].ToString(); sb.Append(clientId + ":" + campaignId + ","); } sb.Remove(sb.Length - 1, 1); return sb.ToString(); }
Using string.Join.aspx) and Select.aspx) to project the JArray element to a string: public static string GiveClientCampaignParam(JArray myArray) { return string.Join(",", myArray.Select(j => $"{j["ClientId"]}:{["CampaignId"]}")); } Using string.Join.aspx) also means you don't need to subtract the additional comma from the end.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "c#, linq, json.net" }
how to implement minheap using template I need to create a minheap template which includes nodes in it. The problem I have is that I don't know if I need to create a node template class as well, or should it be included inside the heap template class as a struct?
Min heaps aren’t usually (never?) implemented using explicit nodes – since a heap is always left-filled (“complete”) and thus has a well-defined structure, that would be unnecessarily inefficient since the handling of nodes and node links introduces quite a bit of overhead, not to mention destroying locality of reference, leading to cache misses and poor performance. (The same goes for max heaps of course.) Instead, they are implemented using arrays. In fact, the C++ standard library already includes the functions `make_heap`, `push_heap` and `pop_heap` to work on iterator Ranges. Use them in conjunction with a `vector` and you got your heap.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c++, templates" }
How to use jQuery to show a different page in ASP.NET I am trying to set up functionality similar to Netflix. Where if you mouseover a movie - you are presented with a window of movie details (all client-side). At high level, can someone in this forum help by telling me how this should be implemented? I.E., one or more .aspx pages, what would go in code-behind, and .js file, css, etc. Just trying to get an idea on how this would be set up to work. Basically, when I hover over an item, I need to query for details that belongs for that record being moused-over and display it in the window or div. I also need to have some functionality in that window (i.e. a textbox and button which will end up needing to get saved in a database). Thanks for any tips and suggestions -
You would want to add an `AJAX` call to the `hover` event of the image, that pulls from a webservice/web method. Here is a good example, you would change some things. However, it should get you started. <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "asp.net, jquery" }
CSS Applied to Only Image and Not Text I'm kinda new to PHP and I'm really confused how things are structured. I uploaded an icon that I want to be aligned in the middle with text on the right side of the icon. I attached an image of what it looks like right now. And what I want it to look like. It's a slight difference but it's there! Help? Thanks! !enter image description here <a href=" <img class="alignnone size-full wp-image-3074" style="height: 26px; width: 22px;" alt="draft" src=" width="39" height="48" /></a> <span style="font-size: 20px; font-weight: lighter; letter-spacing: 1px; color: #609d6f;">Draft Coverage</span>
This has nothing to do with PHP, just HTML/CSS. You are probably going to run into a lot of problems like these -- unfortunately, you can really only learn by experience. What will work here is using `vertical-align: midddle` on the `<img>` and `<span>` elements. <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "css, image" }
How to automatically calculate fibonnacci levels from yesterday/prev day in MQL4? how do I calculate the fibo levels from yesterday/previous day. This is how far I am currently: int shift = iBarShift( NULL, PERIOD_D1, Time[0] ) + 1; // yesterday HiPrice = iHigh( NULL, PERIOD_D1, shift); LoPrice = iLow ( NULL, PERIOD_D1, shift); StartTime = iTime( NULL, PERIOD_D1, shift); if ( TimeDayOfWeek( StartTime ) == 0 /* Sunday */ ) { // Add fridays high and low HiPrice = MathMax( HiPrice, iHigh( NULL, PERIOD_D1, shift + 1 ) ); LoPrice = MathMin( LoPrice, iLow( NULL, PERIOD_D1, shift + 1 ) ); } Range = HiPrice - LoPrice; I think now I should have all values necessary for calculating it. I am not sure on how I now can calculate the different levels now: 23.6 38.2 50.0 61.8 76.4 and -23.6 -38.2 -50.0 -61.8 -76.4 -100
All necessary Fibo-levels can be added manually as an array - this is the easiest way as far as I know. Then simply loop over such array and +values are `( high + array[i] / 100 * range )`, values below the fibo - `( low - array[i] / 100 * range )`, where `array[] = { 23.6, 38.2, .. }` ( only positive values are enough )
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "fibonacci, mql4, metatrader4, mt4" }
jQuery- How to determine properties of internal anchor link's parent I am trying to see if an anchor link location is located in a list whose class is "tab": <ul class="etabs"> <li class="tab"><a href="#tab1" alt="">Tab 1</a></li> <li class="tab"><a href="#tab2" alt="">Tab 2</a></li> <li class="tab"><a href="#tab3" alt="">Tab 3</a></li> </ul> Now, let's say I visit this page directly: I have: if (document.location.href.indexOf('#') > -1) { if ($(window.location.hash).parent('li').hasClass('tab')) { // something wrong here alert('its a tab'); } else { alert('not tab'); } } I keep getting "not tab". What's wrong with my code?
When you visit < , then window.location.hash will be #tab2 , which means $(window.location.hash) will be looking for an element with an **id** of tab2. So add id's to your a tags : <a id="tab2" href="#tab2"
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery" }
Creating with time series from a dataset including missing values I need to create a time series from a data frame. The problem is variables is not well-ordered. Data frame is like below > Cases Date 15 1/2009 30 3/2010 45 12/2013 I have 60 observations like that. As you can see, data was collected randomly, which is starting from 1/2008 and ending 12/2013 ( There are many missing values(cases) in bulk of the months between these years). My assumption will be there is no cases in that months. So, how can I convert this dataset as time series? Then, I will try to make some prediction for possible number of cases in future.
Try installing the plyr library, install.packages("plyr") and then to sum duplicated Date2 rows: library(plyr) mergedData <- ddply(dat, .(Date2), .fun = function(x) { data.frame(Cases = sum(x$Cases)) }) > head(mergedData) Date2 Cases 1 2008-01-01 16352 2 2008-11-01 10 3 2009-01-01 23 4 2009-02-01 138 5 2009-04-01 18 6 2009-06-01 3534
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "r, dataframe, dataset, time series, tm" }
About vim use, when insert comment character(eg. #) system: ubuntu 14.04.2 I use vim7.4 to write python code, sometimes I want to insert a '#' (comment), then vim takes this '#' to top of line. Maybe I don't explain clearly. example: code: if 'test' == 'abc': print 'something' I want to insert a '#' in second line.Then this happens: if 'test' == 'abc': # print 'something' this happens automatically. but what I want to do just like this: if 'test' == 'abc': # print 'something'
There is an issue with indenting of hash character `#`: < > Q: Why does Vim place # at the first column? > > A: You are using 'smartindent', or you have 0# in your 'cinkeys' or 'indentkeys' options. > > Under some circumstances, when you type a '#' character while in insert mode, the indent on the current line will be removed. Also, formatting or otherwise attempting to adjust the indent of a line starting with '#' may not work as you expect. > > This tip discusses the issues and how problems can be avoided.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "python, vim" }
Is it possible to throw a java exception through the calling method of a base class that does not throw exceptions? This may be a ridiculous Java question about exception handling, but I have a UI actor (an Android Activity) that is requesting services from my subclass of ContentProvider. The subclass wants to throw some exceptions when sd-card is full, sd-card is missing, network i/o errros, etc. However, when I code the CP-subclass to throw my exceptions, the compiler offers to add the exceptions to the CP class. Obviously, I don't want to modify the base class, but I want the UI to catch the sub-class' exceptions. Make sense? Is this possible? If not, is there a better pattern for my service subclass to get its throwable object back to the UI?
You only need to declare and catch "checked exceptions". You do not need to declare or explicitely catch RuntimeExceptions. So you can throw a RuntimeException and catch it whereever you like up in the hierarchy.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "java, subclass, throwable" }
How can I pass in generic HTML to an Angular 2 component? I want to make a generic modal component that can hold anything, from just text to images/buttons etc. If I do something like this: <div class="Modal"> <div class="header"></div> <div class="body">{{content}}</div> <div class="footer"></div> </div> I'm not able to actually pass HTML into content, just text. How can I create a component such that the parent component can pass in whatever HTML it wants? What if I wanted to add n number of buttons to the footer, each with it's own callback? Is there a better way I should be doing this?
What you are looking for is `ng-content` <div class="Modal"> <div class="header"></div> <div class="body"> <ng-content></ng-content> </div> <div class="footer"></div> </div> and you may pass any HTML content directly into your component. Lets say your component name is `my-modal`, you may use it like below, <my-modal> <<HTML content : this will be replaced in the ng-content area >> </my-modal> Hope this helps!!
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 5, "tags": "javascript, angular" }
Plausible reason for Earth not be able to get updates about terraforming on Mars? I’ve been working on a story where terraforming robots are sent to another world and the colonists come along later. Originally, I had the new world be extrasolar, but for other plot reasons, I’m wanting to move it to Mars. One problem: I want the results of the terraforming to be something of a surprise to the arrivals. That requires that there be something that keeps Earth from getting broadcasts from the Martian robots and prevents Earth from observing Mars through telescopes, but does not prohibit Earth from building and launching colony ships. I’ve backed myself into this plot corner, and rather than adjust the other elements of the story that are working, I figured I’d ask here to close this gap, if possible. Is there some oddity of solar flares or Earth atmospheric changes or ??? that can save my story?
Not sure on the plausibility of this but here is an idea, the terraforming raises a large amount of dust that covers the majority of the planet. As a result, communications are blocked and telescope observations don't work because the dust is covering everything. Earth still sends the colony ships because the dust storm is still persisting meaning that the robots are still working and terraforming (and they can see an occasional robot wandering out of the dust storm, and then heading back into it), they just add some extra supplies to account for some extra delays due to the dust blocking some (not all) of the solar power and hence reducing the operating speed of the robots.
stackexchange-worldbuilding
{ "answer_score": 23, "question_score": 14, "tags": "solar system, isolation, telescope" }
nestjs-sequelize not syncing with any modle after implementing sesstion store So I'm making a discord bot and a website dashboard for it. I got everything working except the backend Nestjs API I'm making. My Bot uses Sequelize as its database so I thought I would do the same for my API. I really don't want to switch to any other ORM. All my API code can be found at: < For some reason, my API won't sync with my MySQL database. It doesn't throw any errors, but it doesn't work. It may be due to the fact that I tried to set up a session store and got something wrong there. (I'm kind of new to Nestjs and I'm not really sure how to properly store a session ) I think the issue is probably in main.ts or app.module.ts. I've spent a whole day just trying to figure this out but nothing online seems to help. Any and all feedback is greatly welcome. Thanks in advance!
Set `autoLoadModels` to be `true`, it should work.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "mysql, typescript, discord, sequelize.js, nestjs" }
Query Formula using Google Sheets - count data from multiple columns and return results in a single column I am trying to calculate a count of how many times a course is listed in different columns and return the count in a list of all the courses found in those columns. I have a spreadsheet that shows the start of my formula... query(UNIQUE({C2:C21; F2:F21;I2:I21}),"select C,F,I, count(C), count(F), count(I) where B is not null group by C,F,I")
Clear cells A23, A24 and B23 and then try in A23 =query({C2:C21; F2:F21;I2:I21},"select Col1, count(Col1) where Col1 <> '' group by Col1 label Col1 'Fall Courses', Count(Col1) 'Count'") and see if that helps? If it does, you can repeat the same logic for 'winter' and 'spring'. Alternatively, you can also try this single formula =query(ArrayFormula(split(transpose(split(textjoin("~", true, regexreplace(C1:K1, "(Winter|Spring|Fall)", "_$1")&"_"&C2:K21), "~")), "_")), "Select Col3, Count(Col3) where Col3 <>'' group by Col3 pivot Col2", 0)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "google sheets, formula" }
make dictionary result white text in spotlight in mojave dark theme ![enter image description here]( I can't read the result. How do I make the text white? I am on macOS Mojave 10.14.4
This bug exists in 10.14.4 and earlier and It is fixed in 10.14.5
stackexchange-apple
{ "answer_score": 1, "question_score": 2, "tags": "macos, mojave, spotlight, dictionary" }
Need Connector for Motor - I don't want to buy 50 I have no idea what I've gotten myself into, but I've bought electric bicycle motors and they didn't come with the connectors. Apparently the below link is the type of connectors I need. Is there an alternative distributor of these that I can buy just a couple from? Can I make them my self or cut them off and use a different connector? Also is this type of connector standard? Is there a datasheet for these pin-outs somewhere? I would like to get 2 of these, not 50
First 9-Core Waterproof Plug in connector at Green Bike Kit < This was the 3rd result when I googled "9-Core Waterproof Plug in connector"
stackexchange-bicycles
{ "answer_score": 2, "question_score": 1, "tags": "electric bike" }
How can i export Multiple With Routers I am trying to export both of these exponents withrouter so i can use props.location. ./src/App.js Attempted import error: 'MobileMenu' is not exported from './components/Navbar'. module.exports = { Navbar: withRouter(Navbar), MobileMenu: withRouter(MobileMenu) }; import { MobileMenu, Navbar } from './components/Navbar';
let Navbar = withRouter(Navbar) export { Navbar }; let MobileMenu = withRouter(MobileMenu) export { MobileMenu };
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "reactjs, react hooks" }
How do i find out if one of the last to buttons were clicked from a dynamic content list I have like 8 of these div blocks and i want to know if the last two a in the list of 8 were clicked. This will be dynamic so it could be 8 now and 20 later so the code needs to know that its the last two not if its 7 or 8. <div class="seven columns offset-by-one"> <h1> Joshua F. Schwartz </h1> <h2> Position </h2> <p> Etiam lacus dui, sollicitudin non pulvinar nec, fringilla commodo mauris. Nunc orci enim, pellentesque porta malesuada eu, ornare vel lectus. In venenatis nisl ut lorem ultricies semper. Duis vitae turpis nec tortor dignissim tempor. Phasellus et elit et. <a href="">Read More</a> </p> </div>
You can use the jQuery index() method: function isLastTwo(element) { // Get the total <div> tags var length = $("div.columns.offset-by-one").length; // Compare the index of current element to the length return $(element).index() >= (length - 2); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery" }
Heroku not compiling javascripts I'm having real trouble with Heroku. It seems it's compiling CSS now, but still JS is not being compiled. I'm using Foundation 5 and Rails 4. Any idea? production.rb config.serve_static_assets = false config.assets.precompile += %w( vendor/modernizr.js ) config.assets.js_compressor = :uglifier config.assets.css_compressor = :sass config.assets.compile = true config.assets.digest = true` application.js //= require jquery //= require foundation //= require jquery_ujs //= require jquery.validate //= require jquery.lockfixed //= require sticky_footer //= require list //= require foundation.slider //= require landing //= require handlebars //= require landing //= require foundation.abide $(function(){ $(document).foundation(); });
You probably committed your assets to your git repo. You can # add assets to git ignore echo "public/assets" >> .gitignore # remove them from your git repo and from public git rm -rf public/assets # update your repo git add public git commit -m "Removed assets from repo" # push to heroku again git push heroku master
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, ruby on rails, heroku, deployment, asset pipeline" }
Trouble with HP printer I have a HP Photosmart C3180 (it's a printer/scanner). For some reason, it recently stopped working. The power light is blinking (I think all the other lights are one, but don't remember, I'm not there right now), and the only way to turn it off is to unplug it. It won't print anything, and when you put a page in the tray it sucks it in without printing anything on it and stops when the paper is on its way out (Again, I don't remember how we managed to get it out, sorry). This printer is hooked up to a computer running XP, but it doesn't work either when printing from the network. Weirdly, the scanner works fine. Do you have any ideas on what could be the problem? Could it be a driver problem? By the way, sorry if the question lacks a bit of detail. I don't know much about printers, and I don't have it here so I can't remember exactly all the details. If needed I can update the question tonight or tomorrow.
The firmware is bad. You'll have to send it in to HP for repairs unless you can find a local shop that can unbrick it. The Scanner portion is functionally seperate from the Printer part, they just have a shared USB connection.
stackexchange-superuser
{ "answer_score": 1, "question_score": 2, "tags": "printer" }
Webpack imports the same styles multiple times I've noticed, that my webpack configuration imports the same styles into head `<style>` tag multiple times, when I @import styles in sass file. ![Imported Styles]( I think it's because of my global styles file, which looks like this: @import url(' @import '~material-design-lite/src/material-design-lite.scss'; I later import the styles in multiple other component style files: @import 'global'; Is there some configuration that I've missed? I thought I could import the global styles file in index.js file through import, but these imports must come first, and somehow I was not able to achieve that with webpack.
That's not an issue with webpack, more with your use of CSS. Since CSS assets are compiled statically, each stylesheet importing `global` has a copy in it. You could use Less, and the `@import (reference) statement`, or if you prefer CSS then load it separately and don't import it every time.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 9, "tags": "css, reactjs, sass, webpack" }
Create a hyperlink using Xamarin.Forms (xaml and c#) I basically want to create a hyperlink in Xamarin.Forms using the label class. Basically, I want to following link to take the user to google.com in a web browser: <Label Text=" /> I can't find anything in the Xamarin Forms API about this and the internet has vague and limited information on this topic in Xamarin.Forms. Is this possible? If so, could someone please point me in the right direction? Thanks in advance to anyone who answers.
You can't really do this because Labels by default don't respond to user input, but you can achieve something similar with gestures using Xamarin.Forms; using Xamarin.Essentials; Label label = new Label(); label.Text = " var tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += async (s, e) => { // Depreciated - Device.OpenUri( new Uri((Label)s).Text); await Launcher.OpenAsync(new Uri(((Label)s).Text)); }; label.GestureRecognizers.Add(tapGestureRecognizer);
stackexchange-stackoverflow
{ "answer_score": 23, "question_score": 24, "tags": "c#, xaml, xamarin, xamarin.ios, xamarin.forms" }
How to order an array in managed C++/CLI Here is my array : cli::array<String^>^ ar = gcnew cli::array<String^>{ "3", "1", "4", "5", "2" }; How can i **Order By Descending** this array?
You can use Array.Sort.aspx) by passing a comparison function. using namespace System; int Compare(String^ a, String^ b) { return String::Compare(a, b, StringComparison::OrdinalIgnoreCase) * -1; } auto ar = gcnew cli::array<String^>{ "3", "1", "4", "5", "2" }; Array::Sort(ar, gcnew Comparison<String^>(Compare)); Alternately, you can sort with an ascending order and reverse.aspx) the array. Array::Sort(ar, StringComparer::OrdinalIgnoreCase); Array::Reverse(ar);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "arrays, visual studio 2015, c++ cli" }
How to target Windows XP sp3 when compiling with Visual C++ 2010? I am trying to compile a C++ program using Visual Studio 2010 Pro on a Windows 7 computer to target Windows XP sp3 32 bits. I've played around with the compiler and linker settings, but I'm unable to produce an executable that can run on my Windows XP computer. I always get the error "Could not find entry point for function GetTickCount64 in kernel32.dll" and the program doesn't run. I know Windows XP does not support GetTickCount64() and I'm not using it in my code anyways. I don't have other versions of Visual Studio installed, and I already installed Visual C++ 2010 Redistributable Package on the windows XP machine. Any idea on how to accomplish this? Thanks before hand.
VC2010 targets Windows 7 by default. To change target to XP, check Using the Windows Headers
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "visual studio 2010, visual c++, windows xp, target" }
Parse json in objective-c for my iphone app i have a problem parsing my json data for my iPhone app, I am new to objective-C. I need to parse the json and get the values to proceed. Please help. This is my JSON data: [{"projId":"5","projName":"AdtvWorld","projImg":"AdtvWorld.png","newFeedCount":"0"},{"projId":"1","projName":"Colabus","projImg":"Colabus.png","newFeedCount":"0"},{"projId":"38","projName":"Colabus Android","projImg":"ColabusIcon.jpg","newFeedCount":"0"},{"projId":"25","projName":"Colabus Internal Development","projImg":"icon.png","newFeedCount":"0"},{"projId":"26","projName":"Email Reply Test","projImg":"","newFeedCount":"0"},{"projId":"7","projName":"PLUS","projImg":"7plusSW.png","newFeedCount":"0"},{"projId":"8","projName":"Stridus Gmail Project","projImg":"scr4.png","newFeedCount":"0"}]
On iOS 5 or later you can use `NSJSONSerialization`. If you have your JSON data in a string you can do: NSError *e = nil; NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding]; NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e]; **Edit** To get a specific value: NSDictionary *firstObject = [jsonArray objectAtIndex:0]; NSString *projectName = [firstObject objectForKey:@"projName"];
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "iphone, objective c, json" }
Null substitution in SQLite: In Sybase and MSSqlServer TransactSQL, we have a function IsNull(columnName,valueForNull) to return a typed default value when a column value is null. How can I replicate this functionality in SQLite? Example in TransactSQL: select IsNull(MyColumn,-1) as MyColumn from MyTable If MyColumn is null, this expression will return -1 as the value of MyColumn. Want to do something similar in SQLite. _(Yes, I know I can write my own wrapper function to handle this - that's not the answer I'm looking for)_ TIA
You can use ifnull: select ifnull(MyColumn,-1) as MyColumn from MyTable
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "tsql, sqlite, null, isnull" }
How to resolve SELECT list is not in GROUP BY clause and contains nonaggregated? I am getting an error with MYSQL 5.7 on this request. How to resolve this error ? > #1055 - Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.c.customers_group_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by select SQL_CALC_FOUND_ROWS c.customers_firstname, c.customers_lastname, c.customers_group_id, sum(op.products_quantity * op.final_price) as ordersum from customers c, orders_products op, orders o where c.customers_id = o.customers_id and o.orders_id = op.orders_id group by c.customers_firstname, c.customers_lastname order by ordersum DESC
include `c.customers_group_id` also in the group by clause
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "mysql, mysql error 1055" }
Render own partial via javascript in Rails Say there is a partial called _hello_world.html.erb <% if toggle %> HELLO WORLD ON <%= link_to "Turn it off", what_should_come_here %> <% else %> HELLO WORLD OFF <%= link_to "Turn it on", what_should_come_here %> <% end %> Intially this partial will be called from say an index file like this, <%= render :partial => 'test/hello_world', :locals => {:toggle => true} %> But after I click the toggle link it should switch between On and Off states which should basically render the own partial again overriding the previous partial. How to do this ? Note: I have given the Question in < format.
instead of `link_to` it would be better to use `link_to_remote` **index.html.erb** <div id="toggle_div"> <%= render :partial => 'test/hello_world', :locals => {:toggle => @toggle} %> </div> **_hello_world.html.erb** <% if toggle %> HELLO WORLD ON <%= link_to_remote "Turn it off", my_action_path(:toggle => toggle) %> <% else %> HELLO WORLD OFF <%= link_to_remote "Turn it on", my_action_path(:toggle => toggle) %> <% end %> **in action** def myaction value = params[:toggle] // do something with toggle value @toggle = value == "true" ? false: true render :update do |page| page.replace_html 'toggle_div', :partial => 'hello_world', :locals => {:toggle => @toggle} end end
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ruby on rails, ruby, renderpartial" }
JGIT Pull NoHeadException When is try to execute the following method (uses JGIT library) private void pullRepo() throws IOException,GitAPIException, WrongRepositoryStateException, InvalidConfigurationException, DetachedHeadException, InvalidRemoteException, CanceledException, RefNotFoundException, NoHeadException{ Git git = new Git(localRepo); git.pull().call(); } I get the following runtime exception: org.eclipse.jgit.api.errors.NoHeadException: Pull on repository without HEAD currently not supported at org.eclipse.jgit.api.PullCommand.call(PullCommand.java:161) Does someone know how to solve this? The localRepo I use is the same as I use for the cloneRepository method ,which works perfectly. thanks, bgvv1983
Think I found my mistake. was on the wrong level in my project folder. I was at the ../project (which works in your shell) level in stead of ../project/.git level.
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 9, "tags": "java, eclipse, git, egit, jgit" }
How do I use the C preprocessor to make a substitution with an environment variable In the code below, I would like the value of `THE_VERSION_STRING` to be taken from the value of the environment variable `MY_VERSION` at compile time namespace myPluginStrings { const char* pluginVendor = "me"; const char* pluginRequires = THE_VERSION_STRING; }; So that if I type: export MY_VERSION="2010.4" `pluginRequires` will be set at "2010.4", even if `MY_VERSION` is set to something else at run time. **UPDATE:** (feb 21) Thanks for your help everyone. It works. As I'm using Rake as a build system, each of my CFLAGS is a ruby variable. Also the values need to end up in quotes. Therefore the gcc command line for me needs to look like this: gcc file.c -o file -D"PLUGIN_VERSION=\"6.5\"" Which means this is in my Rakefile: "-D\"PLUGIN_VERSION=\\\"#{ENV['MY_VERSION']}\\\"\""
If I recall correctly, you can use the command line parameter `-D` with gcc to `#define` a value at compile time. i.e.: $ gcc file.c -o file -D"THE_VERSION_STRING=${THE_VERSION_STRING}"
stackexchange-stackoverflow
{ "answer_score": 21, "question_score": 13, "tags": "c++, environment variables, c preprocessor, substitution" }
Probability with real numbers There are two sets of real numbers: $S_1=[0,N_1]$, $S_2=[0,N_2]$, where $N_1$ and $N_2$ are positive integers. From $S_1$ a value $x_1$ and from $S_2$ a value $x_2$ is chosen. What will be the probability that $x_1=x_2$?
No loss of generality, suppose $N_2 \ge N_1$, and we divide the intersect $[0,N_1]$ to M small blocks and similarly $[0,N_2]$ to $\frac{N_2}{N_1}M$ blocks. We can find the probability that the point is in the same block is $\Sigma_{i=1}^{M}\frac{1}{M}{\frac{N_1}{N_2M}} = \frac{N_1}{N_2M} $ Let M increase to infinity, it's $lim_{M->\infty}\frac{N_1}{N_2M} = 0 $
stackexchange-math
{ "answer_score": 0, "question_score": -1, "tags": "probability" }
Wevtutil to output event log description Is there anyway to only output the description field in an event log entry? Im current using: wevtutil qe Application /q:*[System[(EventID=431)]] /f:text /rd:true /c:2 /gm:true > C :\query.txt However this output everything. I just want to output the description which is under: <EventData> <Data> Description bllah blah</data> </EventData>
You can use `/f:text` modifier and `grep` with `^|FIND "Description"` wevtutil qe Application `/q:*[System[(EventID=431)]] /f:text /rd:true /c:2 /gm:true ^|FIND "Description" > C:\query.txt` Note the `^` before the pipe, it escapes the pipe in scripts.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "windows, xpath, event log" }
What is the difference between the cognitive hierarchies and level k model? Both these models are hierarchical models of strategic behaviour, where the k'th level plays a best response to the earlier levels. What exactly is the difference, mathematically? A precise definition of each and how they differ would clarify this.
There are several variants of level-$k$ models and cognitive hierarchy models present in the literature. What the level-$k$ models have in common is that level-$k$ players best respond to the assumption that all other players are level-$(k-1)$, while cognitive hierachy models assume that a level-$k$ player best responds to the assumption that all other players are of _some_ lower level.
stackexchange-economics
{ "answer_score": 3, "question_score": 1, "tags": "game theory, behavioral economics" }
передача параметра в регулярное выражение bash Использую grep -o '[0-9]\+.[0-9]\+-[^/]\+' чтобы находить файлы типа 1.2-stable. Сейчас имя файлов изменилось - dev-1.2-stable, это dev передается параметром в скрипт. пробовал grep -o '$1\+.[0-9]\+.[0-9]\+-[^/]\+' но не подходит, как правильно прописать параметр в скрипт?
В баше (а также в Perl и других родных языках), все, что написано в одинарных кавычках не интерполируется (то есть, значения переменных не подставляется). А что бы они подставлялись, нужно использовать двойные кавычки. То есть, достаточно написать так grep -o "$1\+.[0-9]\+.[0-9]\+-[^/]\+"
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "linux, bash" }
pyspark column value is a list Working with a dataframe which contains a column, the values in the columns are lists, how could I process such column id | values 1 | [1,1,2,4,3,5,6] 2 | [1,2,3,5,6,7,8] .... For each row take the first three values and get the max out the first three Expected as: id | max_value 1 | 2 2 | 3 ....
You can use slice and array_max functions from pyspark `sql.functions` For example, by passing `array_max(slice(values, 1, 3))` to `F.expr`, you are first list(`slice`) and taking max (`array_max`) import pyspark.sql.functions as F df .withColumn("max_value", F.expr("array_max(slice(values, 1, 3))")) .show(truncate=False) +----------------+- |id |max_value| +----------------+- |1 |2 | |2 |3 | +----------------+-
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, apache spark, pyspark" }
Is there a built-in way to retrieve a PHP array element such that it is removed from the array? Is there a built-in way to retrieve a PHP array element such that it is removed from the array? Similar to `array_pop()`, but on a specific index? For example: <?php $array = [ 'foo' => 123, 'bar' => 456, 'baz' => 789 ]; $bar = array_get_and_remove($array, 'bar'); /* Outputs: * $bar = 456, * $array = ['foo' => 123, 'baz' => 789] */
$element = $array[$key]; unset($array[$key]); So to make your function (be sure to use a reference `&`): function array_get_and_remove(&$array, $key); $element = $array[$key]; unset($array[$key]); return $element; } Then: $bar = array_get_and_remove($array, 'bar');
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "php, arrays" }
flutter widget: flutter_map don't work, missing latLng function I want o test this (< widget map from Flutter. but i can found what to import to solve dependency to this method: **LatLng**. This method is used to set a point on many places on the first example. Can someone tell me what lib to import to solve this dependency?
**Short answer** : Install latlong2 package simply by doing `flutter pub add latlong2` * * * **Long answer:** On the right side of pub.dev you can find a dependency list, in this case it's this: ![enter image description here]( You should already be able to do `import 'package:latlong2/latlong.dart';` but probably the linter will notify you not to use dependencies that are not defined in your `pubspec.yaml`, so you have to explicitly add `latlong2: ^x.x.x` to your pubspec.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "flutter, dart, geolocation, widget" }
how do I declare a matlab variable to store string? In this matlab code, % kalimba memory read clear all clc close all read_val = zeros(128, 1); read_val_INDEX = 1; fid = fopen('kal_mem_data.txt', 'r'); % assume each row has 1 address string and 16 data strings for j=1:8 asd = fscanf(fid, '%s', 1); % skip the address string for i=1:16 read_val(read_val_INDEX) = fscanf(fid, '%s', 1); read_val_INDEX = read_val_INDEX + 1; end end fclose(fid); kal_mem_data.txt has a list of hexadecimal numbers as 0001c1 FF45DF 012345 ... The first scanf works without problems asd = fscanf(fid, '%s', 1); asd is automatically typecasted to char type to store the hex string as a character array How do I predeclare an array read_val so that each element of read val is a string? Is there an easy way to do this in matlab?
**If all strings have the same length:** You could preallocate a 128x6 matrix (assuming the string length is 6) like this: read_val = char(zeros(128, 6, 'uint8')); Then, you would read each string on a line, like this: read_val(read_val_INDEX, :) = fscanf(fid, '%s', 1); **If the strings don't necessarily have the same length:** One good approach would be using a cell array, like this: read_val = cell(128, 1); And you would read like this: read_val{read_val_INDEX} = fscanf(fid, '%s', 1);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "arrays, string, matlab" }
How to assign diameter size to valve feature class based on waterline size? I have two shapefiles, valves (points) and waterlines (polyline). The waterlines have a diameter attribute that is populated with the correct size. The valves have an attribute for diameter size as well but some of the values are showing 0 for the size. I need to update the 0 sized valves with the correct size from the waterline it is on. The valves are in close proximity to the waterline if not directly on it. I don't have access to the "Near" function because of the level of my license. I am using ArcGIS 10.2 for Desktop with a Standard license. What I have done so far is select valves by 1ft location to specific waterlines with specific diameter size (ie selected valves that are within 1ft of 16 inch waterline). From this point I'm not sure what I should do next or even if this is the correct path to the solution.
You probably want to do a spatial join. Join your lines to points and make sure to select to give each point (valve) the attributes of the line (pipe) it is nearest. ![enter image description here]( Once you have joined the tables, sort ascending on the valve size field (the field with the 0s) and highlight/select all the records with "0" then right click on the field header and use field calculator to copy of the size from the now joined field holding your pipe size to your field holding the valve size
stackexchange-gis
{ "answer_score": 1, "question_score": 1, "tags": "arcgis desktop, arcgis 10.2, fields attributes" }
Java - creating a folder and file in web server directory i would like to create a file in a folder (TestFolder) of web server. I will i get relative path of web server directory and how will i create my TestFolder in that directory. currently i will create a folder in my local server but later i need to create a folder in test environment (server could be different on test environment)
String realPath = getServletContext().getRealPath("/"); File file = new FIle(realPath+"/TestFolder", "testFIle.txt"); file.mkdirs(); The above code will create a folder `TestFolder` and a file `testFIle.txt` in the root directory of your web application. `file.mkdirs()` Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories. **Returns:** `true` if and only if the directory was created, along with all necessary parent directories; `false` otherwise Hope this helps !
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 2, "tags": "java, webserver, relative path" }
Getting the data from a NSTableView to a NSViewController I'd like to have a 'Detail view' for when the user double clicks on a row, I'm just not sure how to get the data to the NSViewController, so it can display the content. I'm using CoreData and I can't think of a way to do this.
There are a couple of steps you need to do here: 1. Make sure the table view is driven by a `NSArrayController` and that your controller for the table view (either a window controller or a view controller, or whatever) has that `NSArrayController` bound to an ivar so that you access it. 2. In your table controller set the double click action to a method in your controller and set the target to your controller. 3. In the double click method you can access the row by requesting the `-selectedObjects` from the `NSArrayController` and that resulting `NSArray` should have only one element in it. From there you can then create your detail view or whatever else you want to do with it. You can create a sheet and display it, open a modal window, etc.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "objective c, cocoa, core data, nstableview" }
Getting Process ID of started process using SSH2 - phpseclib I am using phpseclib, Net_SSH2. I need to get the process ID of the server/process that is started by this command. echo $ssh->exec('java -Xmx256M -Xms32M -jar minecraft_server.jar nogui'); This is so i can store it and be able to kill it via a PHP script at anytime.
You may try: echo $ssh->exec('java -Xmx256M -Xms32M -jar minecraft_server.jar nogui > /dev/null 2>&1 & echo $!;');
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, ssh, libssh2, phpseclib" }
Differentiate complex function? $$f(z)=3z^2+\bar{z}$$ I want to show the function is either differentiable or not so I can state if it is holomorphic or not. What is the method for this ? Edit - Can some give an example of how to apply cauchy riemann equation to this question ?
If $f(z)$ were differentiable, then $f(z)-3z^2=\bar{z}$ would be differentiable since $3z^2$ is. However, $\bar{z}$ is not complex differentiable. Check this with the Cauchy-Riemann equations.
stackexchange-math
{ "answer_score": 1, "question_score": 3, "tags": "calculus, complex analysis" }
iOS: Sinch SDK Instant Messaging Issue(SINErrorDomainCapability error 2001) I am integrating sinch sdk in my iOS application. it's giving me error of SINErrorDomainCapability error 2001. Will you please tell me how to resolve it. i am new to social integration.
Make sure you set up the right capabilities when starting the Sinch client, as documented here: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ios, instant messaging, sinch" }
looking for a regular expression to extract all text outputs to user from js file i have some huge js files and there are some texts/messages/... which are output for a human beeing. the problem is they don't run over the same method. but i want to find them all to refactor the code. now i am searching for a regular expression to find those messages. ...his.submit_register = function(){ if(!this.agb_accept.checked) { out_message("This is a Messge tot the User in English." , "And the Title of the Box. In English as well"); return fals; } this.valida... what i want to find is all the strings which are not source code. in this case i want as return: * This is a Messge tot the User in * English. And the Title of the Box. In English as well i tried something like: `/\"(\S+\s{1})+\S\"/`, but this wont work ... thanks for help
It's not possible to parse Javascript source code using regular expressions because Javascript is not a regular language. You can write a regular expression that works most of the time: /"(.*?)"/ The `?` means that the match is not greedy. Note: this will not correctly handle strings that contain ecaped quotes.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "regex" }
How to fix calculation error in go math operations with floats? I need to normalise a value (degrees) to have it in some range. I need to get a reminder of division by 360. func testFunc(t *testing.T) { v := -1050.6 n := int(v / 360) f := v - float64(n)*360 fmt.Printf("f: %v\n", f) } The value I expect is `-330.6` the value I get is `-330.5999999999999`. This happens when I do `v - float64(n)*360`. Is there any way to get rid of this error?
You can try this (2 digits after comma): fmt.Println(math.Round(f * 100) / 100)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "go" }
Parallelize while/for in OpenMP - files in directory I have a piece of code that searches a pattern in files within some directory. The point is how to parallelise this. My first version: DIR * dptr = opendir(DIRNAME); struct dirent *dir; while(dir = readdir(dptr)) != NULL) { // searching in dir -> d_name; } So I transformed while to for: #pragma omp parallel #pragma omp for for(;(dir = readdir(dptr)) !=NULL;) { // searching } But now I have an error: "Expected iteration declaration or initialization before ';' token. for(;(dir = readdir(dptr)) !=NULL;) " Do you have any idea how to organise going over every file in the directory with the proper for loop?
OpenMP `parallel for` directive splits iteration vector between threads. In order to do this, it takes loops in so-called `canonical` forms. I.e. `for(statement; expression; expression)` and you cannot skip a part of the loop. In addition, bound `expression` shall be one of forms: `less-expr (<), more-expr (>)` and their equal forms: `less-equal-expr (<=), more-equal (>=)`. So, to fix your code, you need 1. Write initializer and increment in `for` loop 2. Rewrite bound expression (it currently uses `ne-expr (!=)`
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "for loop, parallel processing, directory, openmp" }
Trigger an inline function with jquery I have a function written on the anchor itself like <a href="home.jsp" onclick="return confirm('Do you want to logout?');">Log Out</a> I have tried using another onclick even of the anchor like . $("a").click(function(){ }); I know it will trigger another event not the one I expect to trigger. The content in the confirm box is dynamic, so I cant change the function. Is there any way that I could trigger the in line function of the anchor through jQuery?
To programmatically trigger the element's `click` event, simply use the `click()` method without an argument: $('a').click(); This is a shorthand of the `trigger()` method and is equivalent to: $('a').trigger('click');
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "jquery, event triggers" }
Editext push down all content of layout Hi I'm trying to create `EditText` **multiline** but when I back to line all content of layout go down: !Scrennshot manifest.xml <activity android:configChanges="keyboardHidden|orientation|screenSize" android:name=".MainActivity"> <intent-filter> /... </intent-filter> </activity> Activity_main.xml: <EditText android:inputType="textMultiLine" android:layout_marginTop="25dp" android:background="@android:color/transparent" android:layout_width="200dp" android:maxLength="80" android:layout_centerHorizontal="true" android:hint="so.not.Vaporwave" android:textColor="#FFF" android:textColorHint="#a9ffffff" android:layout_height="wrap_content" android:layout_below="@+id/exmple" android:id="@+id/edtietxt" />
You can set MAX height for the edit text so that it won't expand dynamically > android:maxHeight="100dp" <EditText android:inputType="textMultiLine" android:layout_marginTop="25dp" android:background="@android:color/transparent" android:layout_width="200dp" android:maxLength="80" android:layout_centerHorizontal="true" android:hint="so.not.Vaporwave" android:textColor="#FFF" android:maxHeight="100dp" android:textColorHint="#a9ffffff" android:layout_height="wrap_content" android:id="@+id/edtietxt" />
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "android, android edittext" }
How to create dynamic href in react render function? I am rendering a list of posts. For each post I would like to render an anchor tag with the post id as part of the href string. render: function(){ return ( <ul> { this.props.posts.map(function(post){ return <li key={post.id}><a href='/posts/'{post.id}>{post.title}</a></li> }) } </ul> ); How do I do it so that each post has href's of `/posts/1`, `/posts/2` etc?
Use string concatenation: href={'/posts/' + post.id} The JSX syntax allows either to use strings or expressions `({...})` as values. You cannot mix both. Inside an expression you can, as the name suggests, use any JavaScript expression to compute the value.
stackexchange-stackoverflow
{ "answer_score": 258, "question_score": 142, "tags": "javascript, reactjs" }
Finding the Median of three numbers in Python. 3.8.2 How would I find the median of three numbers without using this function in python is there another way median_1 = statistics.median(alpha_1) enter code here def median(alpha_1): #median_1 = sorted(alpha) median_1 = statistics.median(alpha_1) return median_1 if __name__ == "__main__": # FIXME 1: Print the statement where you say what the program is going to do num_1 = int(input("Input first number:\n")) num_2 = int(input("Input second number:\n")) num_3 = int(input("Input third number:\n")) # FIXME 2: Propmt the user to input 3 numbers c = num_1, num_2, num_3 f = median(c) print("The median is",f)
Not the most efficient for larger arrays, but for only three elements it will be fine: def find_median_three_elements(my_list): return sorted(my_list)[1]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python" }
Show that $A/B$ is cyclic and determine its order for $A=\mathbb{Z}\oplus\mathbb{Z}$ and $B = \{(5m+7n,2m+4n)\mid m,n\in\mathbb{Z}\}$ > Let $A$ be the additive group $\mathbb{Z}\oplus\mathbb{Z}$ and let $B$ be the subgroup $\\{(5m+7n,2m+4n)\mid m,n\in\mathbb{Z}\\}$. Show that $A/B$ is cyclic and determine its order. I'm absolutely stuck here. Any push in the right direction would be appreciated!
Clearly $\mathbb Z=\\{5m+7n|m,n\in \mathbb Z\\}$, this means that every coset $(x,y)+B$ contains elements of the form $(0,z)$. We can thus only work with elements of the form $(0,z)+B$. When are two of these equal? We have $(0,z_1)+A=(0,z_2)+A\iff (0,z_1-z_2)\in A$ if and only if there is $m$ and $n$ with $5m+7n=0$ and $2m+4n=z_1-z_2$, we have $n=-\frac{5m}{7}$ so $m=7l$ and $n=-5l$, we must now have $14l-20l=z_1-z_2$ which has solution if and only if $z_1-z_2$ is a multiple of $6$. So the group has order $6$, and it is clearly cyclic, as the cosets can be represented by $(0,0),(0,1),(0,2),\dots,(0,5)$.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "abstract algebra, group theory" }
Ubuntu One music store - in my currency? I'm really curious about the Ubuntu One music store, but I noticed all the prices are in €, and my country doesn't use Euro. Can or will the UOMS translate the prices into sek for me?
There is no support for changing the display currency in the store. Since the purchases are via credit card, there shouldn't be any problems making purchases with the current exchange rate being used for the transaction.
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 3, "tags": "ubuntu one" }
Anchor can't find headings I have headings in all of my TFS 2018 Wiki documentation but I can't seem to link to those headings. If I have a document at `/foo/bar` and a heading in the `bar` document called `# 1.3 Hello World` I would expect my link to be `Hello World` but when I click on that link it doesn't take me to the heading. Instead, it just takes me to the document itself. When I look at the URL, it shows `&anchor=1.3-Hello-World` but that anchor is not scrolled to. In this example, I have to scroll pretty far in order to find the heading. How can I link directly to a heading in TFS 2018 Wiki markdown?
I don't believe anchor links are supported in **TFS 2018** Wiki. I can't get it to work and I find no evidence it is (presently) supported. Much or all of the material cited here refers to a different product, **Visual Studio Team Services (VSTS)** Wiki. Follow a link and notice the somewhat obscure top, left-hand (product) drop down list ( _Visual Studio Team Services_ ). Change it to _TFS 2018_ and notice that the reference material (documentation) changes. **TFS 2018** tends to be a bit behind the hosted VSTS product. I would not be surprised support is coming in a future release.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "tfs, markdown" }
Is there any limitation for the number of the return values from Solidity functions? Answer of this question (< says that: "I am not allowed to return dynamic arrays from Solidity functions yet." On the other hand, Solidity supports functions with multiple return values. How can I return multiple strings from a contract function? [Q] Is there any limitation for the number of the return values in one function call. Such as, could I return N (for example N=1000) number of values or even more in one function call? function getData() constant returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, ...) { bytes32 a = "a"; bytes32 b = "b"; bytes32 c = "c"; bytes32 d = "d"; bytes32 e = "e"; bytes32 f = "f"; bytes32 g = "g"; return (a, b, c, d, e, f, g, ...); } Thank you for your valuable time and help.
In practice, the call stack imposes a limitation in current implementations. The following contract will face a 'Stack too deep' compiler error. pragma solidity ^0.4.3; contract Test { function getData() constant returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) { return ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o"); } } Browser Solidity: < Gist URL: <
stackexchange-ethereum
{ "answer_score": 8, "question_score": 7, "tags": "go ethereum, solidity, contract development, contract invocation, contract deployment" }
What can be said about a function that is odd (or even) with respect to two distinct points? This question is a little open-ended, but suppose $f : \mathbb R \to \mathbb R$ is odd with respect to two points; i.e. there exist $x_0$ and $x_1$ (and for simplicity, let's take $x_0 = 0$) such that $$ (1): \quad f(x) = -f(-x) $$ and $$ (2): \quad f(x_1 + x) = -f(x_1 - x) $$ for all $x$. Then, the vague question I'd like to answer is > What else can we conclude about this function? It seems maybe I can conclude it is periodic, with period $2x_1$ (in general $2\left|x_1 - x_0\right|$): given the values of $f$ on $(0,x_1)$, $(1)$ determines the values on $(-x_1,0)$, then this and $(2)$ determine the values on $(x_1,3x_1)$, then this and $(1)$ determine the values of $f$ on $(-3x_1,-x_1)$, this and $(2)$ determine the values on $(3x_1,5x_1)$, and so forth. Is there anything else to say here?
You can conclude that it's periodic with period dividing $2x_1$, for essentially the reason you gave. On the other hand, if $f$ is odd (about zero) and periodic with period dividing $2x_1$, then $$ f(x_1+x)=f(2x_1-x_1+x)=f(-x_1+x)=-f(x_1-x) $$ and so $f$ is also odd about $x_1$. So "odd about two points" is equivalent to "odd and periodic."
stackexchange-math
{ "answer_score": 1, "question_score": 2, "tags": "algebra precalculus, functions, periodic functions" }
Adding Section/Chapter label to slide header I'm wondering if Powerpoint has a feature where I can automatically add a formatted header to each slide that displays the section and/or chapter. I'm presenting my thesis, and it is divided into sections, like "method" or "evaluation", and I would love it if I could automatically display that in the header of each slide. Preferrably, this would be automatically fetched from my powerpoint sections. I want this look, which I'm currently producing manually for each slide. ![enter image description here](
Here's a bit of starter code to get you the name of the section each slide belongs to. Over to you to provide the code to add the text to each slide and position/format it. Sub Test() Dim oSl As Slide ' Make sure there ARE sections If ActivePresentation.SectionProperties.Count > 0 Then For Each oSl In ActivePresentation.Slides Debug.Print GetSection(oSl) Next End If End Sub Function GetSection(oSl As Slide) As String ' Returns the name of the section that this slide belongs to. With oSl Debug.Print .sectionIndex GetSection = ActivePresentation.SectionProperties.Name(.sectionIndex) End With
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "powerpoint, naming" }
Url Mapping for a Web App built with Google Apps Script? A Web App built with Google Apps Script has a Url link like this: < Any idea how to map such Url to a friendly one like: app.myapp.mydomain.com
Web apps built with Google Apps Script cannot be served off of custom domains. You can create a redirect from your own domain, but the URL in the address bar must be script.google.com.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 5, "tags": "google apps script" }
callin' c from lua crashs while reallocating i got a crazy error within that for-loop matr=realloc(matr, newmax*sizeof(matr*)); for (i=0; i<newmax; i++){ matr[i]=realloc(matr[i], newmax*sizeof(int)); } matr is a multi-dimension array: int **matr. i need to resize column and row. first line resizes column and the for-loop resizes every row. it worked fine in c. now im working on a library for lua and it crashs here. compilin' works fine as well. but calling from lua crashs with lua: malloc.c:3552: mremap_chunk: Assertion `((size + offset) & (mp_.pagesize-1)) == 0' failed. i have no damn idea since it's working fine using it in c.
After calling `realloc`, the contents of the newly allocated portion are indeterminate. This means that then calling `realloc` on the new rows may fail because it tries to reallocate an invalid pointer. You can use `realloc` on the old rows and `malloc` on the new rows to fix this. Or you can zero the new part after the first `realloc`, and then your loop will work as is: matr=realloc(matr, newmax*sizeof(matr*)); for (i=oldmax; i<newmax; i++) matr[i] = NULL; for (i=0; i<newmax; i++){ matr[i]=realloc(matr[i], newmax*sizeof(int)); }
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 0, "tags": "c, lua, malloc, realloc" }
Java serialization with static initialization In Java, static and transient fields are not serialized. However, I found out that initialization of static fields causes the generated serialVersionUID to be changed. For example, `static int MYINT = 3;` causes the serialVersionUID to change. In this example, it makes sense because different versions of the class would get different initial values. Why does any initialization change the serialVersionUID? For example, `static String MYSTRING = System.getProperty("foo");` also causes the serialVersionUID to change. To be specific, my question is why does initialization with a method cause the serialVersionUID to change. The problem I hit is that I added a new static field that was initialized with a system property value (getProperty). That change caused a serialization exception on a remote call.
You can find some information about that in the bug 4365406 and in the algorithm for computing **serialVersionUID**. Basically, when changing the initialization of your `static` member with `System.getProperty()`, the compiler introduces a new `static` property in your class referencing the `System` class (I assume that the `System` class was previously unreferenced in your class), and since this property introduced by the compiler is not private, it takes part in the `serialVersionUID` computation. **Morality** : always use explicit `serialVersionUID`, you'll save some CPU cycles and some headaches :)
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 8, "tags": "java, serialization" }
Magento 2.3 - Why observer triggers multiple times on 'newsletter_subscriber_save_after' event? I am trying to send email when customer subscribes/unsubscribes from newsletter, however, my observer is triggering three times for some odd reason. Any ideas why or how to prevent it? The following code logs "Test" three times in the log files... Observer: <?php namespace VENDOR\MODULE\Observer; use Magento\Framework\Event\Observer as EventObserver; use Magento\Framework\Event\ObserverInterface; use Psr\Log\LoggerInterface as Logger; class NotifyAdmin implements ObserverInterface { public function __construct( Logger $logger ) { $this->_logger = $logger; } public function execute(EventObserver $observer) { $this->_logger->info('Test'); } }
There is a way to prevent it from having the observer react more than once, but it requires using the Registry to log the first call and skip any proceeding calls.
stackexchange-magento
{ "answer_score": 1, "question_score": 0, "tags": "magento2, magento2.3, event observer" }
Parse a date from a string I have String like this: String strDateTimeStamp = "2016-02-29 18:31:51"; Now I would like to extract it to get result in a below format: String strYear = "2016"; String strMonth = "02"; String strDate = "29"; String strHour = "18"; String strMinute = "31"; String strSecond = "51";
Try This.. String CurrentString = "2016-02-29 18:31:51"; String[] separated = CurrentString.split(" "); String date = separated[0]; String time = separated[1]; String[] separated_date = date.split("-"); String[] separated_time = time.split(":"); String strYear = separated_date[0]; String strMonth = separated_date[1]; String strDate = separated_date[2]; String strHour = separated_time[0]; String strMinute = separated_time[1]; String strSecond = separated_time[2];
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, string, date, extract" }
Where is the root path from the perspective of an Android app? The page on Picasso shows an example usage of its library Picasso.with(context).load(new File("/images/oprah_bees.gif")).into(imageView2); I suppose `images` is not actually in the root folder of the device, maybe the assets folder of the app?
> I suppose images is not actually in the root folder of the device According to that `File` object, that is exactly where it is. This is... unrealistic.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "android, filepath" }
regex to allow "single 0" or " any other number of digits? I need a regex to allow either a single 0 or any other number of digits that do not start with zero so: > 0 or 23443 or 984756 are allowed but 0123 is not allowed. I have got the following which allows only 1 to 9 [1-9]\d
Look for a lone 0 or 1-9 followed by any other digits. ^(0|[1-9]\d*)$ If you want to match numbers inside of larger strings, use the word boundary marker `\b` in place of `^` and `$`: \b(0|[1-9]\d*)\b
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "regex" }