INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Is it possible to make a substring out of a Guid in T-SQL? I have to truncate the first couple of digits out of a Guid on a table. Is it possible to do it only using a SQL script? Or I have to do it programatically? Thanks!
To answer the direct question at hand (and assume the column's name is `foo`): `foo` is uniqueidentifier: SELECT substring(convert(nvarchar(50), foo), 3) `foo` is simply a string: SELECT substring(foo, 3) _`3` is just an arbitrary starting offset to remove the first "few" characters._ With that said, this sounds like of like an XY problem. If you're running into an issue where you feel you need to truncate the first few characters, it would be important to list that information in your question as well as what you've described sounds like an odd request. However, you're also entitled to have odd requests.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "sql server, tsql, substring, guid, truncate" }
Incremental variable naming convention like i, but for an inside For statement? This is the example: for(int i = 0; i < 10;i++) { for(int ? = 0;? < 10 ; ?++) { } } I usually use an "o" for the second loop, but is there any standard out there? ideas?
Logically, you would use 'j', but the best is to use something meanlingful, like 'row' and 'column' if you can. If you feel like joking, use 'c' or 'notepad'
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "for loop, coding style, naming conventions" }
Receiving webhook from GitHub from C# Console App I'd like to capture webhooks from GitHub (for various events, like commits, etc), from my C# console application. I figured I could "listen" to an endpoint and webhooks would be thrown there, but it seems that perhaps github is actually sending webhooks to endpoints that you need to setup and listen from. If the latter is this case, then I suppose I'll need to setup a web server to capture the webhooks. If the former is the case, then I'm not finding in the docs how I can listen for webhooks from GitHub?
Your question isn't very clear, but I think you're on the right track vis-a-vis implementing a web server. So, my answer to your question is: you need to implement a web server to receive the webhook requests. _Edit_ At the bottom of this document, you will find instructions on how to implement a very simple web server (in Ruby) to receive **GitLab** webhook requests. I know this isn't a turnkey solution for you, but hopefully it will help get you going.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, github, webhooks" }
For loop output in one line How can I write a Batch script, with a for loop like this: @echo off for /l %%a in (1,1,100) do ( echo %%a ) and get the output in one line, instead of: 1 2 3 4 5 .. ..
@echo off for /l %%a in (1,1,100) do ( echo|set /p="%%a " )
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "loops, file, for loop, batch file" }
Question about apply integrals in finding volume of a pyramid? !enter image description here The answers entered already is what I got but either one or both are wrong. Can someone help me solve this problem?
The first entry is right, if you choose $y=0$ at the bottom of the pyramid. So the volume is $$\int_0^{10}\frac{1}{4}(10-y)^2\,dy.$$ There must have been slippage in the evaluation of the integral, it should be $\frac{250}{3}$. **Remark:** I would prefer to assume that the pyramid is pretty light, and turn it upside down, with the "apex" at the origin. Then the area of cross-section is $\frac{1}{4}y^2$, somewhat more pleasant.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "calculus, integration, volume" }
why cannot i import enum to my angular2 component? I have this enum under the folders: `country-details/enum` export enum ConfigTypes { STAFF, PROD } and I try to import it to another component, though I get a `cannot resolve symbol` error even though my component is in the root folder which contains `country-details` folder import {ConfigTypes} from "country-details/enum"; what am i missing?
Path should be "./country-details/enum" > import {ConfigTypes} from "./country-details/enum";
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "javascript, angular, typescript, enums" }
Solve $(2z-1)^5 - i = 0$ > Solve $(2z-1)^5 - i = 0$ I started by saying that $(2z-1)^5 = i$ $(2z-1) = \sqrt[5]i$ $z =$ $(\sqrt[5]i +1) \over 2$ $z^5 =$ $(i +1) \over 32$ $z^5 =$ $1 \over32$$ *(i +1)$ From there, it's quite simple.. showing $z^5$ as $r^5Cis(5o)$ with da-muaver and showing $(1+i)$ as $\sqrt2 $$ Cis({\phi\over 4})$
Hint : $\cos \theta+i\sin \theta=\sqrt[5]{i}\Rightarrow (\cos \theta+i\sin \theta)^5=i\Rightarrow \cos 5\theta+i\sin5\theta=i\Rightarrow \theta = ??$
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "algebra precalculus, complex numbers" }
Sending commands to the terminal from a script How do you send commands to the terminal in a perl script? For example, if I want to run the command `mkdir $directory` in the console, what do I type in the perl script?
Modeling off the sample code in the documentation at < @args = ("mkdir", $directory); system(@args) == 0 or die "mkdir failed"; Perl can make directories without `system()` calls, but I assume you want to do other things and are just using mkdir as an example.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "perl" }
Can a simple SELECT statement block processes when there is no open transaction? I encountered a weird scenario a couple of days ago, when a simple SELECT statement that returned 4 rows of data was causing a blocking chain in SQL server. There was no open transactions. Any inkling why this might occur?
> Yes a simple SELECT statement can endup in deadlock , Imagine a scenario where User1 is only reading data and User2 trys to Update some data and there a non-clustered index on that table, it is possible. > > 1) User1 is reading Some Data and obtains a shared lock on the non-clustered index in order to perform a lookup, and then tries to obtain a shared lock on the page contianing the data in order to return the data itself. > > 2) User2 who is writing/Updating first obtains an exlusive lock on the database page containing the data, and then attempts to obtain an exclusive lock on the index in order to update the index. `Read here` to learn more about locking in sql-server.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "sql, sql server" }
How to make changes istio-ingressgateway when using GKE Istio Addon? I have google cloud gke cluster installed with istio via addon. I need to change the istio-ingressgateway to NodePort. the problem is that the addon manager is always reverting my changes. Is there a way to disable it from reverting to the original ingressgateway? Thanks
You can't make any changes to the istio pods when using the istio on GKE addon. All of the resources in the istio-system namespace are managed and include the label "addonmanager.kubernetes.io/mode: Reconcile" which causes any changes you do to be reverted. The general consensus is that the istio addon is meant more to be a demo, advanced users should install istio manually and use the unamanaged version
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "google kubernetes engine, grpc, kubernetes ingress, istio, google cloud load balancer" }
SQL limit not working: what is the right syntax? I have a simple question, and I am sorry in advance if this is too basic. I am connecting to a remote database using import pyodbc import pandas as pd import numpy as np cnxn = pyodbc.connect('DSN=MYDSN') and I am able to pull some data using sql = "SELECT * FROM MASTER.PRICES" dataframe = pd.read_sql(sql, cnxn) However, using the query sql = "SELECT * FROM MASTER.PRICES LIMIT 10" sql = "SELECT * FROM MASTER.PRICES where ROWNUM <= 10" give an error such as > Unable to parse query text: Incorrect syntax near "SELECT", found "10". for the first query. My questions are: * without further information about the database, how can I know what is the right syntax for a LIMIT statement? * How can I even know what kind of database I am accessing? Thanks!
I think you are looking in the wrong place. Yes, it is best practice to use `ORDER BY` before `LIMIT` but not strictly needed on MySQL. However that does not explain the syntax errors. The syntax error suggests that something is going wrong in a different direction. Note tat it is near `SELECT` and not near `LIMIT` which makes me wonder if you have assembled your query in a way you are not telling us. Maybe you copied and pasted things in and got a funny unicode character instead of a whitespace? But I don't see anything wrong with the way you are using `LIMIT` from a purely syntactic way and I bet if you type it in a mysql client you get no syntax errors.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "sql" }
Numbers above the notes on a music sheet I am wondering what the numbers above the notes (1 up to 16) on the second line seen in the picture mean ? In other words, how should one play these notes? It is an excerpt from Sympthony No 9 from Schubert. Thanks. ![Numbers 1–16 and 1–7 above identical tremolos](
The numbers are just to help keep track of how many times the repeated note has been played. With that many measures playing exactly the same thing, it's easy to lose track. They don't affect the execution of the music.
stackexchange-music
{ "answer_score": 12, "question_score": 7, "tags": "theory, violin" }
Matrices in an equation It must be an easy one, but I do not figure out how to solve it. $$Z^2\cdot\begin{pmatrix}3 & 0 \\\ 0 & 3\end{pmatrix}\cdot Z^{-1}=\begin{pmatrix}1 & 3 \\\ 1 & 2\end{pmatrix}$$ being $Z$ a matrix. EDIT: Ok, I have it know haha! Thank you guys. Now it's the time I tell you I study Electrical Engineering and all of you can laugh at me because I didn't know how to solve a high school problem (YAI!)
Hint: Bring a scalar out from one of the matrices.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "matrices, matrix equations" }
How do I return an int from EditText? (Android) Basically, I want an EditText in Android where I can have an integer value entered into. Perhaps there is a more appropriate object than EditText for this?
For now, use an `EditText`. Use `android:inputType="number"` to force it to be numeric. Convert the resulting string into an integer (e.g., `Integer.parseInt(myEditText.getText().toString())`). In the future, you might consider a `NumberPicker` widget, once that becomes available (slated to be in Honeycomb).
stackexchange-stackoverflow
{ "answer_score": 151, "question_score": 71, "tags": "java, android, android edittext" }
What interval is from G♭ to A♯ (same octave)? It is a number 2 interval, but being 4 semitones, it is beyond an augmented second. So, what it is?
The interval from any G (flat / sharp / neutral) to any A (flat / sharp / neutral) (in the same octave) is always a _second_. In your case, since the G is flat and the A is sharp, you have a _doubly augmented_ second. Of course, this interval is sonically equivalent to a major third.
stackexchange-music
{ "answer_score": 20, "question_score": 9, "tags": "intervals" }
Bing API Report Unzip I'm loading a CSV file from Bing Reporting API. The documentation says "The report file is compressed; therefore, you must unzip it to read the report.", so I save the raw file as shown in the example, but I can't get SharpZipLib, 7Zip, or WinRar to read the compressed data. How can I decompress Bing API reports?
To answer my own question, I was able to get SharpZipLib to read the compressed data, but only after copying it to a seek-able memory stream first. This isn't the best solution for arbitrarily large files, but I'm reasonably confident our specific data won't get too large.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "zip, bing api" }
Firestore Batched Writes operations sequence guarantee Are operations in a batch write guaranteed to be executed in the order of their calling? it's not clear according to the docs. Is it forced to be only (#0) -> (#1) -> (#2) and not other way? const batch = db.batch(); const nycRef = db.collection('cities').doc('NYC'); batch.set(nycRef, {name: 'New York City'}); // (#0) const sfRef = db.collection('cities').doc('SF'); batch.update(sfRef, {population: 1000000}); // (#1) const laRef = db.collection('cities').doc('LA'); batch.delete(laRef); // (#2) return batch.commit().then(function () { // ... });
The changes in a batch don't have an order. They happen atomically all at once, or not at all. There is no way any client could get a view of the database with an incomplete batch. Any security rules that apply to documents the batch will see all documents changed at the same time. The security rules do **not** apply to individual documents in sequence. If you use getAfter() in security rules to fetch the contents of documents that were changed from the batch, each call to getAfter() will only ever see the new data. There is never an intermediate state where documents updated from a batch appear to be incomplete. If you have any Cloud Functions triggers on documents that could be updated by a batch, there is no defined order of execution - they could execute concurrently, or in some apparently "random" order.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 5, "tags": "firebase, google cloud firestore" }
update source code of locally installed pip package I installed my package with `pip install -e .` If I now change something in the source code, do I need to run `pip install -e .` again or will it consider the updated source files when I run the program? Thanks for your help! Tamme
No, you don't need to reinstall the package. That's what the editable install (mentioned by the `-e` option) does; instead of installing the package to site, it only puts a link to the source files. However if you modify the package metadata (things like author's name, description, version etc. the stuff found in `setup.cfg` or `setup.py`) that wouldn't be carried over, for that change to reflect you need to reinstall the package.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, pip" }
What is the name of this practice when a page loads? It seems that some basic elements take their position quite quickly: ![enter image description here]( and then others follow to form the final page: ![enter image description here]( # update (Apr 2018) I've noticed that youtube is also doing this... ![enter image description here](
It's called a **content placeholder** or **skeleton screens**. This is a great way to **focus attention** on progress and **content being loaded** instead of wait times while the whole app is loading. * * * **About Skeleton screens** Apple have incorporated skeleton screens into its iOS Human Interface Guidelines, calling it "launch images." It recommends showing an outline of the initial application screen without text or any graphical elements that may change. ![enter image description here]( **About content placeholder :** Facebook App (and some other mobile app) made this strategy famous, making users think their apps loads faster. ## ![enter image description here]( * * * Sources : * < * < * < * <
stackexchange-ux
{ "answer_score": 0, "question_score": 0, "tags": "loading, page layout, placeholder, content loading" }
How to solve the Boundary value problem using finite difference method I am solving Boundary value problem using finite difference method from a reference book, but one of the step is not quite clear to me - for more clear view I am sharing a screen shot of that question below. Can anyone help me how that step comes? I had shown that step with the red marker. Please explain me how that step comes? **Question Screenshot**
The line you marked is: $$16y_{i+1} - 33y_i + 16y_{i-1} = x_i, \quad i = 1,2,3. $$ It comes from the previous line by substituting $$h=1/4, \ \ \ {1\over h^2}=16$$ and then subtracting $y_i$ from both sides of the equation.
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "boundary value problem, finite differences" }
"Weakened Sophie Germain" primes Is there a name for a prime $p$ such that $2p+1$ has no prime factors less than a given positive integer $k$? Is there an infinite number of such primes for every positive integer $k$? This question arose while trying to fix this previously erroneous answer, recently corrected by the poster after prompting by me when this answer helped me understand what might possibly have gone wrong. I think it is still useful as justification for the scarcely documented argument there, and I am considering either adding a comment there or editing that answer to add this as a reference.
Yes, this is easy to arrange using Dirichlet's theorem. For $p_2, p_3, \dots $ an enumeration of the odd primes consider the system of congruences $$2p + 1 \equiv 2 \bmod p_i, 2 \le i \le k$$ which has a solution $\bmod p_2 \dots p_k$ by the Chinese remainder theorem. This gives an arithmetic progression (with no common factors) such that any prime in that arithmetic progression has the property that $2p + 1$ is not divisible by $2, p_2, \dots p_k$, and by Dirichlet's theorem there are infinitely many such primes.
stackexchange-math
{ "answer_score": 1, "question_score": -1, "tags": "number theory, prime numbers" }
Prove that there is a unique homomorphism from $\mathbb{Z} [i]$ to $\mathbb{Z}/2\mathbb{Z}$. > Prove that there is a unique homomorphism from $\mathbb{Z} [i]$ to $\mathbb{Z}/2\mathbb{Z}$. I'm struggling to show uniqueness here. In the past I have shown that $\mathbb{Z}[i]/(1+i)$ is isomorphic to $\mathbb{Z}/2\mathbb{Z}$, and from this past work I am convinced that the homomorphism in question is in fact $$ x+yi \mapsto x-y \mod 2. $$ How do I even begin to show uniqueness here? Thanks in advance. Edit: To clarify, we are working with only commutative rings with unity in our course, and our definition of a ring homomorphism includes the clause that $\phi(1) = 1$.
This is only true if $1$ is sent to $1$. If that is the case, let $f$ be the homomorphism. Then $f(i)^2=f(-1)=-f(1)=1$, hence $f(i) =f(-i) =1$. Since the ring is generated by $1$ and $i$, the homomorphism is completely determined.
stackexchange-math
{ "answer_score": 5, "question_score": 4, "tags": "abstract algebra, ring theory, ring homomorphism, gaussian integers" }
Get value of column related to value of column in other rows I've a current table like this !current table and would like to obtain this desired table: !desired table As you can see, this desired table should have a fourth column which indicates me the proportional value of the price in this row in relation with the rest of values of the row for the same product For example, for product type A I have three products (1,2 and 3), and the prices are, respectively, 20, 20 and 30. In this case, for product 1 I'd like to obtain its weight as (price of product/sum of prices of the products that belong to product A). How is this possible? Thanks
We can try using `SUM()` as an analytic function here: SELECT PRODUCT, PRODUCT_TYPE, PRICE, 1.0 * PRICE / SUM(PRICE) OVER (PARTITION BY PRODUCT_TYPE) AS WEIGHT FROM yourTable; The idea here is that the above `SUM()` is a window function which computes the sum of the total price for each product type. This is then used to normalize each price, for each record. ![enter image description here]( ## Demo
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, postgresql, group by" }
How to access members of child class by using reference of parent class? Let there are classes: class Parent { public Parent getParent() { ... } } class Child extends Parent{ public Parent getChild() { ... } } //instantiating Child by using reference of Parent Parent parent = new Child(); when I use: //Works fine Parent parentObject = parent.getParent(); When I use: //Doesn't works Child childObject = parent.getChild(); But when type cast object: //Works fine Child childObejct = ((Child)parent).getChild(); being as programmer this is something hectic to type cast explicitly for every call where I wanted to use child members by reference of parent class.
It is not so complicated. When you have an up-cast, it is simple for the compiler to determine the real type and do the cast because you know every class is simply extended from one parent. But when you are down-casting an object, compiler can not infer that an object with a Parent reference is which Child object in the runtime because every Parent class can have multiple Child class. Good Luck.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "java, inheritance, design patterns" }
Syntax error when trying to insert from a mysql trigger I'm trying to create a trigger to insert into a new table using values from two different tables (I'm using MySQL 5.5.27). I get a syntax error when I try this but cannot see where the error is. DECLARE _Token VARCHAR(255); SELECT token INTO _Token FROM appusers ON username = NEW.username; INSERT INTO queue (token, message) VALUES (_Token, NEW.milestone); My assumption is that it doesn't like the DECLARE because when I use the following I get message that _Token is an undeclared variable. SELECT token INTO _Token FROM appusers ON username = NEW.username; INSERT INTO queue (token, message) VALUES (_Token, NEW.milestone);
Try do it with a single insert statement INSERT INTO queue (token, message) SELECT token, NEW.milestone FROM appusers WHERE username = NEW.username;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "mysql, triggers" }
Did the original Bem have a manga that was based on? As far as I know, the 2019 BEM series is based in a late 60's anime of the same name. Did that anime have an original manga version? Or did the story start with the anime?
**All _Humanoid Monster Bem_ anime are original**, but they also spawned manga adaptation. The first _Humanoid Monster Bem_ anime in 1968 got its manga adaptation and was serialized in _Bokura_ monthly manga magazine until 1969, then reissued by _Kodansha_ in 2012 and got its paperback edition in 2010. The second anime in 2006 got its manga adaptation and was serialized in _Weekly Young Jump_ and _Mankaku_ , then got its tankobon version in 2007. The third anime, _BEM_ in 2019 got its manga adaptation and was serialized in _Manga Park_ application. * * * The manga spin-off _Humanoid Monster Bem RETURNS_ was the only original manga, which was serialized in _Monthly Shonen Gangan_ since 1993 until 1995. The anime (and game) adaptation was planned in 1997 but got canceled, and thus leaving only the manga. * * * Source: Japanese Wikipedia
stackexchange-anime
{ "answer_score": 1, "question_score": 1, "tags": "bem" }
Is AutoFS necessary? In Solaris 11, if I have a single system (NAS), with no other users other than myself, can I delete autofs mappings? To me it seems confusing to have things in two separate folders (/export/home & /home). But what I really want to know if it will break anything important. Thanks!
No, it's not necessary. It's a throwback from the old Sun days when their motto was "The Network Is The Computer" - and thought that everyone would use NIS (or NIS+) and NFS home directories. If you're not using these then autofs can safely be turned off and /home returned to your control. Although disabling the service with `svcadm` should be enough, you might also want to edit `/etc/auto_master` and remove the entry for `/home`, just in case.
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "solaris, autofs" }
For electrical outlets that have on/off switches, is energy sent to the socket when nothing is connected to it but the switch is on? In several countries, electrical outlets have physical on/off switches used to control the energy flow sent to the connected appliance. If the switch is set to the on position but nothing is connected to the socket, will any energy be used/wasted?
A switched outlet with nothing plugged into the outlet will generally not consume any power when the switch is turned on. There are a few cases where this may not be totally true. Some outlets may have an indicator to show that the outlet has a live power connection and the indicator circuit will consume a small amount of power. Some indicators would be a neon bulb, others LED and some may be small incandescent bulbs. Each type will consume a small but different amount of power.
stackexchange-electronics
{ "answer_score": 7, "question_score": 2, "tags": "socket" }
How do I trim space in an input field? I am using an input field and when someone types in it they can add spaces as general behavior. I do not want anyone to add spaces into the field and even if someone adds one it should trim there and then. Can someone please help on how to achieve this? <input type="text">
You can use `trim()` function. This is destroys spaces. const inp = document.querySelector("#inp"); inp.addEventListener("input", function() { inp.value = inp.value.replace(' ', ''); }) <input type="text" id="inp">
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -2, "tags": "javascript, jquery, html, css" }
$ \int\limits_C {\left( {z - z_0 } \right)^m dz} $ Evaluate the line integral $ \int\limits_C {\left( {z - z_0 } \right)^m dz} $ , where $C$ is the circle centered at $z_0$ with radius r>0, and: $i)$ $m$ is an integer $m \geqslant 0 $ $ii)$ m is an integer $m<0$ I want to see how can I solve this , to see some examples of integrals )=.
Parameterize the circle by $C(t) = z_0 + r e^{it} $ with $t\in (-\pi,\pi].$ Using the definition of a path integral, $$ \int_{\gamma} f(z) dz = \int^b_a f(\gamma(t)) \gamma'(t) dt$$ we have $$ \int_{C} (z-z_0)^m dz = \int^{\pi}_{-\pi} r^m e^{imt} ire^{it} dt = ir^{m+1} \int^{\pi}_{-\pi} e^{i (m+1)t} dt.$$ Now if $m+1\neq 0$ then the last integral is simply zero, seen either by direct evaluation or noting that the exponential goes through exactly $|m+1|$ periods. If $m+1=0$ then the integrand is $1$ and the value of the integral is thus $2\pi i.$ To summarize, $$\int_C (z-z_0)^m \, dz = \left\\{ \begin{array}{lr} 2\pi i \text{ if }m=-1 \\\ 0 \text{ if } m\in \mathbb{Z}\setminus \\{-1\\} \end{array} \right.$$
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "complex analysis" }
ko.utils.arrayFirst = function (array, predicate, predicateOwner) { /* .. */ } what does predicateOwner mean , i couldn't find an answer ?! like this: How to use indexOf in KnockoutJS or that <
Last parameter of _arrayFirst_ \- is context that would be assigned to predicate's scope: var array = ko.observableArray([1,2,3]); var context = "Hello"; var result = ko.utils.arrayFirst(array(), function(item) { // 'this' is equal 'context' console.log(this); return item === 2; }, context); <script src="
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "knockout.js" }
Why AWS CloudWatch Log Group and Stream Name cannot be changed? I was trying to change AWS CloudWatch Log Group and Stream Name as follow: cat <<EOT >> /etc/awslogs/awscli.conf [/var/log/messages] file = /var/log/messages log_group_name = MY_LOG region = ap-southeast-1 log_stream_name = {instance_id} datetime_format = %b %d %H:%M:%S EOT And I've tried to stop and start CloudWatch agent, log group name and stream name could not be changed as expected. Please help me how to do it.
It should be `/etc/awslogs/awslogs.conf` and not `/etc/awslogs/awscli.conf`. The rest of your configuration file looks fine. You can also check your `/var/log/awslogs.log` for eventual error messages linked to IAM permissions. See also Why can’t I push log data to CloudWatch Logs with the awslogs agent?.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "amazon web services, amazon cloudwatch" }
Cannot import python package installed from URL I tried to install a python package within a `conda` environment using pip install git+ This seems to work. The package seems to be there according to `conda list` and `pip list`, but when I try to import it, it cannot be found: >>> import logisticnormal ImportError: No module named logisticnormal I can see the source code in $ENV/lib/python2.7/site-packages/logisticnormal so I really don't see a reason why it should not be found. Any help is really appreciated!
The problem was silly, of course. I was testing the import using `IPython` and didn't realise that my conda environment (which I created specifically for testing all of this) didn't come with ipython - so I was using the system's ipython which didn't know about the installed package. To diagnose this, I ran (venv)$ ipython >>> import sys >>> print sys.path ['/usr/bin','/usr/lib/python2.7', etc] And to fix it I ran (venv)$ pip install ipython (venv)$ ipython >>> import sys >>> print sys.path ['ENV/bin', 'ENV/lib/python2.7', etc] >>> import logisticnormal
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "pip, setuptools, conda" }
PHP Environment Variables I'm not sure why I'm still getting the PHP is not recognized as an internal or external command error. Here's my environment variables: C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\EgisTec MyWinLocker\x64;C:\Program Files (x86)\EgisTec MyWinLocker\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\strawberry\c\bin;C:\strawberry\perl\site\bin;C:\strawberry\perl\bin; C:\PHP\; My PHP.exe is located in "C:\PHP\", so I'm not sure why I'm getting this error. :/
I don't have a Windows machine to verify this, but I am pretty sure you cannot have spaces after the `;` delimiters. Remove the space before `C:\PHP`, and it may be harmless, but also remove the trailing `\`. C:\Program Files (x86)\NVIDIA Corporation\;...snip...;C:\strawberry\perl\bin;C:\PHP -------------------------------------------------------------------------^^^^^ Depending on how you are launching PHP, you might need to log out of Windows and back in to propagate the new `%PATH%` through your environment, though I doubt that's necessary.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "php, windows" }
Questions while setting up the combo XBOX360 + TV + Home Theater I'm trying to set up a little combo to enhance the quality of the overall play. Did someone succeed at setting up an XBOX360 to play games on a TV and output the audio through a Home Theater? I thought that if I can connect the XBOX using HDMI to the TV and use the common connectors with the home theater I might be able to do it, but the ports for both connections are way too close, and I can't connect both. Any Ideas?
You need the MS Audio out connector if you want hdmi to your tv and audio to a separate receiver. Amazon has them for fairly cheap. This is the setup I use, and it works just fine. The only oddity is that if I don't have my tv on hdmi before I turn the xbox on, it boots into analog output mode. When I switch my tv over the xbox reboots into hdmi mode. Doesn't really affect anything, but it's weird. That assumes you are using optical audio connections though. If you just want stereo, you don't need anything new, just modify your current xbox cable a bit. Instructable here but it basically says pry the plastic spacer off the xbox cable, wrap the metal in electrical tape just in case, and both connectors will fit just fine.
stackexchange-gaming
{ "answer_score": 1, "question_score": 0, "tags": "xbox 360" }
Javascript Regex Split Words that ends with dot, exclamation, question mark, comma and on whitespace I need to split a string on words that ends with a dot, exclamation/question mark, comma and space. For example: `var s = "An example, string, That have weird? formatting!"` When on `s.split()` will result in: `["An", "example", ",", "string", ",", "That", "have", "weird", "?", "formatting", "?"]`
You should probably use match() with grouping to get what you want and not use split. The basic idea is match a word or match the special characters. var str = "An example, string, That have weird? formatting!" var result = str.match(/(\w+|[,?!])/g) console.log(result)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "javascript, regex, split" }
Hibernate in JBoss drools Rule is showing the following error when using with hibernate > [22,22]: [ERR 102] Line 22:22 mismatched input 'FROM' expecting '(' in rule "Name" in pattern Contact I am inserting: static SessionFactory sessionFactory = null; static{ sessionFactory = new Configuration().configure().buildSessionFactory(); } session =sessionFactory.openSession(); ksession.setGlobal("hibernateSession", session); Once I add drools to the knowledge builder before inserting rules package drools //list any import classes here. import droolsexec.Contact; //declare any global variables here global org.hibernate.Session hibernateSession; rule "Name" dialect "java" when // message: Message( status =="GOODBYE" ) contact: Contact from hibernateSession.createQuery("from Contact").list(); then System.out.println( contact.getFirstName()); end
I believe the parentheses are required in the `Contact`, as: when contact: Contact() from ... then ...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "hibernate, jboss" }
How can i filter consecutive data rows btw NaN rows in a pandas dataframe? I have a dataframe that looks like the following. There are >=1 consecutive rows where y_l is populated and y_h is NaN and vice versa. When we have more than 1 consecutive populated lines between the NaNs we only want to keep the one with the lowest y_l or the highest y_h. e.g. on the df below from the last 3 rows we would only keep the 2nd and discard the other two. What would be a smart way to implement that? df = pd.DataFrame({'y_l': [NaN, 97,95,98,NaN],'y_h': [90, NaN,NaN,NaN,95]}, columns=['y_l','y_h']) >>> df y_l y_h 0 NaN 90.0 1 97.0 NaN 2 95.0 NaN 3 98.0 NaN 4 NaN 95 Desired result: y_l y_h 0 NaN 90.0 1 95.0 NaN 2 NaN 95
You need create new column or `Series` for distinguish each consecutives and then use `groupby` with aggreagte by `agg`, last for change order of columns use `reindex`: a = df['y_l'].isnull() b = a.ne(a.shift()).cumsum() df = (df.groupby(b, as_index=False) .agg({'y_l':'min', 'y_h':'max'}) .reindex(columns=['y_l','y_h'])) print (df) y_l y_h 0 NaN 90.0 1 95.0 NaN 2 NaN 95.0 Detail: print (b) 0 1 1 2 2 2 3 2 4 3 Name: y_h, dtype: int32
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "python, pandas, dataframe, filter" }
How to execute different classes in one class I want to create a program that can do all the stuff from another code, depending on user input. Something like this: import java.util.Scanner; public class Main_Programm1 { public static void main(String args[]) { String something = "something"; String something2 = "something2"; Scanner userInput = new Scanner(System.in); String action = userInput.next(); if (action.equals(something)) { //here i want to execute all the code from class Main_Programm2 } else if (action.equals(something2)) { //here i want to execute all the code from class Main_Programm3 and so on } } } How do i do it?
Actually, you've got it all done, only creates the Objects that you need ;-) import java.util.Scanner; // imports classes; public class Main_Programm1 { public static void main(String args[]) { String something = "something"; String something2 = "something2"; Main_Programm main_prog; Main_Programm2 main_prog2; Scanner userInput = new Scanner(System.in); String action = userInput.next(); if (action.equals(something)) { main_prog = new Main_Programm(); //..... } else if (action.equals(something2)) { main_prog2 = new Main_Programm2(); //..... } } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, class" }
Liferay - Exporting User-Generated Content We are currently evaluating Liferay for our non-profit organization, and there's one concern that I have not been able to find an answer for: Is there a way to export the user-created content (e.g. blog posts, wiki articles, forum discussions) into a structured format (e.g. xml, excel)? In case we need to move away from Liferay in the future, we'd like to know that we can at least salvage all of the content that the users have created. Thanks in advance for the help! AL
copying my answer from the liferay forum to the same question (there's more, but I didn't want to embrace the other answer(s) as mine here: In addition to the LAR export already mentioned, Liferay provides a full API to access all your content where you can access it in any way you like - e.g. only articles, by page, users etc. To take a look at the content creation part of that API (barely reading) you can look at sevencogs-hook (sourcecode available in svn) - this creates the full demo site through the API. Equivalent reading functionality is available, though not that readily available in a full-blown sample to easily point to. The API is accessible through Java or Webservices.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "export, liferay" }
/sys/bus/pci/devices/<B:D:F:>/rescan file missing on Ubuntu Kernel 5.4.14.050414-generic On my ubuntu I am missing rescan files under `/sys/bus/pci/devices/<B:D:F:>/` Does anyone know how to restore them? Can I simply copy them from `/sys/bus/pci/rescan` ? 1. Ubuntu : 16.04.6 LTS 2. Kernel: 5.4.14.050414-generic 3. NVMe driver version: 1.0
In Kernel 5.4 and later: * `rescan` in `/sys/.../<domain:bus:dev.fn>/` was renamed `dev_rescan` (for PCI devices) * `rescan` in `/sys/.../pci_bus/<domain:bus>/` was renamed `bus_rescan` This caused application breakage and there is a proposed patch to revert the behaviour
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ubuntu 16.04, nvm, pci, pci e, nvme" }
How can I tell if a streamwriter is closed? I'm using a streamwriter in combination with a background worker, for logging. As such, I have System::Void MyUI::execBWorker_DoWork(System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) { String^ outputPath = _clr::Settings::ApplicationLogPath("_log.txt", true, false); logfile_ = gcnew StreamWriter(outputPath,true); DoStuff(); logfile_->Close(); } Things in the DoStuff() method raise the Progress event. System::Void MyUI::execBWorker_ProgressChanged(System::Object^ sender, System::ComponentModel::ProgressChangedEventArgs^ e) { logfile_->WriteLine("something"); } I think this really smells. How can I make it better, or at least how can I check the logfile hasn't been closed? There are a lot of messages, so I'm concerned about opening and closing the logfile continuously.
If the `StreamWriter` is closed, the `BaseStream` property will return `null`.
stackexchange-stackoverflow
{ "answer_score": 24, "question_score": 12, "tags": ".net, c++ cli, clr, backgroundworker, streamwriter" }
Counting how much number are in ascending order in a row I need to write function that will count how much numbers are ordered in ascending order in a row. for example: we have this list: L = [2, 4, 5, 6, 7, 2, 3, 2, 2, 2, 8, 7, 5, 6] and the largest ascending series of numbers are 5. I've tried: count=0 def ascord(L,count): for i in range(0,len(L)-1): if L[i]<L[i+1]: count+=1 return count but the output is 7. I don't know how to "reset" count so it wouldn't take [2,8] and [5,6] into consideration Edit: I meant that if I for ex. add at the end of list twenty numbers in asc. order they will be largest series of numbers, so the first count should be set to 0, and start counting from start PS. Sorry for my english.
Cleaned up: def ascord(L): answer = 0 count = 1 for i in range(len(L) - 1): if L[i] < L[i + 1]: count += 1 else: if count > answer: answer = count count = 1 return max(count, answer) L = [2, 4, 5, 6, 7, 2, 3, 2, 2, 2, 8, 7, 5, 6] print (ascord(L)) # 5 cheers :)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, python 3.x" }
Warm, round, and 40 Mm long Here is an easy riddle that I came up with. I don't expect it to take long to crack. > I am warm, round, and 40 Mm long. Who/What am I?
> The equator is 40 Megametres long, warm, and round.
stackexchange-puzzling
{ "answer_score": 3, "question_score": 1, "tags": "riddle" }
Ionic 2/3 Pushing items in Array based on ID I'm looking to push items from one page to another, based on the category ID. Then I went to push all the contents from the array(who have the category ID that matches) to the next page. I'm caught between using an if statement to pass the parameters to the second page, or to call the array in the second page and use an NgIf. Below is my code for a better visual. I'm fairly new to Ionic. Thank you for the help! First Page if(id = 1) { category_id: this.referenceList.category_id = 1; this.navCtrl.push(ReferencePage,{category_id:"category_id"}); } else { console.log("nope") } Second Page <div *ngfor = let reference of referenceList></div> <div *ngif = category.id === 1> {{reference.referenceField1}} {{reference.referenceField2}} {{reference.media}} </div> Not sure which one to use and why. Thanks again! Happy to clarify if there's any confusion.
You stored the `category_id` in a variable, so use this: `this.navCtrl.push(ReferencePage,{category_id:category_id});` In the second page controller you need: import ( NavParams ) from 'ionic-angular'; category_id: number; constructor(public navParams: NavParams) { ... } ionViewDidLoad() { this.category_id = this.navParams.get('category_id'); } Also, your `html` should be (if I understand what you are doing): <div *ngFor = let reference of referenceList> <div *ngIf = category_id === 1> {{reference.referenceField1}}; {{reference.referenceField2}}; {{reference.media}}; </div> </div>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ionic framework, ionic2, ionic3" }
jquery get msg of specific class only In the following i am trying to track the last element that is getting inserted into `p-msg-class` class, but i see the alert a lot of times since the there are other elements inserted dynamically to `.middle-ui,.flt-rt,.content-ht` . how can i track only `p-msg-class` and make the alert stop for all the other html inserted dynamically $('.middle-ui,.flt-rt,.content-ht').bind('DOMNodeInserted', function(event) { if($(this).find(".visitor-msg-cont").last().find(".p-msg-class").length > 0) { alert($(this).find('.visitor-msg-cont').last().find('.p-msg-class').last().html()); } });
Ok something like this could work. Get the class of the last element added and check if it is "p-msg-class". $('.middle-ui,.flt-rt,.content-ht').bind('DOMNodeInserted', function(event) { var newElement = $(this).find(".visitor-msg-cont").last().children().last().attr("class"); if(newElement === "p-msg-class") { alert($(this).find('.visitor-msg-cont').last().find('.p-msg-class').last().html()); } }); if you know the child elements will be all div or p then you can use `children(div:last)` or something like that. Not sure this will work but it could point you in the right direction.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery ui, jquery, dom" }
Python: Flask uWSGI thread stops when making a network call I have a flask server running on top of uWSGI, with the following configuration: [uwsgi] http-socket = :9000 plugin = python wsgi-file = /.../whatever.py enable-threads = true The flask server has a background thread which makes periodic calls to another server, using the following command: r = requests.get(...) I've added logging before and after this command, and it seems that the command never returns, and the thread just stops there. Any idea why the background thread is hanging? Note that I've added `enable-threads = true` to the configuration. **Updates** * I've added a timeout parameter to requests.get(). Now the behaviour is unexpected - the background thread works in one server, but fails in another.
`kill`ing all the uWSGI instances and restarting them using `sudo service uwsgi restart` solved the problem. It seems that `sudo service uwsgi stop` does not actually stop all the instances of `uwsgi`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, multithreading, flask, uwsgi" }
Does visual studio "watermark" builds with unique metadata Does visual studio "watermark" builds? If I used the same solution and build settings, on different computers (same vs build, same build settings), should I always get the same build? Do any of the microsoft compilers (VB6, sketchflow, etc) "watermark" builds? By "watermark", I mean attach metadata about the build environment. **Edit 1** With regards to the metadata, I'm wondering if unique metadata (outside of compiler version) is attached. For example, usernames, mac addresses, build environment(screen size, directories, cpu version, etc.) or hashed keys, etc. **Edit 2** There is a similar question at Visual Studio store hidden data in the compiled files?.
You could try it and see. A program like WinMerge will compare two files and show you the difference. If you don't have multiple build environments you could create a project and ask somebody online to compile it for you. My guess is there will be small differences if they're using a different version of Visual Studio, the CLR or the runtime libraries involved. You probably want to know whether something malicious is being done, such as the MAC address of the machine being used to compile the code is included somewhere. I highly doubt it. There are people that pay attention to this type of thing and it gets companies in hot water when they're found out.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 6, "tags": "visual studio, compilation, sketchflow" }
Squeak - SUnit Testing for Errors I have been suggested to use should:rise in my test case to test for errors that a method might raise. For some reason it does not work as expected, so I want to verify that I'm doing it right. Here is the code in the test case: self should: [aMyClass compareTo: 'This is a string'] raise: 'invalid input'. My compareTo/1 method looks like this: (aMyClass isKindOf: MyClass) ifFalse: [self error: 'invalid input'.]. The test runner output is that there is "1 errors". Thank you.
`#should:raise:` expects an Exception class as its second argument, similar to the first argument of `#on:do:` in exception handling: self should: [ aMyClass compareTo: 'This is a string' ] raise: Error
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "squeak" }
Print output live and save it to a variable at the same time I know that I can save the output to a variable and _then_ print it: VAR=$(command) echo "$VAR" But this has a number of drawbacks: * I won't see the progress of the command as it goes. * In particular, will see all `stdout` output after all `stderr` output, making it hard to match them. * Since this will result in no output for the duration of the command's work, in some environments (like Travis CI) this will terminate the job if the command works for long enough. **So, how can I save the output and also see it live on the console?** * Portable solutions are preferrable though a Linux/MacOS-only one will do in a pinch. * A solution should not have undesirable side effects in `errexit` mode
From the top of my head, one can `tee` the output to an additional file descriptor set to the original stdout: exec 3>&1 VAR=$(command | tee /dev/fd/3) One needs to have `set -o pipefail` set to detect `command`'s error in `errexit` mode.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "bash, platform agnostic" }
If $x^2\equiv1\pmod5$, what can be said about $x \pmod5$? (ENC 2000) If $x^2\equiv1\pmod5$, $x\in\mathbb{N},$ then: > A) $x\equiv1\pmod5$ > > B) $x\equiv2\pmod5$ > > C) $x\equiv4\pmod5$ > > D) $x\equiv1\pmod5$ or $x\equiv4\pmod5$ > > E) $x\equiv2\pmod5$ or $x\equiv4\pmod5$ I tried $$x^2\equiv1\pmod5\Longrightarrow5\mid1-x^2\Longrightarrow5\mid(1+x)(1-x)$$ Hence $$5\mid(1-x)\;\;\text{or}\;\;5\mid(1+x)$$ If $$5\mid1-x\Longrightarrow x\equiv1\pmod5$$ If $$5\mid 1+x\;\;?$$
$$x^2\equiv1\pmod5\Longrightarrow5\mid1-x^2\Longrightarrow5\mid(1+x)(1-x)$$$$\text{Soon}\;\;\;5\mid(1-x)\;\;\text{or}\;\;5\mid(1+x)$$$$\text{If}\;\;\;5\mid1-x\Longrightarrow x\equiv1\pmod5$$ $$\text{If}\;\;5\mid 1+x\Longrightarrow x\equiv -1\pmod5\Longrightarrow x\equiv4\pmod5$$$$$$Alternative (D)
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "elementary number theory, congruences" }
Number of partitions needed in spark In Spark summit 2013 one of the yahoo presentation had this formula mentioned: > partitions needed = total data size/(memory size/number of cores) Assuming a 64Gb memory host with 16 cores of CPU. The presentation mentioned that to process 3Tb of data, the number of partitions needed is 46080. I am having hard time getting to the same result. Please explain the calculation, how the number 46080 came?
Looking at the presentation (available here), the information available is: * 64Gb memory host * 16 core cpu * Compression rato 30:1, 2 times overhead Your formula should use the uncompressed data size when calculating, therefore, in this case you need to first uncompress it. Data size = 3Tb * 30 * 2 = 180Tb = 184320Gb Running it through the formula you get: 184320Gb/(64Gb/16) = 46080 partitions
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "apache spark, spark streaming, partitioning" }
Angular $scope.$digest vs $scope.$apply I just want to know how to use `$digest`. Inside a controller the following code works fine and it updates the DOM after 3 seconds: setTimeout(function(){ $scope.$apply(function(){ $scope.name = 'Alice'; }); }, 3000); However by using setTimeout(function(){ $scope.$digest(function(){ $scope.name = 'Alice'; }); }, 3000); nothing happens... I thought that they do the same thing. Am I wrong?
`$apply()` and `$digest()` have some similarities and differences. They are similar in that they both check what's changed and update the UI and fire any watchers. One difference between the two is how they are called. `$digest()` gets called without any arguments. `$apply()` takes a function that it will execute before doing any updates. The other difference is what they affect. `$digest()` will update the current scope and any child scopes. `$apply()` will update every scope. So most of the time `$digest()` will be what you want and more efficient. The final difference which explains why `$apply()` takes a function is how they handle exceptions in watchers. `$apply()` will pass the exceptions to `$exceptionHandler` (uses try-catch block internally), while `$digest()` will require you handle the exceptions yourself.
stackexchange-stackoverflow
{ "answer_score": 59, "question_score": 15, "tags": "angularjs" }
How to leave all rooms that the socket is connected to at one go in Socket.IO I have some code where a socket is made to join multiple rooms. At some point in the code, i want to leave all the rooms at one go, without disconnecting the socket. Is it possible to do this? If yes, then how can i do this? Thanks in advance.. I am using socket.IO
That's possible. You can leave rooms without disconnecting the socket. The socket disconnects only when you make a call to socket.disconnect(). To do this you'll have to maintain a list of rooms each client joins and leaves. To leave all rooms iterate through this list and make a call to socket.leave(roomname);
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 21, "tags": "node.js, websocket, socket.io" }
mysql returning more than one row I have a mysql query that needs to return the supplier ID from the supplier table by searching with the supplier name but it keeps returning multiple values. CREATE DEFINER=`root`@`%` PROCEDURE `sp_insert_sup_order`( supname varchar(50), dat date, total decimal(10,2) ) BEGIN insert into Supplier_Order ( Supplier_ID, SupDate, Total, Sup_Name ) values ( (select Supplier_ID from Supplier Where Supplier_ID.SupName = supname ), dat, total, supname ); Thats the query. Any help with this will be appreciated thanks
(select Supplier_ID from Supplier Where Supplier_ID.SupName = supname ) this should be like this: (select Supplier_ID from Supplier Where Supplier.SupName = supname ), And why do you store the supplier name and the id in the order ? that should not be done, image you have to change the name of the supplier, you will have to update all orders. Only the supplier id should be stored in the order table!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql" }
Non-destructively reversing an array in Javascript Say I have a function: function linesReverser(lines) { var localLines = lines.slice(); localLines[1].reverse(); return _.flatten(localLines); } And using it like so: var input = [["Hello"],["Hello", "World"]["Attention", "Please"]]; var output1 = linesReverser(input); //["Hello", "World", "Hello", "Attention", "Please"] var output2 = linesReverser(input); //["Hello", "Hello", "World", "Attention", "Please"] Notice how the object reference is being shared. I am new to JS, but I thought copying the values would alleviate this issue (`line.slice()`), but it doesn't seem to work. Is this because of the nested arrays? How can I non-destructively/immutably perform a reverse?
You're making a shallow copy of the `lines` array. To copy the nested arrays, you need to slice each one. var localLines = lines.map(function(arr) { return arr.slice(); }); The `.map` method will return a new Array of the return values, which are a slice of each nested Array. * * * FWIW, here's a shorter version that will work in modern browsers, though I'd probably stick with the first one. var localLines = lines.map(Array.apply.bind(Array, null));
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 17, "tags": "javascript" }
How to use File.separator in Windows Every time I use `File.separator` in Java code, I get the error because `'\'` is an escape character in Windows and Java doesn't recognise "quotes". I tried doing this: `String[] split = strData.toString().split(File.pathSeparator);`, but it crashes with following error message: Caused by: java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \ ^ File.pathSeparator = ; File.separator = \ strData.toString() = C:\Users\server\Desktop\minecraft\plugins\krneki
Since the argument of `String.split` is a regular expression, you need to quote the separator for it to be treated as a literal: String[] split = strData.toString().split(Pattern.quote(File.pathSeparator));
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, eclipse, plugins" }
Gnome shell restart is not working in Ubuntu 22.04 using ALT+F2 Two days ago I have install Ubuntu 22.04. I was trying to restart the gnome shell using ALT+Fn+F2. The command prompt opened but when I wrote 'r' and enter it is not restarting. The following message was coming as displayed on the image ![enter image description here]( What can I do now to resolve this problem?
Please enter this command: echo $XDG_SESSION_TYPE If the above command outputs, wayland, your system is using wayland. We have to disable wayland and enable xorg (x11). To do this, Please go to this file `sudo nano /etc/gdm3/custom.conf` Uncomment this line. `WaylandEnable=false` Reboot your system. Voila! You can now press ALT+F2 and then press r to restart your gnome shell. `echo $XDG_SESSION_TYPE` Now it should display x11. Enjoy!
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 0, "tags": "command line, gnome, reboot" }
How to note the time (possibly datetime) of PC Lock, Shutdown, Restart Event? I am trying to create a service which tracks the desktop events like LOCK, LOGOFF, SHUTDOWN etc, I need to write the time (and date) in a text file, regards.
You can handle the events on the SystemEvents class.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, .net" }
MVC: How do you remove focus from a datepicker? I have this Editor Template so that I have a datepicker set for date input. See <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %> <%:Html.TextBox("", (Model.HasValue ? Model.Value.ToLongDateString() : string.Empty), new { @class = "datePicker" })%> When I load a page with a date input field I automatically get the datepicker invoked. I would rather wait until the user clicks on the field or button. I am thinking that I want to use a JQuery Blur command associated with this Editor Template to stop this happening. But is that the right way, can it be done like that, or is there a better way?
If you don't want the calendar to appear until something is clicked, then you can try the showOn option, possibly like: $(document).ready(function () { $(".datepicker").datepicker({ showOn: "button", buttonImage: "/images/calendar.gif", buttonImageOnly: true, buttonText: 'Calendar' }); })
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, asp.net mvc" }
Regular exppresion tuning I use the following regular expression for validating one of my text areas: ^[a-zA-Z0-9][a-zA-Z0-9 ]+$ * It allows alpha numeric * It Avoids first space to be blank * It Allow blanks after first character How should i modify it to be able to allow the following characters: * coma (,) * semicolon (;) * colon (:) * euro symbol (€)
^[A-Za-z\d:;,\u20AC][A-Za-z\d :;,\u20AC]+$ * `\d` is any digit * `\u20AC` is the unicode value for euro (`€`)
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 3, "tags": "java, regex" }
Create multiple documents in Cloud Firestore at the same time Is it possible to create multiple documents against a collection using Cloud Firestore in the same transaction? I'm looking at the documentation on batched writes. Unless I'm mistaken (I'm new to Firebase, so could be the case) these examples are meant to demonstrate 'batched writes' but the examples only show a single field being updated.
Yes. Batched writes can work for both updating a single field on multiple documents, or creating a bunch of documents at once.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "firebase, google cloud firestore" }
Bluescreen on startup after Windows 7 Service Pack 1 installation I tried to install Windows 7 Service Pack 1 (64 bit) on my Dell notebook. Everything worked fine up to the first reboot after the installation. When booting, right before the Windows logo appears, a bluescreen with code `STOP 0x0000007B` occurs. Booting in safe mode is not possible, as it states a corrupt SP1 installation and wants to restore the system. Restoring resulted in several system problems (.NET framework for example). So I decided to do a fresh install of Windows 7 and then install the SP1 directly before installing anything on the new install. As you perhaps already guessed: it did not help a thing. Bluescreens on almost every boot attempt. I then found some articles which said, it may be a SATA driver problem and I switched from AHCI to IDE with no success. What could be the problem? Any guesses and advices? System: Dell Studio 1558 with Corsair SSD F240 drive and Windows 7 Home Premium 64bit
My first guess would be a corrupt device driver - maybe not something as drastic as a SATA driver, but it could be something you haven't thought of such as a webcam. (e.g. I remember Windows XP SP1 failing because of my USB CD-RW Drive) If you are not using the computer much at the moment because of this, as a test, I would recommend you reinstall Windows 7 and attempt to disable pretty much every piece of hardware you can from device manager before trying to load up SP1, then enable one by one and do a restart. If this doesn't help, please let me know and I will try and help further.
stackexchange-superuser
{ "answer_score": 3, "question_score": 4, "tags": "windows 7, service pack, bsod" }
Trello how to add attachments I am trying to add an attachment to a pre-created Trello card I know how to create the card, but so far I was not able to find how to add an attachment without providing the ID (because the card is not yet created) in case of need : < I am using this to create the card :
Ok I found the answer! Create the card -> get the ID of the card in the process -> add attachments !
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "api, trello, windev" }
how fancyvrb background color fill completely with fillcolor? I'd like the whole `Verbatim` (`fancyvrb`) block to have a background color. How do I do it? The `fancyvrb` package does define a fillcolor -- but that only colors the area around the margin -- not the background of the block itself.
You can use `tcolorbox` with `listings` package seemlessly. There by one can combine the advantages and features of both. Here is an example. \documentclass{article} \usepackage{tcolorbox,listings} \lstdefinestyle{mystyle}{ basicstyle=\ttfamily, numbers=left, numberstyle=\tiny, numbersep=5pt } \tcbuselibrary{listings,skins,breakable} \newtcblisting{BGVerbatim}{ arc=0mm, top=0mm, bottom=0mm, left=3mm, right=0mm, width=\textwidth, boxrule=0.5pt, colback=yellow, spartan, listing only, listing options={style=mystyle}, breakable } \begin{document} \begin{BGVerbatim} abc def { xyz \end{BGVerbatim} \end{document} !enter image description here
stackexchange-tex
{ "answer_score": 3, "question_score": 11, "tags": "verbatim, fancyvrb" }
How to use an XSL variable for a div's id value I thought the following mark up would work: <div id = '<xsl:value-of select="$TIMEDISPLAY"/>'> </div> I get a bunch of XML documents from an external system. One of the tags contains a timestamp using a certain datetime format. I need to transform the XML to HTML pages that will then be loaded into iframes. I have a javascript function to transform that datetime format to a readable display. So I though to use XSL to generate each HTML file with its `<script>` section that would locate the id of the div and inject the date display format. For that each HTML file needs to have that div with its own id.
Your question is not clear, except for this part: <div id = '<xsl:value-of select="$TIMEDISPLAY"/>'> </div> That's invalid syntax. If you want to output a `div` element with an `id` attribute containing the value held in the `$TIMEDISPLAY` variable, you must use one of these: <div> <xsl:attribute name="id"> <xsl:value-of select="$TIMEDISPLAY"/> </xsl:attribute> <!-- some content here --> </div> or: <div id="{$TIMEDISPLAY}"> <!-- some content here --> </div>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "xslt" }
Java get first 2 decimal digits of a double I have a huge double that i want to get the first 2 decimal digits as float from. Here is an example: double x = 0.36843871 float y = magicFunction(x) print(y) Output: `36` If you don't understand feel free to ask questions.
You could multiply by `100` and use `Math.floor(double)` like int y = (int) Math.floor(x * 100); System.out.println(y); I get (the requested) 36 Note that if you use `float`, then you would get `36.0`.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 6, "tags": "java, math, double" }
getting requestattributes in javascript I want to retrieve the request scope attribute in javascript as follows. How can I achieve this? function caseChanges(req) { var innervalue= "${dashboardTicketSummary}" alert("nand you are 1234"); alert(innervalue); }
Assumin the javascript is included inline on the jsp page -- you're on the right track, you just need to make sure the attribute is set (typically by your controller class) on the HttpServletRequest object, ie: @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) { DashboardTicketSummary dts = ...; // code to obtain ticket summary here req.setAttribute("dashboardTicketSummary", dts); // code to dispatch to your jsp page here } Of course there are many other more sophisticated way -- especially is you use popular MVC framework such as Spring
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jstl" }
Smoke sim is not visible in render view unless I go inside the domain Smoke sim is not visible in render view unless I go inside the domain? I added material for the domain too. I have done everything and checked YTube[![material[![\]\[1\]\[1\]](
First check that your scale is correct for the simulation you want. Simulations can be effected by domain size. Adjust your camera end clip. Select the camera then in the camera property tab. Under Lens there is a Clip Start, Clip end. Increase the Clip end larger. Also if you are using Evee, select render property then under volumetric there is a start and end field. Increase end. For the viewpoint in the top right corner select view, there is a clip start end field for the view, increase End.
stackexchange-blender
{ "answer_score": 0, "question_score": 0, "tags": "eevee render engine" }
Perms and Combs Question - Dealing with 'Mississippi' Firstly I apologise for my lack of formatting, I'm looking into fixing it. Q: How many distinct arrangements of the letters in 'Mississippi' are there if, (i) all four I's do not come together. I had this as a complementary event, so all arrangements subtract the ones that have the I's together. However, I calculated the I's together as 8!/4!. The answers say 8!/4!2! Where did the 2! come from? Once I find this I can subtract from all arrangements to find the solution.
How many distinct ways can we arrange letters of $MISSISSIPPI$ such that the $I$'s are all together. I think of it like this: the $I$'s are behaving as just one symbol, so count all the permutations on just 8 letters. $$ M, S, S, S, S, P, P, IIII $$ This is $8!$. The letter $S$ is repeated 4 times so divide by $4!$ not to overcount the re-arrangements of $S$. And the letter $P$ is repeated 2 times so divide by $2!$.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "combinatorics" }
Removing virtual COM Ports in c# I am creating a batch file to remove virtual com ports created before using com0com. at the time of creation, the port names where renamed for example: change CNCA2 portname=COM20 So when i want to remove i should use the original name like: remove 2 which corresponds to the original portname `CNCA2` So, what i m trying to do here is if the user chooses to remove Port COM20, how can get the original name which is `CNCxx` ? below is the sample of command i used:!enter image description here as u can see, when i write `remove COM150` there is no change, so i need to get the corresponding name which is `remove 2`. so from the c# application how can i get the corresponding name without manually using a `list` command? Thanks.
You could spawn a command prompt process that runs the list command and capture the output by redirecting stdout to a text file. Then read the results back from the file. From the example above, it should be relatively simple to parse the results and use them to create a Dictionary, so you can then easily look up the original name given the new name.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, serial port, virtual serial port, com0com" }
Incorrect export I have an issue with exporting my object from Blender. For my project I need a simple hollow cylinder with the UV map. So I create this cylinder, try to export it as .obj (by the way, same happens with other formats as well). It exports fine, without errors. But whenever I try to reopen this object from the harddrive I get a default scene with the cube and nothing else. At the same time, when I copy-paste the cylinder from one scene to another, it works absolutely fine. Also, when I open this exported .obj for example in some online obj viewers, it also works fine. In addition, saved .blend file opens properly with my cylinder. Same happens on two different machines, with windows and linux. I hadn't experienced this issue when I was doing the same about a year ago (not the same machine and version of blender as today). The cylinder is on the first layer, it has solidity modifier and the UV map, nothing else. Thanks in advance. Blend file .obj file
You cannot open .obj files in Blender, you need to import them instead: ![enter image description here]( Everything seems to be fine with your OBJ file.
stackexchange-blender
{ "answer_score": 1, "question_score": 0, "tags": "uv, export" }
Connecting to SSH using JTA in Java Can someone give me some example code? I've tried to look for the documentation but it looks confusing.. Or maybe I could use a different library to conenct to SSH in Java?
JTA only connects to SSH-1. If you are talking about SSH-2 you need something else, or you need my JTA SSH2Socket class ;-)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, ssh" }
What the plus operator does with an array? I found this code in one of Arduino libraries u8 buf[6]; Host2SCS(buf+0, buf+1, Position); Host2SCS(buf+2, buf+3, Time); Host2SCS(buf+4, buf+5, Speed); What the plus operator does with the array?
In the expression, `buf + 1`, where `buf` is an array; * `buf` is implicitly converted to a pointer equal to `&buf[0]` (the address of the first element of `buf`) This is a standard conversion known (unsurprisingly) as an "array to pointer conversion", or as "decaying to a pointer". * Adding an integral value to a pointer is normal pointer arithmetic, so the result of `buf+1` is equivalent to `&buf[1]`. In your code as shown, the pointers resulting from adding integral values to pointers are passed to the function. A more explicit version of your code would be u8 buf[6]; Host2SCS(&buf[0], &buf[1], Position); Host2SCS(&buf[2], &buf[3], Time); Host2SCS(&buf[4], &buf[5], Speed); Which form is "better" is a stylistic concern - technically they are equivalent.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": -2, "tags": "c++" }
what does it do dummy filler sql loader? hello I not understand dummy filler what it do? someone explains it to me? load data infile * "str '</contact>'" INSERT into table address_book TRUNCATE FIELDS( dummy1 filler char(2000) terminated by "<contact>", contact_name char(2000) enclosed by "<contact_name>" and "</contact_name>", address char(2000) enclosed by "<address>" and "</address>", dummy2 filler char(2000) terminated by "</start>" ) BEGINDATA example:dummy1 filler : It means to ignore everything until contact? thank you
Basically at a high-level `Sqlldr` first matches a field as defined in the control file with a field in the data file. Then if it also matches a column name it attempts to insert it into a table. Note that the `str` part of the infile line: infile * "str '</contact>'" tells sqlldr that a record ends with the string `"</contact>"`. So we can discern that `sqlldr` is to load some data from a contact record. In this case the data from the record will be read up until the string `"<contact>"` is found, and since it does not match a column name, and further it is defined as FILLER it will be ignored by sqlldr. It is only interested in the contact_name and address fields. So to answer your question, yes. :-)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "xml, oracle, sql loader" }
Python variable values changes automatically I am scrapping a website and everything looks fine except I can't save links in the website to variables and then to text file. import requests from bs4 import BeautifulSoup r = requests.get(" soup = BeautifulSoup(r.content) file = open("newtext.txt", "w") for link in soup.find_all("a"): g_data = link.get("href") print g_data **output is perfect till this script** but if I try to print g_data once more after the for loop is executed ,everything is gone.. print g_data Only one link is output nothing else.Am I doing anything wrong ? PS:I have tried this on different sites and it all outputs perfectly without any error.
In the code that you've posted, `g_data` is only pointing to one `href` at a time. If you want it to collect _all_ of the `href` attributes, you need to make it a `list`: `g_data = [] for link in soup.find_all("a"): g_data.append(link.get("href")) `
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, beautifulsoup" }
Other way to speed up Microsoft Access Form Load with Datasource I am tasked to fix a performance issue on a Microsoft Access Form. The page has a datasource using a Query. The Query joins several tables and does summation. The problem is when the page loads, the form uses a dummy value like QueryColumn = 'ImplossibleValue' to show an empty.list. The form contains search condition filter plus search button. When the search button is click the correct Filter is set. Because the query handles a lot of data, the page loads very slow at first but when the form opens the user is presented with blank query as design. Is there a way to Open the form and to make it have no data source?
You can change the recordsource to a query which returns Null values and need not reference any of your tables. SELECT Null AS field1, Null AS field2; After the user selects her search criteria, change the recordsource to the query which incorporates those criteria. Changing the recordsource automatically triggers a requery. If a user saves the form design after the recordsource has been changed to the search query, the form will use that again the next time it is opened. You can force the form to always open with the dummy row query as its recordsource by resetting that property during the form open event. Me.RecordSource = "SELECT Null AS field1, Null AS field2;"
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "performance, ms access, ms access 2003, form load" }
Looking for simple slideshow with previous and next navigation I just need to display the images in the very center of the page. The images will be different widths but should still be centered. I have custom arrow pointers and I want the other images to be hidden while the other fades out and a new one in. I've found jquery cycle and stuff but I couldn't center the slideshow to the center of the page for some strange reason. Any advice? What plugins can I alter (just replace images) to get what I want?
Checkout Anything Slider. That seems to be what you are looking for.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, slideshow" }
Better way to make a certain list with palindromic sublists Here is my code, which works, but seems a little too long, I think might be a more refined version. Range[Ceiling[#/2]] ~ Join ~ If[OddQ[#], Rest, Identity] @ Reverse @ Range[Ceiling[#/2]] & /@ Range[9] Range[Ceiling[#/2]] ~ Join ~ Range[Floor[#/2], 1, -1] & /@ Range[9] > > {{1}, {1, 1}, {1, 2, 1}, {1, 2, 2, 1}, {1, 2, 3, 2, 1}, {1, 2, 3, 3, 2, 1}, > {1, 2, 3, 4, 3, 2, 1}, {1, 2, 3, 4, 4, 3, 2, 1}, {1, 2, 3, 4, 5, 4, 3, 2, 1}} >
Table[Min[i, n + 1 - i], {n, 9}, {i, n}]
stackexchange-mathematica
{ "answer_score": 16, "question_score": 8, "tags": "list manipulation, palindrome" }
Fullcalendar can't access html5 data attribute in drop, only on Firefox I have fullcalendar setup to grab the html5 data attribute "event" from external events. For reasons unnecessary to get into, I am needing to access that data in the `drop` event handler in fullcalendar, but when I use `var foo = $(this).data(event);`, it seems to stop the script at that point, but only in Firefox, and no errors show in the console. Here is a jsfiddle showing it. For some reason, the calendar isn't working right, but that is not my problem. The problem shows itself when you drop the event anywhere on the calendar. In chrome, you will see a total of 3 alert boxes. In Firefox, only two.
You are using the wrong method here. .data() is for storing arbitrary data, > Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements. > […] > The .data() method allows us to attach data of any type to DOM elements This "data store" has little to do with HTML5 data attributes. To read those, you should simply use: `$(this).attr('data-event')`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, fullcalendar, fullcalendar scheduler" }
How can I increase the tasks.max for debezium sql connnector? I tried setting the configuration for debezium MySQL connector for the property 'tasks.max=50' But the connector in logs shows error as below: 'java.lang.IllegalArgumentException: Only a single connector task may be started' I am using MSK Connector with debezium custom plugin and Debezium version 1.8.
It's not possible. The database bin log must be read sequentially by only one task. Run multiple connectors for different tables if you want to distribute workload
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "apache kafka, apache kafka connect, debezium" }
What is an algorithm to enumerate lambda terms? What is an algorithm that will enumerate expressions for the lambda calculus by order of length? For example, `(λx.x), (λx.(x x)), (λx.(λy.x))` and so on?
As length I would choose the number of `T`-expansions ("depth") in this BNF of (untyped) lambda expressions: V ::= x | y T ::= V | λV.T | (T T) In python you can define a generator following the above generation rules for given variables and a given depth like this: def lBNF(vars, depth): if depth == 1: for var in vars: yield var elif depth > 1: for var in vars: for lTerm in lBNF(vars,depth-1): yield 'l%s.%s' % (var,lTerm) for i in range(1,depth): for lTerm1 in lBNF(vars,i): for lTerm2 in lBNF(vars,depth-i): yield '(%s %s)' % (lTerm1,lTerm2) Now you can enumerate the lambda terms for/up to a given depth: vars = ['x','y'] for i in range(1,5): for lTerm in lBNF(vars,i): print lTerm
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "algorithm, functional programming, lambda calculus" }
nested tertiary operator failed in javascript What's wrong with this code? { "disableDiscount_3": !isEmpty(data.discounts) ? (data.discounts.map(obj => obj.days === 3 && obj.is_enable === true ? true : false) : '', "disableDiscount_5": !isEmpty(data.discounts) ? (data.discounts.map(obj => obj.days === 5 && obj.is_enable === true ? true : false) : '', } Can't I nest tertiary operator within tertiary operator?
Remove `(` before `data.discounts.map()` and trailing comma following last value set at object. `obj.days === 3 && obj.is_enable === true ? true : false` is equivalent to `obj.days === 3 && obj.is_enable` { "disableDiscount_3": !isEmpty(data.discounts) ? data.discounts.map(obj => obj.days === 3 && obj.is_enable) : "", "disableDiscount_5": !isEmpty(data.discounts) ? data.discounts.map(obj => obj.days === 5 && obj.is_enable) : "" }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "reactjs, lodash" }
"assignment discards 'const' qualifier" error on non-const pointer In the following function: char *mystrtok(const char *input, const char *delim,char *rest) { int i; for (i = 0; input[i] != *delim && input[i] != '\0'; ++i) { continue; } char *result = malloc(sizeof(char) * (i + 2)); memcpy(result, input, i + 1); result[i + 1] = '\0'; if (input[i + 1] != '\0') rest = input + i + 2; else rest = NULL; return result; } I am getting `assignment discards 'const' qualifier from pointer target type` for the line `rest = input + i + 2`, however, as you can see, rest is not a constant pointer. What am I doing wrong here?
`input` is a pointer to a constant char, and you're assigning it to a pointer to a **non-constant** char. This here might be an interesting reading for you.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 6, "tags": "c, pointers, constants" }
Google Maps kml files If I use an embeded google map in my website, will the data contained in an kml displayed be publicly viewable? Will it be possible for the user to access just the data displayed (i.e., not the user interface) or would I have to provide that separately?
If you load your KML through the API, with GGeoXml(), (V2), or KmlLayer(), (V3), then your data needs to be in a public server because it is parsed by Google's servers and they need to be able to get to it. If you load it with a third party extension then you can keep it private. Third party extensions that can load and parse KML data are EGeoXml() by Mike Williams < and GeoXml() by Lance Dyas < but I believe that both of those are only available for the API V2 for now.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 1, "tags": "google maps, kml" }
Jump to ELF file I'm trying to write a simple bootloader. So, I switched into Protected Mode, jumped to `.code32` and trying to jump to ELF file, linked by `ld`. `ld` puts `.ELF` (`7F 45 4C ...`) into the begging of the file. Bochs interprets it as `jnle .+69` command, so it is not that result, which I was wainting. How can I put _entry_ point in the very beggining of the file? There is a `linker.ld` script: ENTRY (boot) SECTIONS { .boot ALIGN(0x1000) : { bootstrap.o(.text) } .text ALIGN(0x1000) : { *(.text) } .rodata ALIGN(0x1000) : { *(.rodata) } .data ALIGN(0x1000) : { *(.data) } .bss ALIGN(0x1000) : { *(.bss) } }
In order to execute an ELF binary, you must read the data from the file and interpret it accordingly. A description of this can be found in this PDF. The ELF is a header which contains information about the various sections of the file and how to set them up. After performing all the neccessary steps, you can jump to the entry point, which is also found in that header.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "gcc, assembly, x86, ld, elf" }
declarations in css empty selector not functioning for div class I have some styling for comments. However if the server sends null the div tag is going to require a different (no) styling. What's the best way to do this in CSS (preferably)? Such as is there a way to do _not_ empty in CSS ??? <div class="comments"><?php echo $comment; ?></div> .comments{ color: #CD3134; padding: 10px; float: right; border-style: dashed; border-color: #FF0000; width: 200px; } .comments:empty{ border-style: none; border-color: none; clear:both; }
I believe you can negate the `:empty` pseudo selector with the following: .comments:not(:empty) { } Another way would be to add a class to the div if there are no comments. <?php $commentclass = $comments == '' ? 'nocomments' : ''; <div class="comments <?php echo $commentclass; ?>"> <?php echo $comment; ?></div> .comments{ color: #CD3134; padding: 10px; float: right; border-style: dashed; border-color: #FF0000; width: 200px; } .comments.nocomments{ border-style: none; border-color: none; clear:both; }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "html, css" }
DataAnnotation for creating Custom auto increment (or auto decrement) identity What I want to do is to create a primary key that has auto decrement: Id BIGINT PRIMARY KEY IDENTITY(-1,-1) I searched for it and I could only find the following DataAnnotation for setting the Identity: [DatabaseGenerated(DatabaseGeneratedOption.Identity)] But this not fullfill my need of setting start and increment values. And if I want to increment by 1, and starting from 1 actually the following that I always use works for me: [Key] public long Id { get; set; }
Hi You can achieve this output by using the **database initialization or migration** There is no direct way to implement this in Code First. So, for using any of these options, you need to **customize the DB initialization:** This is done by implementing your own database initializer class and execute the desired SQL commands from the Seed methods (look for the implementation of public class MyInitializer in the linked article) **or to customize a migration:** you can execute any SQL Command in the Up() or Down() method of your migration Source: < Kindly look at the above url , the asker commented that ,By using above technique could be able to solve the problem. so hope it will be useful for you too. Thanks Karthik
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "c#, asp.net mvc, asp.net core, data annotations" }
SharePoint 2019 on premise - Delete list as template from apps I have several list I no longer need which were created with some PS script. I need to know how to delete them now to clean up the listings. Any help always appreciated. Script used SharePoint 2019 on premise - Save list as template
From Delete List Template in SharePoint using PowerShell Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue #Variables for Site URL and List template name $SiteURL=" $ListTemplateName ="Project Health.stp" #Get Site and List Template Folder objects $site = Get-SPSite $SiteURL $ListTemplateFolder = $site.RootWeb.GetFolder("_catalogs/lt") #Find the Specific List template and delete $ListTemplate = $ListTemplateFolder.Files | Where-Object { $_.Name -eq $ListTemplateName } if($ListTemplate) { $ListTemplate.Recycle() #To permanently delete, call: $ListTemplate.delete(); write-output "Deleted List template!" }
stackexchange-sharepoint
{ "answer_score": 2, "question_score": 0, "tags": "list, app, template" }
how to get current url from codeception & phantomjs test? I am creating product in estore with my test, and need to get url after submitting a form. Is it possible to get url _in the test scope_ after submitting button ? $I->click('#formSubmit'); $I->wait(5); // wait for redirect to new url $url = $I->someFunctionToGetCurrentUrl()` I am running this test from console, not from the web browser, so I don't have access to $_SERVER that is on the server's side. But if I have some methods like `$I->canSeeCurrentUrlEquals()` in codeception framework then i should somehow be able to access current url... how to do it?
The solution was to add a helper method to AcceptanceHelper in _support/AcceptanceHelper.php file: class AcceptanceHelper extends \Codeception\Module { /** * Get current url from WebDriver * @return mixed * @throws \Codeception\Exception\ModuleException */ public function getCurrentUrl() { return $this->getModule('WebDriver')->_getCurrentUri(); } } and then use it in test: $url = $I->getCurrentUrl();
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 13, "tags": "php, phantomjs, codeception" }
PHP: Convert str to number For an unknown reason, I cant seem to be able to convert a string to a number. It always return 0. Here is the code: $str = 'C$​2,313'; $str = str_replace(array("C$",","),"",$str); echo $str.PHP_EOL; echo intval($str); exit; The following always output: ​2313 0 How can I convert this string successfully to a number?
You have a non-printable character between `$` and `2`. Try using `preg_replace` to remove all non-digit characters instead: $str = preg_replace('/[^\d]/', '', $str); echo $str.PHP_EOL; echo intval($str); Output: 2313 2313
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "php" }
Illustrator: how to create a spirograph? I am trying to create a spirograph in Illustrator, as per attachment. How do I do this? Where do I start? ![spirograph](
Ok, so a spirograph is just a function and I have made a function drawing script called jooGraphFunction. With this tool at hand we can go and plot cos(2*t)*(10*cos(12*t)) -sin(2*t)*(26*sin(12*t)) sin(2*t)*(10* cos(12*t)) +cos(2*t)*(26*sin(12*t)) over range `0` to `PI` with stepping `PI/24` and you get. Where 12 is the number of lobes. ![enter image description here]( **Image 2** : Screenshot of jooGraphFunction GUI and a few alternate versions with different number of lobes. ![enter image description here]( **Image 2** : And drawing with same number of lobes as yours (36) made with same technique. You can also dissect the script for a starting point for your own learning.
stackexchange-graphicdesign
{ "answer_score": 15, "question_score": 12, "tags": "adobe illustrator, shapes" }
How to convert a png into pdf using LaTeX? I have a larger png image: width is 5400 pixels and height is 3850 pixels. I need to transform it into a pdf file in SPA3 size, which means 320mm x 450mm. Is there a way to do it with LaTeX? What I think I need, is to be able to specify the paper size explicitly and to tell LaTeX that there should not be anything around the image.
You can use the `standalone` class which will produce a pdf with no border. If you want a small border you can add `[border=<length>]` class option. ## Notes: * As LionelMANSUY mentioned in the comments it is usually preferable to use `keepaspectratio`, but if specific dimensions of _both_ height and width are required, using ``keepaspectratio` may conflict with those requirements.. ## Code: \documentclass{standalone} \usepackage{graphicx} \begin{document} \includegraphics[width=320mm,height=450mm]{../images/EiffelWide} \end{document}
stackexchange-tex
{ "answer_score": 25, "question_score": 17, "tags": "graphics, pdf, paper size, png" }
Calculus Riemann Sums - why do the partitions have to be of the same size? To set up Riemann sums for integration, my calculus text will say that the intervals of partition are all of the same size. Isn't it rather the case that they could be any size, as long as they are bounded by a largest partition which goes to zero as we take the limit? Why bother being so explicit about the equalities of each delta x? Similarly, does it matter that the point within each partition be determined in the same manner each time? As the limit goes to zero, as long as the x-value we choose is _somewhere_ within that segment of the domain...
You are right---they don't! Some texts/examples do so out of convenience, but certainly they should not say that $\Delta x_i$ must be constant across $i$. Similarly, $x_i$ does not have to be say, a left-endpoint, or right-endpoint, or midpoint of the $i$th subinterval. Any $x_i^*\in [x_i,x_{i+1}]$ will do, and you can vary your method of choosing $x_i^*$ across the various $i$. As you noted, so long as the norm of the partition tends to $0$, all is well.
stackexchange-math
{ "answer_score": 2, "question_score": 5, "tags": "calculus" }
Sequence of Measures that converge weakly to a non product measure Can someone provide an example of a sequence of probability measures $\\{u_n\\}$ which converges to a measure $u$ that is not a probability measure?
Much revised. If by weak convergence of the sequence of probability measures $\mu_n$ to the measure $\mu$ you mean that for each continuous bounded $f$ the limit $\lim_n\langle \mu_n,f\rangle = \langle \mu,f\rangle$ holds, you can indeed conclude that $\mu$ is a probability measure. Because the constant function $1$ is continuous and bounded. So the answer to your question is _no_. The condition of tightness brought up in your comment is meant to rule out convergences like the following. If the underlying space $X$ is not compact, such as $\mathbb R$, the sequence of point masses $\mu_n$ concentrating their mass at $\\{n\\}$ is so-called _vaguely convergent_ to the zero measure $\mu$: the convergence $\langle \mu_n,f\rangle\to\langle\mu,f\rangle$ is verified for all continuous $f$ of compact support. But these $\mu_n$ do not converge weakly to a measure.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "probability, weak convergence" }
Selenium - Chrome Web Driver - Html Only, No Images I am doing a lot of testing with the Chrome Web Driver within Selenium. The problem is that every time I run it, it has to re-download all the site images which takes time. It does not keep these images cached. So I would like to set which files to render and which not too. Obviously I want Javascript and CSS files to still download. But I particularily want to turn off images. Is this possible? If not, is there a way to enable caching? So the next time I run the progran it can get the images from the local cache.
Caching from one session to another is not possible as far as I know. However, it is possible to remove rendering the page if you run it headless. This will load the page, but not render it (make it visible, load images). You can use HTMLUnitDriver, which is the standard, but somewhat outdated, or you can use PhantomDriver, which has a more modern version of Javascript.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "selenium, selenium webdriver, selenium chromedriver" }
ubuntu 14.04 - unable to remove ppa:ondrej/php5 Can anyone please help me to remove broken package ondrej/php5-5.6 , I am trying to install Ruby on Rails , but when I run `\curl -L | bash -s stable --ruby` command , it throws - Requirements installation failed with status: 100. I searched it's solution and found "404 errors should be fixed for rvm to proceed" then I run `sudo add-apt-repository --remove ppa:ondrej/php5-5.6` to fix broken package but `getting Cannot access PPA ( to get PPA information, please check your internet connection.` I have checked internet connection and it is proper. ![enter image description here]( Thank much!!!
Well, @inian is perfectly right that installation questions don’t belong here. This particular question highlights a specific Ubuntu problem, so it belongs to Ask Ubuntu. However, if you reword it as _is there a non-standard way to remove a ppa, when`add-apt-repository` doesn’t work for some reason?_ it is possible to answer it here (I think) with a bash script: for ppa in $(fgrep -l ondrej /etc/apt/sources.list.d/*); do mv -i "$ppa" "${ppa}.disabled"; done; apt-get update (I put semicolons in so that you can run it as a one-liner without having to add them, if you like) Also, you mention Ubuntu-14.04 as a tag, but the ppa you are trying to remove is for Ubuntu-12.04 (precise). This might explain the errors.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, bash, ubuntu 14.04" }
Can we have external NoScript file? Can we have external NoScript file? If javascript is not avaialbe i want to hide **+** and **-** from According page. How to do this if i can't edit html `<head>` i only can add any external css and js file
The easy way is to add the +/- from Javascript, rather than sticking them directly in the HTML. That way they won't show up if scripts are disabled.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "javascript, css, xhtml" }
Open Windows Firewall to all connections from specific IP Address Is it possible to "whitelist" an IP Address in the Windows Firewall and allow all connections from that specific address?
Assuming the IP address you want to whitelist is `192.0.2.55`: netsh advfirewall firewall add rule name="Allow from 192.0.2.55" dir=in action=allow protocol=ANY remoteip=192.0.2.55
stackexchange-serverfault
{ "answer_score": 19, "question_score": 17, "tags": "windows server 2008 r2, firewall, ipv4, whitelist, rules" }
What is the better approach to find if a given set is a perfect subset of a set - If given subset is not sorted? What is the best approach to find if a given set(unsorted) is a perfect subset of a main set. I got to do some validation in my program where I got to compare the clients request set with the registered internal capability set. I thought of doing by having internal capability set sorted(will not change once registered) and do Binary search for each element in the client's request set. Is it the best I could get? I suspected that there might be better approach. Any idea? Regards, Microkernel
Assuming that your language of choice doesn't implement a set class with "contains in a set" method already like Java does with HashSet... **A good approach is to use hashmaps (aka hashes aka associative arrays)** If your superset is not too big, generate a hashmap mapping each object in the larger set to a true value. Then, loop over each element in a subset. Try to find the element in the generated hashmap. if you fail, your small set is NOT a peoper subset. If you finish the loop without failing, it is.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "algorithm, set, subset" }