INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Solve conditional equation with two variables, and one variable within a range
I have a simple equation s=n/r, knowing that s and n are between 0 and 1, and r>0, how do I find the values of n and s that make this equation true? I am interested in proceeding in two ways. (i) Set a value for r and then find all n,s pairs that solve the equation (ii) Find all values of r,s,n when the equation is true, always by keeping the constraints mentioned above
|
The triplet $(r,n,s)$ is a solution of the equation with the other conditions iff $$(r,n,s)\in (0,\infty)\times (0,\min(1,r))\times \\{n/r\\}$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "linear algebra"
}
|
Difference between DIR /S and Get-ChildItem -Recurse
Why do these commands return different results?
From cmd.exe:
>DIR /S C:\SVN
...
Total Files Listed:
87268 File(s) 23,080,818,153 bytes
15836 Dir(s) 216,886,992,896 bytes free
From powershell.exe:
>Get-ChildItem -File -Recurse -Force -Path 'C:\SVN' |
Measure-Object -Sum -Property Length |
Select-Object -Property Count,Sum
Count Sum
----- ---
87305 23081499113
|
When you issue a DIR command in a CMD prompt, the default behavior is to NOT to show System and Hidden files. To show everything, use the `/A` switch without any modifiers.
However, in PowerShell you have used the `-Force` parameter, which is defined as "Allows the cmdlet to get items that cannot otherwise not be accessed by the user, such as hidden or system files".
So this difference means that you have some hidden or system files in your folder.
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 1,
"tags": "powershell, cmd.exe"
}
|
How to GroupBy in Relationship?
I have post table
| ID | TITLE | SLUG | CONTENT | COMMENTS_COUNT |
and i have post_reactions table
| ID | USER_ID | TYPE | POST_ID |
I want to make a relationship that what reactions that post have
|
You can directly do it by model.
public function postrelation()
{
return $this->hasMany(PostRelation::class)->groupBy('type');
}
Or
Post::with(['postrelation' => function($q){
$q->groupBy('type');
}])->get();
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "laravel, laravel 5"
}
|
Count unique value of a range
I know there is a way to count unique values using sum(if(frequency())), but my problem doesn't solve with that. Here is a screenshot I'm providing an image link for you to understand it, see if anyone can help me.
<
Here I want to put a formula to count the unique number of cheques for the names please feel free to ask any other question, and please see if anyone can solve this.
|
I would suggest using a pivot table to summarize the table. You will then have the results that you want, automatically updated if you have new people in the future.
You would easily be able to filter and slice it based on period or user or amount.
**EDIT** I just noticed the duplicate cheque numbers.
Create a "helper" column that identifies if the cheque number is unique. In E2 put:
=IF(MATCH(D2,D:D,0)=ROW(D2),1,0)
You could then either use the pivot table, or in J2 use the following formula:
=SUMIF(B:B,RIGHT(F2,LEN(F2)-FIND("|",SUBSTITUTE(F2," ","|",
LEN(F2)-LEN(SUBSTITUTE(F2," ",""))))),E:E)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "excel, count, excel 2010, unique, countif"
}
|
Dishwasher Drain Into Sink instead of Under?
Is it ok to have the drain hose of the dishwasher just set into the kitchen sink and set in place, or do I have to merge it with the drain under the sink?
I am leaving this apartment soon (with my dishwasher), have a huge sink, and don't care aesthetically if there's a hose.
Thanks!
|
When the dishwasher goes to pump out then the pressure will move the hose possibly blowing it all over your kitchen.
Think of a hose left on full without anyone holding it.
You will need to clamp it down somehow and even then expect some splashing.
Good luck!
|
stackexchange-diy
|
{
"answer_score": 1,
"question_score": 1,
"tags": "pipe, sink, drainage, dishwasher"
}
|
Definite integral of $\int_{-2}^{2} \frac{5}{(x^2+4)^2}\,dx$ using the substitution of $x=2\tanθ$.
Can someone help with the integral $\int_{-2}^{2} \frac{5}{(x^2+4)^2}\,dx$?
I'm supposed to find the definite integral for this using the substitution $x=2\tanθ$.
This is what I've done so far: $$\longrightarrow \frac{dx}{dθ}=2\sec^2θ$$ $$\longrightarrow x=2 \rightarrow θ=\frac{\pi}{4}$$ $$\longrightarrow x=-2 \rightarrow θ=-\frac{\pi}{4}$$
$$\therefore \int_{-\frac{\pi}{4}}^{\frac{\pi}{4}} \frac{10\sec^2θ}{(4\tan^2θ+4)^2}\,dθ$$ Using; $$t=\tan^2θ+1,$$
$$=\int_{2}^{2} \frac{10}{32t^2\sqrt{t-1}}\,dt$$
After this, I don't know how to finish. Does anyone know how to finish?
*Note: The first substitution is the one the exercise is telling me to use, the other is one I used myself.
|
Instead of applying another substitution, just simplify the expression after your first substitunion. $$\int_{-\frac{\pi}{4}}^{\frac{\pi}{4}} \frac{10\sec^2{\theta}}{{\left(4\tan^2{\theta}+4\right)}^2} \; d \theta $$ $$=\int_{-\frac{\pi}{4}}^{\frac{\pi}{4}} \frac{10\sec^2{\theta}}{16{\left(\tan^2{\theta}+1\right)}^2} \; d \theta$$ $$=\frac{5}{8}\int_{-\frac{\pi}{4}}^{\frac{\pi}{4}} \frac{\sec^2{\theta}}{{\sec^4{\theta}}} \; d \theta$$ $$=\frac{5}{8}\int_{-\frac{\pi}{4}}^{\frac{\pi}{4}} \cos^2{\theta} \; d \theta$$ Using the angle reduction formula for $\cos^2{\theta}$: $$=\frac{5}{16} \left(\theta+\frac{1}{2}\sin{(2\theta)}\right) \bigg\rvert_{-\frac{\pi}{4}}^{\frac{\pi}{4}}$$ $$=\frac{5\left(\pi+2\right)}{32}$$
|
stackexchange-math
|
{
"answer_score": 7,
"question_score": 2,
"tags": "calculus, integration, definite integrals"
}
|
Format date with random number of split seconds
I need to parse a string to date. The problem is that the string has a random number of split seconds. To be more precise the number of digits vary between 0 and 7. To test this i wrote the following scenario:
public static void main(String[] args) throws ParseException {
// printDate("2016-02-10T12:48:08.632746Z");
printDate("2016-02-10T12:48:08.632Z");
}
private static void printDate(String datumAsString) throws ParseException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
System.out.println(LocalDateTime.parse(datumAsString, formatter));
}
The commented line does not work (it throws a ParseException). Do you have any idea how to solve this?
|
Assuming that the digits after the seconds represent a fraction of second and not a number of milliseconds, both strings can be parse "natively" by `ZonedDateTime` \- so you could write:
private static void printDate(String datumAsString) throws ParseException {
LocalDateTime ldt = ZonedDateTime.parse(datumAsString).toLocalDateTime();
System.out.println(ldt);
}
You may also want to stick with a `ZonedDateTime` instead of ignoring the time zone information.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "java, date, date conversion"
}
|
Construction of three tangent circles in a triangle
Given a triangle I want to construct three tangent circles inscribed in the triangle (every two sides of the triangle are tangent lines of one of the circles). For better understanding of the problem I tried to draw desired result (picture is only approximative, I do not know exact construction). Could you give me some hint, how exact construction can be done?
!enter image description here
|
It seemed to me that since there are many different centers in a triangle, one of them might be useful for your construction. Going through the links of various centers, I stumbled upon a name for the problem you describe: these three circles are known as **Malfatti circles**.
The Wikipedia article has some details on a construction by Steiner. ℝⁿ was kind enough to add a comment below, providing links to details about some of the steps in that construction, namely the construction of bitangents and incircles to quadrilaterals. The latter seems obvious in hindsight…
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 9,
"tags": "geometry"
}
|
How to calculate the frequency of each value in a column corresponding to each value in another column in R?
I have a dataset as follows:
col1 col2
A 1
A 2
A 2
B 1
B 1
C 1
C 1
C 2
I want the output as:
col1 col2 Frequency
A 1 1
A 2 2
B 1 2
C 1 2
C 2 1
I tried using the aggregate function and also the table function but I am unable to get desired result.
|
You can add a dummy column or use the `rownames` to aggregate on:
aggregate(rownames(mydf) ~ ., mydf, length)
# col1 col2 rownames(mydf)
# 1 A 1 1
# 2 B 1 2
# 3 C 1 2
# 4 A 2 2
# 5 C 2 1
`table` also works fine but will report combinations that may not be in your data as "0":
data.frame(table(mydf))
# col1 col2 Freq
# 1 A 1 1
# 2 B 1 2
# 3 C 1 2
# 4 A 2 2
# 5 B 2 0
# 6 C 2 1
* * *
Another nice approach is to use "data.table":
library(data.table)
as.data.table(mydf)[, .N, by = names(mydf)]
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "r, aggregate"
}
|
Regex (Has between 1 and 4 digits and as many characters as possible)
Hi trying to create a regex that ensures you have between 1 and 4 number of digits and also as many characters as possible
Here's what I have written so far `^([A-Za-z]+([0-9]){1,4}$)`
This doesnt allow me to have characters after the digits
|
You might repeat the whole part 1-4 times and match optional trailing chars a-z
^(?:[A-Za-z]*[0-9]){1,4}[A-Za-z]*$
The pattern matches
* `^` Start of string
* `(?:` Non capture group
* `[A-Za-z]*[0-9]){1,4}` Repeat matching 1-4 times optionalchars a-z and a single digit
* `[A-Za-z]*` Optionally repeat char A-Za-z
* `$` End of string
Regex demo
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "regex"
}
|
Python regular expression date
How can I use Python regular expressions on the following variables to extract the date?
a = 'abc_de_00_abcd_20130605.zip'
a = 'abc_de_20130605_00_abcd.zip'
I tried the following but it doesn't work.
re.match(r'[0-9]{8}',a)
|
`re.match` checks if the pattern can be found at the _start_ of the string (it's as if you had asked for `^[0-9]{8}` instead of `[0-9]{8}`).
You want `re.search` since your date string can be at different positions in your file name:
re.search(r'[0-9]{8}', a) # results in a match
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python"
}
|
Fedora command-line installation proposals
How to force Fedora command-line to give me proposals for installation of package when a missing command is typed?
Now when I type `git` the command-line tells me :
-bash: git: command not found
Before it gave me proposal (something like this):
Command not found. Install package 'git' to provide command 'git'? [N/y]
I made a clean installation of Fedora 24 and obviously this feature is missing. I tried to `dnf install command-not-found` but it couldn't find the package. What should I do to bring this feature back?
|
You have to install `PackageKit-command-not-found` package:
dnf install PackageKit-command-not-found
It is fine to check its config `/etc/PackageKit/CommandNotFound.conf` for some details (it's well documented), but default config should be enough.
|
stackexchange-unix
|
{
"answer_score": 2,
"question_score": 0,
"tags": "command line, fedora"
}
|
Once I have saved data to a variable, how can I then use that variable to copy to a new file?
I have a pipeline that is retrieving data to an array variable in a ForEach loop. I'd like to next use this array variable and save this array data into a new file (JSON or CSV is preferred).
How would I accomplish this?
|
In a ForEach loop and We can use the `item().<KeyName>` to access every item's value.
For exmaple :
If the file is formatted as the following: {"id":"ba3cbfdd-c668-4dab-88c0-ac2f3af183cf"} {"id":"e90f527b-efe0-43ee-b398-e9e6b7f2abb5"}, then we can use `item().id` to access the value.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "azure data factory"
}
|
Change Git Commit Message
I've made a terrible mistake. Looking back on my git commits, it seems that somehow I've managed to get some incorrect data on each of them.
My git commits, rather than looking like this `username<email@address>` look like `username<mypassword>`. How can I fix this for future commits? I will scrap the password but there it doesn't seem right to continue pushing with this message.
My git email is set to my email address, they're not set to the password. Anyone have any ideas?
|
I suspect you have a badly set git config. Try running:
git config user.name
git config user.email
Or find `.gitconfig` To see what's there. You can override with
git config --global user.email "notmypassword@address"
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "git, version control, github"
}
|
Maximum Period of Decimal Expansion
My question is similar to (but different from) the one here.
I came across this sentence on Wikipedia: "The decimal expansion of a rational number always either terminates after a finite number of digits or begins to repeat the same finite sequence of digits over and over."
Is it possible for an unbounded sequence of digits to repeat in the decimal expansion of an irrational number? Is the concept of an infinitely long sequence of digits compatible with the concept of that sequence repeating and, if so, what discipline in math addresses such a thing?
|
The only way for an infinite sequence of digits to repeat is if the second occurrence is a shift of the first occurrence, with offset $n$ say. But then the sequence repeats with period at most $n$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "irrational numbers, decimal expansion"
}
|
VisualStudio 2017 Console Project template missing
Yes, i've tried devenv/install, with no help. So, I don't have the Console C# Project option when creating the project, as shown here Currently i have installed windows basic pack - there's my 'about' screen.
I have just reinstalled Windows because i was getting the same exact problem on old system, and because VS2015 had interface bugs and crashed consequently, but it didn`t help(as well as reinstalling both VS 2015 and 2017 numerous times) Hope that you can guess whats wrong with my PC.
|
Visual Studio 2017 setup allows you to very fine-grainedly install various "components" separately, or groups of components delivered as "workloads".
You're missing the workload named ".NET desktop development", which contains among others these project templates. So re-run setup and install that workload.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 2,
"tags": "c#, console application, visual studio 2017"
}
|
How can web form content be preserved for the back button
When a web form is submitted and takes the user to another page, it is quite often the case that the user will click the Back button in order to submit the form again (the form is an advanced search in my case.)
How can I reliably preserve the form options selected by the user when they click Back (so they don't have to start from scratch with filling the form in again if they are only changing one of many form elements?)
Do I have to go down the route of storing the form options in session data (cookies or server-side) or is there a way to get the browser to handle this for me?
(Environment is PHP/JavaScript - and the site must work on IE6+ and Firefox2+)
|
I'd put it in the session.
It's going to be the most reliable and even if they don't go straight "back", it'll still have their search options there. Putting it in the cookie would also work, but wouldn't be recommended unless it's a very small form.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 5,
"tags": "php, javascript, session, forms, back button"
}
|
What does "the Latex template does not allow for keywords" mean?
I'm new to paper writing in LaTex and looking at the paper submission guideline of one IEEE conference, what does "the Latex template does not allow for keywords" mean in the description? .
Thanks in advance.
|
This is a common piece of boilerplate text on a number of IEEE conferences. It's a bit odd because as Alan Munn noted in his comment, the IEEE classes do include an `IEEEkeywords` environment for providing keywords. But in this instance, they're telling you not to use that environment. Presumably production might be using a different version of the IEEE classes or otherwise processing things in a way that invalidates that environment.
|
stackexchange-tex
|
{
"answer_score": 2,
"question_score": 2,
"tags": "templates, ieeetran"
}
|
Smalltalk (Pharo) methods
I am trying to learn Smalltalk (Pharo), but since not so many documentaion available I would like to ask for some help. I have There two classes, CarRental and Car, and a Test class, CarRentalTest. Now, supporse rental service has a fixednuber of cars.
| carRental |
carRental := CarRental new.
carRental
addCar: Car panda;
addCar: Car panda;
addCar: Car tesla.
self assert: carRental totalCars size = 3
However, my addCar method is red, how can I fix it?
|
Your method `addCar:` is red (note the colon at the end) because you haven't defined it. Let's write it down then:
The class `CarRental` must have an instance variable which will hold all its cars. Let's say we name it `cars`.
In the `initialize` method (instance side) we need to do the following
CarRental >> initialize
super initialize.
cars := OrderedCollection new.
Now, if we create a new instance of `CarRental` it will have an empty `OrderedCollection` in its `cars` ivar.
Now we can add the `addCar:` method like this
CarRental >> addCar: aCar
cars add: aCar
Finally, make sure that you have something like this
CarRental >> totalCars
^cars size
Review your code and keep trying!
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "methods, smalltalk"
}
|
composer and amazon php sdk
I am trying to follow the instructions here on downloading the amazon-php-sdk. In the last step it says To use it, just add the following line to your code’s bootstrap process.
require '/path/to/sdk/vendor/autoload.php';
What is my code's bootstrap process in this case?
|
Well, once you have added dependencies to composer.json and update/install the vendors, you are ready to use them.
Because, Symfony2 bootstrap uses composer autoload already.
> To ensure optimal flexibility and code reuse, Symfony2 applications leverage a variety of classes and 3rd party components. But loading all of these classes from separate files on each request can result in some overhead. To reduce this overhead, the Symfony2 Standard Edition provides a script to generate a so-called bootstrap file, consisting of multiple classes definitions in a single file. By including this file (which contains a copy of many of the core classes), Symfony no longer needs to include any of the source files containing those classes. This will reduce disc IO quite a bit.
FYI: use-bootstrap-files
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, symfony, amazon web services"
}
|
Find all rationals $q$ that make $q+\sqrt{2}$ a reduced quadratic irrational.
**Question.** Find, with proof, the possible values of a rational number $q$ for which $q+\sqrt{2}$ is a reduced quadratic irrational.
So, by definition a _quadratic irrational_ is one of the form $u+v\sqrt{d}$ where $u,v\in\Bbb Q, v\neq 0$ and $d$ being square-free. Then, it is said to be _reduced_ if it exceeds $1$ and has conjugate in the interval $(-1, 0)$.
For the question at hand; this corresponds to having $-1<q-\sqrt{2}<0$ and $q+\sqrt{2}>1$.
But I'm not quite sure how to proceed from here?
|
Since we have $-1 < q-\sqrt{2} < 0$ and $q+\sqrt{2} > 1$, we can simply move the square roots to get the inequalities $$-1 + \sqrt{2} < q < \sqrt{2} \text{ and } q > 1 - \sqrt{2}$$ Because $-1 + \sqrt{2} > 1 - \sqrt{2}$, our first inequality is all that is necessary. This means we can define a set $S$ of all rational numbers satisfying the inequality as $$S = \left\\{q \in \mathbb{Q} \mid q \in (-1+\sqrt{2}, \sqrt{2})\right\\}$$ This is the set of all rational numbers between $-1+\sqrt{2}$ and $\sqrt{2}$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "elementary number theory"
}
|
heeelp, i keep getting a read underline under foreach
do
{
//string test = questions[qCounter] = objReader.ReadLine();
string test = question.Split('?')[qCounter];
qCounter++;
foreach (string part in test)
{
Console.WriteLine(part);
Console.ReadLine();
}
} while (objReader.Peek() != -1 && qCounter < quest);
|
Using `foreach` on a `string` will produce a sequence of `char`, so declaring `part` as a `string` is not valid. Declare `part` as `char` or use `var`.
do
{
//string test = questions[qCounter] = objReader.ReadLine();
string test = question.Split('?')[qCounter];
qCounter++;
foreach (char part in test)
{
Console.WriteLine(part);
Console.ReadLine();
}
} while (objReader.Peek() != -1 && qCounter < quest);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -7,
"tags": "c#, foreach"
}
|
Trouble removing hidden parts of a string
I'm trying to use a scraped `string` with `BeautifulSoup` in a simple calculation. The interpreter gives a `base 10 error`, indicating that there's hidden characters in the string.
This turned out to be true, because the console outputs the raw string including hidden data as:
2.177
['\n\n2.177']
`2.177` is the number I'm trying to work with here. `['\n\n2.177']` is a hidden part of the string. Since it won't cast to int because of the hidden values however I can't make any calculations on it.
I've looked up a few ways to remove hidden characters from strings but so far stackoverflow only seems to have answers regarding removing special hidden characters.
Mine are sadly not special. Does anyone know how to remove this part of the string?
|
Based on the clarification, it looks like the contents of the string are `"\n\n2.177"`, i.e. with two leading newline characters. In this case, the issue is not so much with the newlines as the fact that `2.177` is indeed not a valid representation of an `int`. Both `int("\n\n2.177")` and `int("2.177")` give `ValueError: invalid literal for int() with base 10: '2.177'`.
To answer your direct question, you can strip leading and trailing whitespace with the `strip` method on strings, e.g. `vacancy_amount.strip()`.
Perhaps instead you intend to get a floating-point number out, in which case `float(vacancy_amount)` will give you `2.177`. If you want to further convert this to an integer, you can try `int(float(vacancy_amount))` to give `2`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, beautifulsoup"
}
|
Xcode Show only valid code signing identites in Build Settings
Does anybody know if its possible to get Xcode to only show valid code signing identities when you go to Build Settings > Code Signing > Code Signing Identity?
Currently it shows all code signing identities and greys out the non-valid ones, but the problem is I have hundreds and the list is getting bigger and bigger so it makes for a lot of scrolling to find the proper one.
|
There is no way to do that through settings in xcode. It has to be done manually by removing the invalid identities. Here is the link to apple doc's that clearly mentions that. Take a look at the section " keep your profile library clean".
Apple documentation link
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "iphone, ios, xcode"
}
|
How frequently to open and close IndexedDB database connection
So I have a chrome extension that I'm implementing with IndexedDB. The extension uses a content script which stores a record to the database every time the user casts a vote on a comment. I'm wondering how frequently I should open and close the connection.
|
I never close the connection and never see problem.
Just make sure, you listen to onversionchange of idb (not idb open request) to close the connection. It is the only time to close the connection. Otherwise browser will close for you.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "javascript, google chrome, google chrome extension, indexeddb"
}
|
In Fireworks CS5, How to hide all fills/strokes and show only paths (wire view)?
I have a complex vector graphic with overlapped shapes and I've been looking for a View mode that allows me to see only the paths. I guess it's called wire view or path view, but I can't find that option.
|
Alan is right that there is no such view but there is a way to do it. I usually just use the sub-selection tool (white arrow) and click and drag (a black box appears) around the vector object(s) to show up all the paths.
|
stackexchange-graphicdesign
|
{
"answer_score": 1,
"question_score": 1,
"tags": "adobe fireworks, visualization"
}
|
How to display html text in DevExpress.XtraEditors.RichTextEdit?
I am having `DevExpress.XtraEditors.RichTextEdit` control in which I want to display html text as readable text. But it show html text as it is with html tag.
How to display html text in `DevExpress.XtraEditors.RichTextEdit`?
|
I suggest you use the RepositoryItemRichTextEdit.DocumentFormat property in the following manner:
richTextEdit.Properties.DocumentFormat = DevExpress.XtraRichEdit.DocumentFormat.Html;
richTextEdit.Text = htmlString;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "c#, devexpress, richtextbox, xtraeditors"
}
|
Azure function REST API handling GET POST
I'm following some Azure Function tutorials on creating a REST API, this all seems straight forward. However I'm struggling to understand how I should deal with the different verbs.
Is the recommended practice to create a separate Azure Function for each verb? And then also separate functions for each variation of routing for each verb, so a e.g. a separete function for each of:
1. products/{productid} (GET)
2. products (GET, returns list)
3. products/me (GET returns a list of products belonging to the user making the request)
It seems to me I'm going to end up with a lot of Azure functions here. In the WebAPI approach I would have put all these in a single controller and the attribute routing would have taken care of the rest.
Is there another way to achieve this with Azure function?
|
You can use Azure Function Proxies to setup routing for HTTP verbs and parameters and then pass the call down to a single function. Creating a function per each verb/parameter combination seems to be an overkill.
Of course, if processing logic is completely different e.g. for GET vs POST, it makes sense to put those into separate functions. So, in the end it's your call, but you have tools for both scenarios.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "rest, azure, azure functions"
}
|
Git error 403 pushing
I am contributing in a repository. I can't push my code. Last week I pushed successfully my code, but today I can't. When I try to push I have this message:
> Failed with error: fatal: unable to access '< The requested URL returned error: 403
I tried to change the .git/config archive in many ways, but nothing worked. I have also tried to push using Android Studio, the desktop GitHub client, tortoise git and cmd but nothing works. I don't know what else to try.
|
I had a similar error. For my github account email verification was pending. Once Email verification was in place i was able to push my code to the repo.
There can be other reasons why you are not able to access the git repo but if you have recently created your github account please check if there are any warnings being shown when you login to your github account.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "android, git, github"
}
|
IP Datagram Fragmentation total length and payload calculations
I do not understand how to fragment a IP datagram.
Let's say the original datagram has a total size of 302 (20bytes header and 282 bytes payload). My datagram needs to be fragmented since it goes through a network of 128MTU. I have to fragment it and add 20 header for each new fragments.
* Fragment 1 124 total length (104 bytes payload)
* Fragment 2 124 total length (104 bytes payload)
* Fragment 3 94 total length (74 bytes payload)
If I addition that it gives me indeed the original payload. I do not understand how to find those numbers...
Why couldn't it be
* Fragment 1 114 total length (94 bytes payload)
* Fragment 2 114 total length (94 bytes payload)
* Fragment 3 114 total length (94 bytes payload)
(282/128(MTU)) > 2 so I need 3 fragments. 3Fragments = 60 bytes header added 60 +282 = 342 342/3 = 114 total lenght for each fragments.
My question is...
How and why should I get 124 124 and 94?
|
The IP fragmentation and reassembly is described by the RFCs. You must fragment on 64-bit boundaries. There are RFCs dealing with this, and other sites which will describe the fragmentation and reassembly process in depth; you can do a search to find them
Start with RFC 791, INTERNET PROTOCOL:
> To fragment a long internet datagram, an internet protocol module
> (for example, in a gateway), creates two new internet datagrams and
> copies the contents of the internet header fields from the long
> datagram into both new internet headers. The data of the long
> datagram is divided into two portions on a 8 octet (64 bit) boundary
> (the second portion might not be an integral multiple of 8 octets,
> but the first must be). Call the number of 8 octet blocks in the
> first portion NFB (for Number of Fragment Blocks). The first
> portion of the data is placed in the first new internet datagram,
> and the total length field is set to the length of the first
|
stackexchange-networkengineering
|
{
"answer_score": 3,
"question_score": 1,
"tags": "routing, ipv4, mtu, data, fragmentation"
}
|
Is iBooks Author suitable for producing poetry?
in terse terms:
poets
craft
lines.
eBook readers wrap
witlessly
Will Author for iBooks let us read
"Achilles' baneful wrath resound, O Goddess, that impos'd
Infinite sorrows on the Greeks, and many brave souls loos'd
From breasts heroic, sent them far to that invisible cave
That no light comforts, and their limbs to dogs and vultures gave;
To all which Jove's will gave effect, from whom first strife begun
Betwixt Atrides, king of men, and Thetis' godlike son."
instead of
"Achilles' baneful wrath resound, O Goddess, that impos'd Infinite sorrows on the Greeks, and many brave souls loos'd From breasts heroic, sent them far to that invisible cave That no light comforts, and their limbs to dogs and vultures gave; To all which Jove's will gave effect, from whom first strife begun Betwixt Atrides, king of men, and Thetis' godlike son."
|
Yes. Actually, what iBooks Author excels at is letting you format your text precisely, with elaborate styles and style sheets, and **_preventing_** the user from changing the font, point size, or theme. You get tremendously precise formatting and layout, and the user can't change anything at all in landscape orientation, while they can scale font size a bit in portrait orientation.
Here's the main drawback that I have just discovered myself: iBooks Author will only output books that can be read on an iPad with iOS 5 running the new iBooks 2.0. The book you create with iBooks Author cannot be read on an iPhone or iPod Touch or anything running iOS 4.2.1 or iBooks 1.0.
Secondly, the file size of a book that is all text (no illustrations) is **HUGE**. I'm talking 20 times as large as it should be. I've tested it. A book that was 900K in size created with other tools becomes 20MB in size when created in iBooks Author.
|
stackexchange-apple
|
{
"answer_score": 5,
"question_score": 4,
"tags": "ibooks author"
}
|
How to align list items
I am giving a trial on how to style lists and using child selectors. Currently I managed to style an unordered list as my jsfiddle displays:<
Html:
<ul>
<li>List item 1</li>
<li>List item 1</li>
<li>List item 1</li>
<li>List item 1</li>
</ul>
Css:
ul li:not(:first-child){
color: red;
}
ul li:first-child{
line-height: 50px;
list-style: none;
}
At the moment the bullet disappeared, but the list did not move to the far left replacing the position of the bullet. How can I align the first list item to the bullets of the other list items?
|
That's because your ul-items has an `padding-left: 40px;` If you set this to `0`, all items will go to left. If you want to change then the left-alignment of the li-items, you could use `margin-left` on them.
Just try and add this to your fiddle, and you will see that the first items move 20px to right, while all other items on the left.
ul {
padding-left: 0;
}
ul li:first-child {
list-style: none;
margin-left: 20px;
}
If you want to prevent the padding which accours then, just add `line-height: 100%;` to `ul li:first-child` like:
ul li:first-child {
line-height: 100%;
list-style: none;
margin-left: 20px;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "html, css"
}
|
Botframework | Direct Line | Attachment Upload - Need more info about limitations, security and storage
I have a few questions regarding Attachment upload on direct line (webchat)
When the user uploads a file on web chat
* What storage is being used ?
* Can we use our own storage ?
* What are the limitations ?
* Size limits
* Allowed File types
* etc.
* What about security ?
* I noticed that we can upload anything from an image to an executable
Thank you,
Marc
|
Attachments for Direct Line are stored encrypted on Microsoft servers. The size limit currently is 20MB and the contents will be available for 24 hours. You can use links to resources (actually how you would get around size limits) instead of through the Direct Line storage, but there is no way to override the Direct Line storage if you are sending actual attachments. I don't believe there are any restrictions on file types within Direct Line.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, botframework, direct line botframework, web chat"
}
|
How to get api_token for Sportmonks?
I want to take informations from soccerApi and I do not really understand from where should i take it. <
from sportmonks.soccer import SoccerApiV2
soccer = SoccerApiV2(api_token='My API token')
|
You need to register for an API Token and put it in place of `'My API token'`.
In order to get the API token, you would have to register for an account here: <
However, do not push your repo to github with the API token saved as other people can use your token. I would advise creating a separate file, for example `config.js` and then creating a variable with your token inside it. export the variable containing your token so that you can import it in inside the file that needs it.
Add `config.js` to .gitignore so that you do not push your API token to github.
However, if you are not publishing your work to github then you'd be fine just putting your token in place of `'My API token'`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python"
}
|
Escape ampersand in PL/SQL Developer
I'm trying a simple INSERT statement against an Oracle database. One of the values is a VARCHAR2 field and the insert statement contains an ampersand. How do I do this? I've tried the following methods:
1. Escape the & as \& with set escape on
2. set scan off (this causes an ORA-00922 missing or invalid option error)
3. set define off (this causes an ORA-00922 missing or invalid option error)
Any other ideas?
|
How I solved it is escaping the & with another &.
For example:
INSERT INTO Foo (Bar) VALUES ('Up && Away');
Works nicely. Thanks for all the help
|
stackexchange-stackoverflow
|
{
"answer_score": 27,
"question_score": 27,
"tags": "oracle, escaping, special characters, plsqldeveloper"
}
|
cron job can't source functions from bashrc
**crontab -e:**
30 22 * * 7 ~/bin/cron_run.sh
**~/bin/cron_run.sh** :
#!/bin/bash
source ~/.bashrc
#run_this_function is defined in a script sourced by bashrc
run_this_function
`run_this_function` is not found. What is happening here?
|
Try changing the `source ~/.bashrc` to `. ~/.bashrc`
That change will reload the contents of bashrc.
Then run_this_function should be available... if it is assigned properly as an alias.
Do you have the `run_this_function` declaration? - please post if you can.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "cron"
}
|
Retrieving the args given to StopIteration in a for loop
In python generators can return a final value that gets passed into the `StopIteration` exception:
def gen():
yield 3
yield 1
return 2
> g = gen()
> next(g)
3
> next(g)
1
> next(g)
Traceback (most recent call last): ...
next(g)
StopIteration: 2
> next(g)
Traceback (most recent call last): ...
next(g)
StopIteration
Is there any way to access the value passed into the StopIteration raised in a for loop? something like:
> result = 0
> for x in gen():
result += x
else catch StopIteration as y:
result /= y.args[0]
> result
2
|
No; `for` loops swallow `StopIteration` exceptions. If you care about the details of the `StopIteration` exception, you'd need to implement the iteration yourself.
That said, there's probably a better way to do whatever you're trying to do.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, for loop, python 3.x, generator"
}
|
Simultaneous Variants in Commerce
I'm trying to setup a product that has multiple variant groups that need to be simultaneously selectable and that have their own up-charges.
An example use-case: Say I have a digital product that I'm selling that has multiple license options as follows:
* Standard vs Pro
* Commercial vs Non-Commercial
* License levels based on Users
Each of these items would need to be individually selectable, with appropriate up-charges.
Any ideas on how to approach this?
Thanks!
|
As mentioned on Slack, the best approach to this currently is to set up all your variants and then use the plugin MultiAdd < to set up a form that can handle this.
Example code is in the ReadMe there.
It uses a single fast controller to update the cart all in one go, so there's no real speed penalty, and it raises events onMultiAddToCart etc. if needed too.
|
stackexchange-craftcms
|
{
"answer_score": 1,
"question_score": 1,
"tags": "plugin craftcommerce"
}
|
How to insert @ symbol between name and address
SQL Server Management Studio 2012
Table: Users Field: EmailAddress
ISSUE: I have an email address field that is missing the @ symbol before the address. GOAL: I need a method of inserting the @ symbol for over 100 email addresses.
EXPECTED: [email protected] ACTUAL: gdilbertwebsite.com
The website is the exact same amount of characters for all email addresses. The name will be different for each email address.
Thanks!
|
Something like this UPDATE Customers SET email = SUBSTRING(email,1,LEN(email)-11)+'@'+'website.com';
So this will remove the website.com from the string and add @website.com.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "insert, ssms, symbols"
}
|
Can i send Midi system exclusive from Chrome browser?
I do need to use chrome to trigger and send midi exclusive midi message and send it to a synthesizer hardware can chrome do it ? any framework ? any tutorial link that could get me on track , thanks.
|
When you are requesting access to the MIDI device, you need to set `sysex` in the options (see the examples).
You can the use `MIDIoutput``.send()` like with any other message.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "google chrome, web, system, midi"
}
|
Can't use paperclip+lightbox together
How to perform this piece of lightbox code using rails link_to method
<a href="img/bmw.jpg" data-lightbox="cars" data-title="My caption"><img src="img/bmw.jpg"></a>
the image_tag outputs images well
image_tag(@ad.photo.url(:medium))
so how to use this image_tag with link_to so lightbox works?
my application.js
//= require jquery
//= require jquery_ujs
//= require foundation
//= require lightbox
//= require turbolinks
//= require_tree .
$(function(){ $(document).foundation(); });
and my application.css is
*= require_tree .
*= require_self
*= require foundation_and_overrides
*= require lightbox
*= require mystyle
*/
|
`link_to image_tag(@ad.photo.url(:medium)), @ad.photo.url(:original), data: { lightbox: "cars", title="MyCaption" }`
Breakdown: The first image_tag is your thumbnail, and the second, is your original image which will be shown in the modal generated by lightbox.
Btw: That is Slim syntax.
Working code after debugging:
`link_to image_tag(@ad.photo.url(:medium)), image_path(@ad.photo.url(:medium)), data: { lightbox: "cars", title="MyCaption" }`
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "ruby on rails, ruby on rails 4, lightbox"
}
|
Nuxt routing multiple levels
Could somebody explain how to add a multi levels (children) path using nuxt. The structure of my project is:
root
events
_id.vue
cateogries
_id.vue
Basically my links are like this:
Will display a list of events
Will display the event information plus some categories
Will display the event category information
I've tried doing the structure of the folders and subfolders and is not working.
I've tried to use inside _id.vue from events `<nuxt-child/>` and is not working.
Does anyone has any ideas how to solve this?
Thank you in advanced.
|
First, not duplicate id param, use other name.
you can use such a structure:
pages
events
_eid
category
| |__ index.vue
_id.vue
_id.vue for <
<template>
<div>
{{ $route.params }} //{ "eid": "2", "id": "5" }
Hello from _id
</div>
</template>
For each level add index.vue or a dynamic "_".
Also be consistent in names (category or categories)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "vue.js, vuejs2, vue router, nuxt.js"
}
|
Add Remove RegEx Options in .NET
I want to take regex options as input from user and I am using check boxes to take input, which looks something like following:
[ ]IngoreCase
[ ]Multiline
[ ]Sigleline
[ ]RightToLeft
etc.
My questions is that how I can pass parameters (RegexOptions) according to option(s) selected by user.
Thanks,
Amit
|
When you use those options, you "OR" them together into a single value. There is no need to do that in 1 statement within the regex call, you could use something like:
var options = RegexOptions.None;
if (checkBoxIgnoreCase.Checked) options = options | RegexOptions.IgnoreCase;
if (checkBoxMultiLine.Checked) options = options | RegexOptions.MultiLine;
// etc.
and use that `options` value in your `Regex.Match`.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "c#, .net, regex"
}
|
Is there a way to make command text follow input?
Say i want to print a text prompt in java, and then get input from user from System.in. But another thread can write to System.out and "takes down" the input but the text prompt stays up, which is normal.
> Enter input here ->
> `<waiting for input ...>`
But if a thread writes something the following occurs:
> Enter input here ->
> ...
> ...
> ...
> Thread output here
> ...
> ...
> `<Waits for input here>`
Is there any trick to "bind" the input with the prompt text?
|
You could wrap your system.outs into a logging class, and when you want to print something add it to a queue in the new logging class.
When ever you ask for user input, have it activate a lock in the logging class so anything in the queue doesn't get printed until the user input is submitted, then have all the output in the queue get printed.
This will result in all the output text being paused while input is coming in. It won't interrupt your input, so the input will be bound around the cursor, but you also won't get any output. Up to you if that's worth it.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "java"
}
|
Android: How do you play a sound at a volume unaffected by any of the Android system volumes (ringtone, media, etc)?
I'd like to play a sound from a (ringtone) URI in my Android application. However, I would like to play this sound at an arbitrary volume and not have system volumes, such as Media and Ringtone volume, affect playback.
I've been paging through the API docs, but I'm at a loss. Is this possible with Android and if so, how would I do it?
|
I believe most apps aiming to do this choose a stream type, stash the current volume level (using `AudioManager.getStreamVolume`), set that volume to whatever they want it to be (using `setStreamVolume()` to some percentage of `getStreamMaxVolume`), and then restore the stashed volume level after playback completes. But think hard before you do this -- unless you're creating a "find my lost phone" app, there's rarely a reason to ignore the user's requested volume levels, and you run a high risk of irritating someone silencing their phone for a meeting.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "java, android"
}
|
Can I distort a bitmap image in Flash?
what I would like to do is to take a loaded GIF file as a Bitmap, and then distort it by stretching and shrinking parts of it, so it would look like it got squished up against the screen.
I'm pretty sure that there's no easy way in Flash to go beyond scaling and shearing, but I wonder if there might be some simple techniques to accomplish this kind of effect.
By the way, I've also thought of pre-deforming the images in GIMP and saving them there, but I can't find a simple way to do it without learning their scripting language.
Thanks for your help!
|
you should check out the `DisplacementMapFilter`. This tutorial should be a good start: <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "flash, actionscript 3, image"
}
|
Request.Headers to read GET URL
I have some code,
if (Request.Headers["User-Agent"] == "Mozilla/4.0 (compatible; MSIE 4.01; Windows NT; MS Search 6.0 Robot)")
{
this.Response.Redirect("/_windows/default.aspx?" + qp.ToString());
}
else if(Request.Headers["GET"].Contains("SignOut.aspx") ) {
this.Response.Redirect("/_layouts/signout.aspx");
}
else
{
this.Response.Redirect("/_trust/default.aspx?trust=ADFS%20DEV&" + qp.ToString());
}
The problem is that my `else if` does not work because `Request.Headers` can not read the "GET", per Microsoft I want to know when the GET url contains SignOut.aspx, is there a way for me to read that part of the header?
|
Looks like you're looking for HttpRequest.Url.aspx), which you can access from the Request object via Request.Url:
...
else if (Request.Url.AbsoluteUri.Contains("SignOut.aspx"))
{
//Whatever
}
...
Furthermore, you might want to look more into what the framework offers for handing requests - you're doing things the hard way and re-inventing the wheel. Consider using
Request.UserAgent
instead of
Request.Headers["User-Agent"]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, asp.net, http headers, response headers"
}
|
How to set title of a xhtml panel when it is closed
I use this code:
<p:panel header="Advanced User Data" toggleable="true" toggleOrientation="horizontal" collapsed="true">
some other stuff...
</p:panel>
Is there an attribute with which I can set the title when th panel is closed like this: example
|
There is no attribute like this AFAIK. You could bind the value of `collapsed` attribute to a managed bean and add an AJAX listener on `toggle` event:
<p:panel header="Advanced User Data" toggleable="true"
toggleOrientation="horizontal" collapsed="#{myBean.booleanVal}" style="display: inline-block;">
<p:ajax event="toggle" process="@this" update="pnlAlternativeTitle" />
</p:panel>
<h:panelGroup id="pnlAlternativeTitle">
<h:outputText rendered="#{myBean.booleanVal}"
value="Alternative title" />
</h:panelGroup>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "primefaces, xhtml"
}
|
Grep whole path
I would like to do this:
ls * | grep pattern
But I would like, instead of just showing the file with the pattern, the whole path of the files that match the patterns.
|
One way would be to use `find` to do your matching, though you might have to change the pattern to match the `find` syntax instead of `grep`s as I think they are not identical.
find "$PWD" -maxdepth 1 -regex 'pattern'
should show you the full path and the `-maxdepth` will prevent it from going into subdirectories. If you just want to use globs instead of regex you can use `-name 'glob'` syntax instead, and then use the `*` as you would with `ls`.
Here's an example output I see:
$ find "$PWD" -maxdepth 1 -regex '.*sh$'
/home/erenouf/tmp/scratch/t.sh
/home/erenouf/tmp/scratch/parseIW.sh
/home/erenouf/tmp/scratch/output.sh
since I was in `~/tmp/scratch` at the time and looked for files that ended in `sh`
In this case I can get the same output with
find "$PWD" -maxdepth 1 -name '*sh'
To have it look in subdirectories you can just remove teh `-maxdepth 1` part of each command
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 2,
"tags": "linux, path, grep"
}
|
Why did the Torah need to be given if the Avos knew and kept it?
It is a common theme in aggadic literature that
* The Avos were incredible tzadikim
* They more-or-less kept the entire Torah, including some derabannans
If the mitzvos were already known and kept, and the full text was not necessary for them to have perfection in their middos, why was Revelation necessary?
(I would guess that a potential answer is that their descendants forgot it, but that also seems strange. See also here.)
|
1) Revelation at Har Sinai was necessary to make it mandatory. As Mizrachi explains, the reason Avraham waited, until commanded, to perform circumcision is because there is greater merit in fulfilling a commanded mitzvah than an uncommanded one.
2) See the Rashba's explanation / understanding of this idea, that they were spiritually sophisticated and understood and intuited the fundamentals, applying it to their unique circumstances. This is not the same as keeping all the mitzvot.
3) But even according to the common explanation, Chazal said regarding Avraham "that his two kidneys expressed to him chochma like two teachers". This is intuition and knowledge of how to act, in according with Biblical and even Rabbinic law. Without a fixed text and methods by which to understand principles and derive law, one cannot expect subsequent generations to be similarly sophisticated and intuit how to act.
|
stackexchange-judaism
|
{
"answer_score": 10,
"question_score": 5,
"tags": "avot patriarch fathers, kabbalat hatorah, genesis bereishith"
}
|
Why does GoLand debug rebuild every time? how to solve it?
When press the Run button in GoLand, it will **recompile** the code even without any change for the code, why?
|
This is done by the Go compiler and it should be very fast if nothing changed, thanks to the compiler cache introduced in Go 1.10.
And the reason the recompilation step is required is simple: there is no simple way to tell if indeed nothing has changed or not in the build as external resources outside of the compilers reach could affect the results.
So, the IDE invokes the compiler first, then it starts the debugging process.
A better question would be: what are you trying to do and why is the recompilation a problem in this case?
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "go, goland"
}
|
Can I use a transistor to control my garage door?
I am using an Arduino to make a keypad to open my garage door when the correct pass code is entered. I plan on using a MOSFET to connect the two wires that currently go to the push button in the garage. The label on the garage door opener says it's 30 volts going to the push button. The MOSFET is rated at 60V 30A. Will this work, or do I need to use a relay?
|
Most door opners have terminals for a simple low-power switch to operate them. get out your multimeter and measure the voltage on these terminals and the current when they are connected.
it's probably a DC current of 200mA or less at 24V or less, (probably much less in both cases)
An ordinary transistor like 2n3904 would likely suffice, but your massive-overkill mosfet will do the job too, but you still need to connect it the right way round.
|
stackexchange-electronics
|
{
"answer_score": 1,
"question_score": 0,
"tags": "arduino"
}
|
Variation on exponential pdf expected value: integration
I know that $$ \int_{0}^{\infty}t \mu {\rm e}^{-\mu t}\,{\rm d}t = {1 \over \mu^{2}}\,\qquad \mu > 0 $$
I haven't been able to figure this out with substitution: $$ \int_{0}^{\infty}t^2 \mu {\rm e}^{-\mu t}\,{\rm d}t = ??,\qquad \mu > 0 $$
Was hoping someone could help?
Thanks
Mark
|
\begin{eqnarray} \int_0^\infty t\mu e^{-\mu t}\,dt&\stackrel{s=\mu t}{=}&\frac1\mu\int_0^\infty se^{-s}\,ds=-\frac1\mu se^{-s}\Big|_0^\infty+\frac1\mu\int_0^\infty e^{-s}\,ds=-\frac1\mu e^{-s}\Big|_0^\infty=\frac1\mu,\\\ \int_0^\infty t^2\mu e^{-\mu t}\,dt&\stackrel{s=\mu t}{=}&\frac{1}{\mu^2}\int_0^\infty s^2e^{-s}\,ds=-\frac{1}{\mu^2}s^2e^{-s}\Big|_0^\infty+\frac{2}{\mu}\cdot\frac1\mu\int_0^\infty se^{-s}\,ds=\frac{2}{\mu^2}. \end{eqnarray}
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "calculus, integration, definite integrals"
}
|
Complexity of weighted cycle in a hamiltonian graph
Assume a weighted graph G and a positive value k are given.
What is the complexity of finding a cycle with total weight k when G is Hamiltonian or Hamiltonian-connected?
pointing to papers and books is also welcome!
I wish it wouldn’t look as a homework!
|
If we are asking for a simple cycle the problem is NP-complete by a reduction from the Hamiltonian cycle problem.
We want to find a Hamiltonian cycle in a graph $G$. We assign weight 1 to all edges of $G$, and add to this graph all the other edges with weight $\infty$. We have thus created a clique, which is obviously Hamiltonian, and we ask whether there exist a cycle with weight $n$ in it.
|
stackexchange-cstheory
|
{
"answer_score": 4,
"question_score": 0,
"tags": "cc.complexity theory, graph theory"
}
|
Alone, locked inside an empty and dark room. From where to start eating oneself?
If I was locked in a empty room which is completely dark, from which body part should I start eating my body to maximize the survival time?
Also can we survive longer if we eat our flesh or keep drinking our own blood ?
|
You are already eating yourself without needing any conscious act. When your body needs energy, it starts to consume your fat reserves (that's what they're for), then your muscles and all the rest, in order of increasing importance for survival.
Biting off anything would not do you any good.
|
stackexchange-worldbuilding
|
{
"answer_score": 31,
"question_score": 0,
"tags": "survival"
}
|
When parent, child and grandchild processes share a page how does copy-on-write work?
If the child tries to write, it gets a new copy of the page (which is no longer write protected), does the grandchild point to that new page or the old one (which the parent holds)?
|
The process that writes to the page gets a new copy. If there are multiple processes that shared the old copy, they keep sharing the same page. It doesn't matter if the processes happen to be related.
|
stackexchange-unix
|
{
"answer_score": 2,
"question_score": 1,
"tags": "linux, fork"
}
|
PHP PDO fetch returns false
I keep thinking on that "error" but can't say why it returns false. I've already done a SELECT for this but that is in an other file..
$result = $db->dbh->prepare("SELECT thumbs FROM skill WHERE id=? LIMIT 1");
$result->bindParam(1, $id);
// $id == 4 here
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
// $row == false > why ?
$thumbs = $row['thumbs'];
When i'm trying to run this on PhpMyAdmin, it works well.
I execute this code on an AJAX call, and using the same config.php file for the $db conection.
Another question:
$sql_in = $db->dbh->prepare("INSERT INTO `voted_ip` (id, ip) VALUES (:id, :ip)");
// $id == 4
$sql_in->bindParam(":id", $id);
$sql_in->bindParam(":ip", $ip, PDO::PARAM_STR);
$sql_in->execute();
it inserts "0" and my ip. Why 0 ?
Please help
|
That is becasue of the $id which is a STRING is converted at 0 by MySQL.
$id = intval($id);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql, pdo"
}
|
Question is about a paper "A Block-sorting Lossless Data Compression Algorithm" by M. Burrows and D.J. Wheeler
In the paper A Block-sorting Lossless Data Compression Algorithm by M. Burrows and D.J. Wheeler Link. On page number 5. please describe this line
> If the original string $S$ is of the form $Z^p$ for some substring $Z$ and some $p > 1$, then the sequence $T^i[I]$ for $i = 0,...., N - 1$ will also be of the form $Z'^p$ for some subsequence $Z'$.
|
F.e. string "abc" becomes "bca" after BWT. This means that "abcabc" will transform into "bbccaa", i.e. "external repetition" of entire string will lead to "internal repetition" of each char in transformed string.
|
stackexchange-cs
|
{
"answer_score": 1,
"question_score": 1,
"tags": "algorithms, data compression, research"
}
|
Do "formal vous" and "plural vous" always have the same conjugation?
In English, the second person subject pronoun is always “you”, but French has two words: _tu_ and _vous_.
* _Tu_ is the familiar _you_ ,
* _Vous_ is the formal _you_ ,
* _Vous_ is also the plural _you_.
Now, in sense of conjugation, will the “formal vous“ and “plural vous” always behave the same?
|
Yes, the conjugation between the formal and plural _you_ ( _vous_ ) is always exactly the same.
Now, slightly related to your question, the plural of adjectives is different. For example:
* to a single woman:
> Vous êtes belle.
* to several women:
> Vous êtes belles.
|
stackexchange-french
|
{
"answer_score": 22,
"question_score": 15,
"tags": "conjugaison, vouvoiement"
}
|
Hostname issue in Mac OS X Lion
I've recently bought myself one of the new mid-2011 Mac Minis with OS X Lion, I'm completely new to Mac OS but I've used linux quite a bit before. The problem I'm having is that at the terminal my hostname is displayed as (blanked some of the numbers out) this is basically "unknown-(ethernet mac addr)"
unknown-28-00-00-00-00-8f:~ michael$
In linux I would have just edited /etc/hostname but there doesn't seem to be a file for it. I've tried changing the computer name in:
System Preferences => Sharing => Computer Name
with no luck.
This is purely a cosmetic issue for me but something must of broken in the setup for my hostname to look like that!
|
After a bit of playing about on the Terminal I've found a solution
sudo hostname <desired hostname>
this has permanently changed my hostname - I've tested it with a reboot and full shutdown and it seems to have done the trick! This doesn't explain why it gave me the odd hostname in the first place but that could just be because Lion is still new
|
stackexchange-superuser
|
{
"answer_score": 15,
"question_score": 16,
"tags": "osx lion, terminal.app, hostname"
}
|
How do I print colored text to the terminal in Rust?
How do I output colored text to the terminal using Rust? I've tried using the special escape characters that I found in this python answer, but they just print literally. Here is my code:
fn main() {
println!("\033[93mError\033[0m");
}
Any insight is welcome!
|
Rust doesn't have octal escape sequences. You have to use hexadecimal:
println!("\x1b[93mError\x1b[0m");
See also <
What happens, and the reason the compiler does not complain, is that `\0` _is_ a valid escape sequence in Rust - and represents the NULL character (ASCII code 0). It is just that Rust, unlike C (and Python), does not allow you to specify octal number after that. So it considers the `33` to be normal characters to print.
|
stackexchange-stackoverflow
|
{
"answer_score": 34,
"question_score": 33,
"tags": "rust, terminal, output"
}
|
Text Case in a list
I'm trying to get the text in upper case in a list. The column is a choice column where i typed all the options in upper case. In searching this site and others it says to create a calculated column and use =UPPER([Column Name]) so i did that. However, even that column still shows in lower case. My columns are UnitOfMeasure and Unit. The formula I'm using is =UPPER(UnitOfMeasure)
The other weird thing is when i first open my list both columns show in upper case, but then after a few seconds they show only the first letter capitalized.
|
You can do this with "Format this column" in modern list views!
` function - but no `toUpperCase()`. CSS to the rescue!
|
stackexchange-sharepoint
|
{
"answer_score": 1,
"question_score": 2,
"tags": "sharepoint online, list"
}
|
How to use setTimeout with every item in an array?
In the following:
ko.utils.arrayForEach(cards, function (card) {
setTimeout(function () {
observableData().saveCard(card);
}, 1000);
});
This is supposed to be waiting one second for every card in the array, but it just waits one second and then blasts through the array. How can I achieve the expected behavior?
|
You need to increment the timeouts
var idx = 1;
ko.utils.arrayForEach(cards, function (card) {
setTimeout(function () {
observableData().saveCard(card);
}, (idx++) * 1000);
});
Since the `arrayForEach` doesn't look like giving the index of the item, you need to maintain a separate index
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "javascript, jquery, knockout.js"
}
|
on tortoise svn I'm getting commit failed file already exists: filesystem
Well I'm getting those error messages.
I've updated my tortoise client and tried cleanup and updates and still can't commit.
Any ideas?
Richard
|
Delete and then check out the code again.
That's it
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 0,
"tags": "tortoisesvn, commit"
}
|
Count a character in a string split into 4's
I have an output string/array for example of 001100110011. Every fourth character depicts a single unit. I would like to calculate the number of 1's in each unit.
So for the above I would like a return of 2,2,2. If the string was 0100001100111 then It should return 1,2,3.
My current script only counts at every fourth loop so 0100001100111 would return 1,3,6.
$u = 16;//total of entries /4 is one unit
for($i=0;$i<=$u;$i++){
if(($i % 4) == 0){if($i==0){}else {$str .= substr_count($util_end, '1');}}
$util_end .= $_POST['userinput'.$b];
// util_end is the input from user on a checkbox select 0 for unselected and 1 for selected in sets of four ex 0110 (two selected)
}
|
$input = "010101010001001";
$result = array_map(function($i){
return substr_count($i, "1");
}, str_split($input, 4));
Demo: <
* <
* <
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "php, for loop"
}
|
Developing for mobile devices and desktop
I'm starting a new project. It will run on devices running Windows CE, Windows Mobile 6 and will also have a desktop version. The software will connect to some equipments through the serial port, using it's own protocol. Basically it will:
* connect to the equipment
* send and receive info
* read and write binary files
These tasks will be shared between desktop and mobile devices. I've been searching the information I need, but I still have some doubts:
1. If I create the solution targeting Windows CE devices, will it work with Windows Mobile 6 too?
2. Creating a class library targeting Windows CE will give me any trouble on using it in the desktop version? (when I add a reference to that class library, my VS says that I could experience some unexpected results)
3. Is it possible to install .NET CF 3.5 on devices running Windows CE 4.2?
Thanks!
|
1. Maybe. Windows Mobile is Built on Windows CE, but it doesn't contain everything the OS has to offer. If you use a CE feature that WinMo does not have then no, it will not work. The same can be said about creating an application for WinMo - it may or may not run under Windows CE.
2. CF assemblies are retargetable, meaning that the desktop framework can at least attempt to run them. They will run fine until you hit an issue where you cann something CE specific. For example, P/Invoking coredll, using a SIP control, using the MessageWindow class, etc. If you use classes common to both frameworks, it will be fine.
3. Yes. You cannot debug directly on the device (well, you're not supposed to be able to but often you can get it to work by manually running corecon) but it will run just fine (assuming you have all of the OS components necessary to load the CF runtimes anyway).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": ".net, compact framework, windows ce, shared libraries, code organization"
}
|
First hitting time of leftcontinuous process
Suppose that we are working with a Filtration which is right continuous. I know then, that the first hitting time of a right continuous process into an open set is a stopping time. Is the same true, if we replace right continuity with left continuity?
hulik
|
For a right continuous filtration $(\mathcal F_t)_{t\geq 0}$, a left continuous process and $O$ an open set, the map $$T_O\colon\omega\mapsto \inf\\{t>0, X_t(\omega)\in O\\}$$ is a stopping time.
Since the filtration is right continuous, it's enough to show that $\\{T_O<t\\}\in\mathcal F_t\\}$ for all $t>0$. We have $$\\{T_O<t\\}=\bigcup_{q<t,q\in\Bbb Q}\\{X_q\in O\\}.$$ Indeed, let $\omega$ such that $T_O(\omega)<t$. We can find $t'<t$ such that $X_{t'}(\omega)\in O$. By left continuity and using openness of $O$, we can find a rational $q<t'$ such that $X_q(\omega)\in O$.
Conversely, if $X_q(\omega)\in O$ for some rational $q<t$, we have $T_O(\omega)\leq q<t$.
Since $\\{X_q\in O\\}\in\mathcal F_q\subset\mathcal F_t$ for each $q<t$, we are done.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "measure theory, probability theory, stochastic processes"
}
|
How to map a dictionary in Swift5?
I need some help :
if let dogFriends = dictionary[Key.dogFriends] as? [String: Int] {
var newDogFriends = [String: FriendType]()
dogFriends.forEach {
newDogFriends[$0.key] = FriendType(rawValue: $0.value)
}
}
And I try to change a part of my code:
dogFriends.forEach {
newDogFriends[$0.key] = FriendType(rawValue: $0.value)
}
Into this code(because swiftlint shows me a warning, I try to shorten my code):
self.dogFriends = dogFriends.map{ ($0.key,: FriendType(rawValue: $0.value)) }
Throws the below error:
> Cannot assign value of type '[String]' to type 'Property<[String : FriendType]>'
let dogFriend: [String: Int]
FriendType = enum FriendType : Int
Any help please?
|
You can use map. In this line
self.dogFriends = dogFriends.map{ ($0.key,: FriendType(rawValue: $0.value)) }
Change
self.dogFriends =
To
let newDogFriends =
You cannot overwrite dogFriends with a different type.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "swift, dictionary"
}
|
Python jumping a while Loop
I'm, trying to avoid this while loop what is wrong
while True:
start = input("Ok, are you ready now?\n")
if (start != "yes" and start != "no"):
print ("Please enter Yes or No")
else:
break
elif start =="no":
continue
|
Your indentation is totally wrong. Your code is not valid. By the way, there's the correct indented code:
while True:
start = input("Ok, are you ready now?")
if start == "yes":
break
elif start == "no":
continue
else:
print ("Please enter yes or no.\n")
Note that it works in **Python3**
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, loops, if statement"
}
|
Application doesn't oriented
My application doesn't oriented even if I use
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Override to allow orientations other than the default portrait orientation.
return YES;
}
the only thing I do is to hide the lower tab bar using
SearchScreen.hidesBottomBarWhenPushed = YES ;
Any idea how to fix that
|
Some ideas:
* Are the "Supported Device Orientations" set properply?
* Maybe a parent ViewController is not allowing interface orientation?
* If testing on a device: Is it "orientation locked"?
**Setting 'Supported Device Orientations' inside Info.plist:**
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "iphone, ios, ipad"
}
|
Using 年代 for decades when using 昭和XX年 for individual years
If you are describing a year as
>
rather than
>
Can you similarly use for decades, such as
>
or does that convention only apply when using the Christian calendar
|
Yes, you can safely use like that. 40 refers to 1965–1974.
Note that does not always refer to _decades_. For example, 1600 typically refers to 1600–1699.
|
stackexchange-japanese
|
{
"answer_score": 2,
"question_score": 1,
"tags": "time"
}
|
Instantiate a class from a string in ActionScript 3
I've got a string which, in run-time, contains the name of a class that I want to instantiate. How would I do that?
I read suggestions to use `flash.utils.getDefinitionByName()`:
var myClass:Class = getDefinitionByName("package.className") as Class;
var myInstance:* = new myClass();
However, that gives me the following error:
> [Fault] exception, information=ReferenceError: Error #1065: Variable className is not defined.
|
The easiest method I've come up with is to simply write the classnames out, separated by semicolons, anywhere in your project.
e.g. I create an Assets.as file with this in it:
package {
public class Assets {
// To avoid errors from the compiler when calling getDefinitionByName
// just list all of the classes that are not otherwise referenced in code:
Balloon;
Cloud;
FlyingHorse;
FlyingPig;
UFO;
Zeppelin;
}
}
Full code example/tutorial on this is here: <
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "actionscript 3, class, dynamic class"
}
|
PBR transparent fence texture node set-up not working
Thanks in advance for your help!
I'm working with a transparent wire fence PBR texture, and I cannot get the space between the wires to be transparent. (I've also tried on a simple plane mesh - same results)
I've tried with two different materials:
Picture 1: <
Picture 2: <
What am I missing here?
, on "blend mode", it is set to "opaque". As you are using Eevee, click there and just choose another blend mode, like "alpha clip" or "alpha blend".
$ and a threshold value $W$, I want to select $k$ tuples such that: $$ maximize\sum_{i=1}^k c_i \\\ \sum_{i=1}^k w_i \ge W $$ It seems pretty simple at first. Without the weighting constraint, you can use any selection algorithm to select the $k$ elements with largest $c$. But with the weighting, it seems there's no special structure to exploit. Seems like you'd have to search all subsets?
|
Use dynamic programming.
Let the $(c,w)$ pairs be $(c_1,w_1),\dots,(c_n,w_n)$. Define $A[k^*,n^*,W^*]$ to be the largest possible sum of $c$-values obtainable by selecting $k^*$ pairs from $(c_1,w_1),\dots,(c_{n^*},w_{n^*})$ such that the sum of their $w$-values is at least $W^*$. Then you can write down a recursive definition of $A[k^*,n^*,W^*]$:
$$A[k^*,n^*,W^*] = \max(A[k^*,n^*-1,W^*], A[k^*-1,n^*-1,W^*-w_{n^*}]+c_{n^*}).$$
Now fill in this table using dynamic programming. The running time will be $O(nkW)$, where $n$ is the number of $(c,w)$-pairs in the input.
This is basically an adaptation of the dynamic programming algorithm for the knapsack problem: <
|
stackexchange-cs
|
{
"answer_score": 1,
"question_score": 1,
"tags": "optimization, selection problem"
}
|
Type or namespace name could not be found...
I have a solution with many projects. All are reusable class libraries except one that is a console application I am using to build test cases. I can successfully reference some projects, but not others. I can add a reference to the projects, but when I reference them with a using statement, some of the project references fail at compile time with a "type or namespace name 'project name' could not be found.
The strange thing about this is that I am successfully referencing all of these projects in another separate application, but within this solution, I can reference some successfully and not others?
|
By default Visual Studio 2010 creates Console apps against the .Net Framework Client Profile. Often times this is incompatible with existing libraries built against the full framework. Go to you console app, go to properties, and change the target framework to .Net Framework 4.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "c#, .net"
}
|
what does link href="#" do?
I stumbled upon the following snippet in a source code of a web site.
<link href="#" id="colour-scheme" rel="stylesheet">
What does this do?
|
Probably some stylesheet that is to be loaded later on.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 21,
"tags": "html, css"
}
|
If $\;\lim\limits_{x\rightarrow 10}g(x)=a\;$ and if$\;\lim\limits_{x \rightarrow10}\dfrac{f(x)}{g(x)}=b$, find $\lim\limits_{x\rightarrow10}f(x).$
If $\;\lim\limits_{x \rightarrow10}g(x)=a\;$ and if $\;\lim\limits_{x\rightarrow10}\dfrac{f(x)}{g(x)}=b\;,\;$ where $\;a,b\neq 0\;,\;$ what's $\;\lim\limits_{x\rightarrow10}f(x)\;?$
The answer is insufficient information to determine. But I thought there was a "limit multiplication rule" I could use to determine it's $ab$? Can someone give an example when this doesn't hold?
[EDIT] based on below discussion, I guess the question boils down to, can we conclude $\lim\limits_{x\rightarrow10}f(x)$ exists based on above conditions?
I am also curious if the answer changes if $b=0$ or $a=0$?
|
$f(x)= \frac{f(x)}{g(x)} \cdot g(x)$ for $x $ in a neighborhood of $10$, since $a \ne 0.$
Hence
$$f(x)= \frac{f(x)}{g(x)} \cdot g(x) \to b \cdot a$$
as $x \to 10.$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "real analysis, calculus, limits, limits without lhopital"
}
|
firebase HTTP function termination
Is it OK practice to put additional logic into a Firebase HTTPS function, after the response was sent?
I have functions where this is happening:
1. write to the Firebase DB
2. once the write is done, I send back the response (this is where `res.status(200 / 500).send()` is called)
3. I look up some FCM tokens in the DB and send a push message (it does not matter from a requester perspective if this is successful or not)
I understand that another pattern could be that I move step 3 to another DB trigger function to do the messaging. That would introduce some delay as I'd need to wait for that DB trigger function to fire.
My question is: is it safe to put additional logic to a HTTPS function after the response is sent, or Firebase may start to cleanup / terminate my function already?
|
_firebaser here_
While your sending of FCM messages (in step 3) may frequently work, it is not reliable. There is no guarantee that the HTTP-triggered function will continue running after a response has been sent.
Precisely for this reason the Firebase documentation says:
> HTTP functions are synchronous, so you should send a response as quickly as possible and defer work using Cloud Firestore.
So in your case, the documentation explicitly says to put the sending of the notification into a database-triggered function.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "firebase, google cloud functions"
}
|
Teach dog to stay in one spot while defecating
Backstory: I have a 6 month old Australian Labradoodle, that has been housetrained since we brought her home at 8 weeks. She is very trainable.
The issue we are experiencing is that she rotates/moves around as she is defecating, so she sometimes steps in her own feces. Using commands like stay/stop just seem to confuse her in those situations.
I'd like to find a way to get her to stay in one spot to prevent the potential for accidentally stepping in her own poop. Any suggestions?
|
I have seen several dogs that move while defecating, but never one that turns in tight circles. This seems to be some kind of natural behavior, so instead of trying to teach her to stay in one spot, teach her to move forward rather then in circles.
Keep her on leash, stay in front of her with no slack in the leash, not pulling, but just making forward the only choice. Praise her staying put as well as for moving forward. I would not use negative commands for turning, as you point out that only confuses her.
Of note travailing deification in your pet requires a higher pooper scooper effort on your part. She is likely to step in a previous pile, if the area has not been cleaned for a couple of days.
|
stackexchange-pets
|
{
"answer_score": 7,
"question_score": 12,
"tags": "training, toilet training, dogs"
}
|
EventListener like AbstractMongoEventListener in Spring Data JPA?
We are migrating from a Spring Data MongoDB repository to a Spring Data JPA repository. We were using the AbstractMongoEventListener to capture `onBeforeConvert` and `onAfterLoad` events to enhance the data objects before returning them from our Service layer.
I cannot find similar EventListeners in Spring Data JPA. Are there hooks in Spring Data JPA that I can use to do the same thing? It would be great if I can avoid modifying our service layer to make this change from MongoDB to JPA.
Thanks!
|
The `@PrePersist` annotation is exactly what I was looking for.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "spring data, spring data jpa, spring data mongodb"
}
|
Using regex to extract substring
I am trying to make a parser for PGN-file moves. I would like to extract a substring from the total text-input starting from move 1.
This is an example piece of a PGN file:
PGN-file
I tried to extract the moves in a `substring` using `indexOf()` by a regex.
This is my attempt:
function extractMoves(){
const pgn = '[Date "2013.11.12"] 1.Nf3 d5 2.g3 g6'; // Sample PGN.
const firstMove = /1\.([a-h]|[NBRQK])/; // First move regex.
const moves = pgn.substring(pgn.indexOf(firstMove));
return moves;
}
console.log(extractMoves());
This is the expected output:
1.Nf3 d5 2.g3 g6
|
`indexOf` doesn't work with regex. Use `search` instead.
It gives the expected output now:
function extractMoves(){
const pgn = '[Date "2013.11.12"] 1.Nf3 d5 2.g3 g6'
const firstMove = /1\.([a-h]|[NBRQK])/;
const moves = pgn.substring(pgn.search(firstMove));
return moves;
}
console.log(extractMoves());
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, regex, substring"
}
|
After git reset, trying to merge again, but not saying conflict
I messed up the codes after I merged branch `feature-search` to `master`. So I am trying to redo the merge and fix the conflict again. So I `git reset hard -- eae8ee4`. `eae8ee4` is the commit before the merge.
Then I try to merge the branch to master again. It didn't show any conflict error. It seems the master still contains the merged codes. So how do I do a merge and fix conflict again?
|
Use `git reflog`, find the `HEAD@{...}` prior to that dreadful `merge` and do `git reset --hard HEAD@{id}` (where `id` is a number). This will revert your code to the state it was prior to that `merge`
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "git, merge"
}
|
What is the alternate/workaround of designer workflow in SharePoint Add-in
There was a requirement to create workflow in SharePoint Hosted Add-in. Earlier the same flow was implemented on O365 but now the requirement is to achieve the same thing on Add-in.
Is there any way to create workflow in SharePoint Add-in?
|
First of all, let me tell you that it is impossible to create Designer Workflows for SharePoint Add In.
Now, you can use Visual Studio for creating workflows. Also, you can try creating Site Workflows. But this will only work on O365 but not on On Premises as the On Prem Workflow Manager will not be able to relate the workflows of the Add in.
|
stackexchange-sharepoint
|
{
"answer_score": 6,
"question_score": 4,
"tags": "sharepoint addin"
}
|
strange inputrc behavior: characters succeeding '1' being pushed to the end of the line
I type in IP addresses frequently for my work. Most are on the same network, so it is fairly repetitive. I want to bind `F1` to the repetitive part of the IP, so I can just smack that and type in the rest. After identifying `F1`, I wrote a test `.inputrc`:
"1~":"foobar"
output:
foobar
This worked. I then wrote it with the intended functionality:
"1~":"146.184.4"
output: 16.14.468
After some fiddling I realized that for any sequence of characters, numbers (or characters) succeeding a `1` were pushed to the end of the line.
Weird, right?
|
Try with this configuration instead:
"\e[11~":"146.184.4"
I used the `readline(3)` manpage for that.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "linux, bash, readline"
}
|
Multiple ID's in REST endpoints
coming from a Wordpress background my knowledge on using REST API's is quite limited. I've started using JSON server (dummy local rest API) to learn the ins and outs.
Looking at the documentation, there doesn't seem to be any way to delete, update or post multiple items in one go? The `PATCH`, `POST`, `PUT` and `DELETE` methods all require an endpoint structured with one trailing ID eg `/posts/1`. I've tried both sending multiple ID's in the url ie `?id=1&id=2` and also as part of the request body but neither seem to work.
Is this how typical REST API's work, and if so does this mean i would have to loop though ID's and send multiple requests for each, or am i missing the point??
|
With REST, you don't typically have bulk operations, unless you are, say, deleting a collection. A POST request usually inserts a single entity into a collection, although that doesn't mean that you CANNOT construct the endpoint to accept an array of entities to insert into the collection. When I design a RESTful endpoint for POSTing a new resource, I only accept a single entity. I leave it up to the client to perform multiple POST requests in parallel to reduce the time it takes to create the list of entities.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, rest, fetch, json server"
}
|
If I set the pixels for a component , will it behave the same on every monitor?
Will the following `css` :
#search_bar {
width: 300px;
margin-left:475px;
height:27px;
}
generate the same position of search bar on every mointor as in the following snapshot ?
!enter image description here
Like units in percentage will show the size accordingly on every monitor,is it the same with pixels ? I mean I try to align the search box as visible in the snapshot in the center but I don't know if it will look the same on broader monitors than mine.
|
Neither monitors nor screen resolution have anything to do with how your element will be positioned. What matters is the width/height of the viewport (especially since desktop users don't always maximize their browser). If the viewport is only 300px wide, not only will your element not be centered, it will be so far to the right that it will appear off screen! If the viewport is 2000px wide, it will be woefully far to the left.
Here are 2 options for perfectly centering an element no matter what the viewport size is.
input.one {
display: block;
margin: 0 auto;
width: 300px;
}
input.two {
width: 300px;
margin-left: -150px; /* half of the element's width */
position: relative;
left: 50%;
}
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "html, css, pixel"
}
|
Finite abelian groups of order 100
(a) What are the finite abelian groups of order 100 up to isomorphism?
(b) Say $G$ is a finite abelian group of order 100 which contains an element of order 20 and no element with larger order. Then G will be isomorphic to exactly one group from your list in (a): which one, and why?
Can someone tell me how to analyze this question? As for question (a), I know that finite abelian group could be isomorphic to $Z_{a_1}\times Z_{a_2}\times...\times Z_{a_n}$, but have no idea what's the relation between $a_1,a_2,...,a_n$ and 100. Can someone tell me how to analyze this question?
|
We just have to use the fundamental theorem for finite abelian groups.
Note $100=2^2\cdot 5^2$
You just have to choose a factorization of $2^2$ and a factorization of $5^2$.
The only two factorizations for $2^2$ are $2\cdot 2$ and $4$
the only two factorizations for $5^2$ are $5\cdot 5 $ and $25$.
So there are $4$ combinations, these give us all the groups:
$\mathbb Z_2\times \mathbb Z_2\times \mathbb Z_5\times \mathbb Z_5$
$\mathbb Z_2\times \mathbb Z_2\times \mathbb Z_{25}$
$\mathbb Z_4\times \mathbb Z_{5}\times \mathbb Z_5$
$\mathbb Z_4\times \mathbb Z_{25} \cong \mathbb Z_{100}$
* * *
The only of these that has maximum order $20$ is the third element in the list.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "abstract algebra, group theory, finite groups"
}
|
Showing a linear programming property
Let a linear programming (LP) in the form:
$\max \ cx$
$s.t. \ Ax\leq b,$
$\ \ \ \ \ \ \ \ x\geq0$
If this program has an optimal finite solution, then if I exchange $b$ to $\bar{b}$, **show that the new LP either has an finite optimal solution or is infeasible**.
Finally, how can I argue that, regardless of the value of $\bar{b}$ I choose, I will not have an unbounded LP problem?
obs: I dont need a rigorous formal proof, just arguments with a mathematical basis it's ok.
|
Let's write down the dual of the original problem:
$$\min p'b$$
$$p'A \geq c'$$ $$p \geq 0$$
We know that the original problem has a finite solution, hence we can conclude that the feasible region for the dual is non-empty.
Now, suppose we replace $b$ by $\bar{b}$.
Suppose on the contrary that the problem is unbounded, then the dual is infeasible. However, the new dual is
$$\min p'\bar{b}$$
$$p'A \geq c'$$ $$p \geq 0$$
We have earlier found out that the feasible region is instead non-empty, which is a contradiction.
Hence, it cannot be unbounded. The primal either has finite solution or it is not feasible.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "linear programming"
}
|
Old-style electrical conduit connector?
See photos. I'm having trouble finding this on the internet. Looks like it's some kind of compression connector for EMT conduit, with dimples. The conduit is 3/4"
What is this style of connector called?
Is there an easy/right way to remove it?
-4+3^\frac{1+h}{1-(1+h)^2}$$ $$RL=-2+\lim_{h \to 0}3^{\frac{(1+h)}{1-(1+2h)}}=-2+\lim_{h\to 0}3^{\frac{1+h}{-2h}}=-2$$ Left limit at $x=1$ is $$LL=\frac{8}{\pi}\tan^{-1}a $$ Finally, $LL=RL$ gives $a=-1$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "limits, piecewise continuity"
}
|
Has anybody actually already played Dungeons The Dragoning 40000 7th Edition?
Released as an April Fools joke, Dungeons The Dragoning 40000 7th Edition is a parody and conglomerate of many established roleplaying games, including but not limited to: D&D, WoD, 7th Sea, Exalted, Deadlands, WH 40k and many more.
While obviously not intended as a "real" rpg (it even says so in the credits) some elements and aspects of the game do sound interesting.
* Has anybody already tried running it or at least taken a closer look at the game's mechanics?
* How does it play, especially considering the strange combination of WoD's stat system with Lot5R's Roll-and-Keep dice system?
* What are the game's party dynamics (if such a thing exists in that system)
* What style of play is best suitable for the system (heroic, grim'n'gritty, ...)?
|
It is a pretty solid system. It's a bit on the rules-heavy side, but it has no real fundamental flaws, and the minor flaws are being ironed out. It may say that it's not real at the end, but as far as I know that's for legal reasons, as there is a complete (and entirely real) set of rules and fluff. It is best for heroic games and games that are at least a little bit beer-and-pretzels. If you can't abide light-heartedness, you won't like it, but anyone else will probably enjoy it fine. Party dynamic is based on what people want to play, there aren't really proscribed roles like D&D or Shadowrun.
|
stackexchange-rpg
|
{
"answer_score": 13,
"question_score": 15,
"tags": "dungeons the dragoning"
}
|
how to include mobile like scrollbars in AngularJS based web application?
I've a web application based on AngularJS which runs on mobile phone. I've screens that have scrollbars. But I want these scrollbars to look like a standard mobile scrollbars.
For example, see the scrollbars used inside facebook.com. Iam looking for scrolbars like these.
Thanks
|
I found an awesome JavaScript lib that does all more than scroll and because their modules are broken up functionally, developers only need to use the one that fits their need thereby reducing the net time.
It works on mobile and across platforms as well.
No dependency on any other library as well (like jQuery or AngularJS).
Check this out iScroll.
Appreciations to iScroll team !
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "facebook, angularjs, user interface"
}
|
Import .pem public and private keys to JKS keystore
I have public and private keys in separate .pem files that I would need to get into a JKS keystore somehow.
Tried using the -import command in KeyTool for this, which gives an "not an X.509 certificate" error.
I'm guessing the solution has to do with OpenSSL, but I'm not entirely sure what to do with it.
Would really appreciate any help with this, since I'm completely clueless with everything crypto-related.
Thanks in advance, \--Rolf
|
KeyTool expects the objects in DER format. PEM is Base64-encoded DER, with a header and a footer. KeyTool cannot parse PEM.
However, OpenSSL can convert PEM objects to DER. E.g., for an X.509 certificate, the `-outform DER` command-line flag instructs OpenSSL to use DER as its output format.
This page apparently contains some more detailed explanations.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 12,
"tags": "cryptography, certificate, public key, keystore, private key"
}
|
How to choose between different forecasting methods
If we have 2 ways of predicting a variable y: Regression:
y(t) = ax(t) + b + e;
and a time series AR model:
y(t) = c.y(t - 1) + d.y(t - 2) + e.
And both give similar results in out of sample testing, which method should we choose?
|
The regression model assumes the errors to be independent, whereas the time series autorregresive model takes into account the correlation. Maybe the output for some specific forecast is the same but the models are not, and if your data is correlated over time you should take the second approach.
|
stackexchange-stats
|
{
"answer_score": 1,
"question_score": 4,
"tags": "regression, time series, forecasting"
}
|
LeetCode 509: Fibonacci Number "int object not subscriptable"
LeetCode 509: Fibonacci Number
class Solution:
def fib(self, N: int) -> int:
if N == 0:
return 0
if N == 1:
return 1
memo = [None] * (N+1)
return self.recurse(N, memo)
def recurse(self, N: int, memo: List) -> int:
if N == 0:
return 0
elif N == 1:
return 1
elif memo[N] != None:
return memo[N]
memo[N] = self.recurse(N-1, N-2)
return memo[N]
I am getting an "int object not subscriptable" error on the line "elif memo[n] != None:". However, memo is a list not an int. I can't figure out why I am getting this error. Maybe it has to do with the fact that I initialized my List with all None elements? Any help would be appreciated. Thank you!
|
Here you go:
from typing import List
class Solution:
def fib(self, N: int) -> int:
if N == 0: return 0
elif N == 1: return 1
memo = [None] * (N+1)
memo[0] = 0
memo[1] = 1
return self.recurse(N, memo)
def recurse(self, N: int, memo: List) -> int:
if memo[N] is not None:
return memo[N]
memo[N] = self.recurse(N - 1, memo) + self.recurse(N - 2, memo)
return memo[N]
solution = Solution()
for i in range(10):
print(f'fib({i}) = {solution.fib(i)}')
Output:
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python, algorithm, fibonacci, memoization"
}
|
probability problem - expectation
A tourist wants to visit four cities: A, B, C and D. First he chooses one at random. If he chooses A he then randomly chooses among B, C and D. If he chooses B then he randomly chooses among A, C, D. The tourist remembers only the city he's in and not the ones he visited. Find the expectation for the numbers of cities he visits before visiting the four cities. I haven't really tried much since i don't know where to start... Thanks
|
In the first $2$ trips, the tourist will have visited $2$ cities.
Let $X$ be the number of extra visits until a third city is visited. Let $Z$ be the number of extra visits beyond that until the fourth city is visited. Then the total number of visits is $2+X+Y$. We want to find the expectation of this, that is, we want to find $2+E(X)+E(Y)$.
Once the tourist has visited the second city, with probability $\frac{2}{3}$ the next visit is to a new city, and with probability $\frac{1}{3}$ it is to an old city. So (expectation of a geometric random variable), we have $E(Y)=\frac{3}{2}$.
Once the tourist has visited the third city, with probability $\frac{1}{3}$ the next visit is to a new city, and with probability $\frac{2}{3}$ it is to an old one. You can now write down $E(Z)$, and conclude what the expected total number of visits will be.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "probability"
}
|
How to know whether NSTableView is in editing?
I want to check if my NSTableView is in editing or not.
I tried to use **tableView: shouldEditTableColumn: row:** and **tableView: setObjectValue: forTableColumn: row:** functions. For example:
- (BOOL)tableView:(NSTableView *)tableView shouldEditTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
isRenaming = YES;
return YES;
}
- (void)tableView:(NSTableView *)tableView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
isRenaming = NO;
...
}
However, **tableView: shouldEditTableColumn: row:** function was called even when I didn't try to edit the tableview.
So, sometimes, isRenaming is remained to YES.
How to know whether NSTableView is in editing?
|
Finally, I found the missing case.
" **tableView: shouldEditTableColumn: row:** " function was called when the double-click event was occured on NSTableView.
So,
- (void)tableViewDoubleClicked:(id)sender {
isRenamed = NO;
...
}
It solved the problem.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "objective c, macos, nstableview, editing"
}
|
BreakIterator ICU - Get byte length of grapheme cluster
When using the BreakIterator from ICU, is there a way to retrieve the byte length (or code unit length) of the grapheme cluster at the nth boundary in the input string? Ideally with the least amount of API calls.
|
Self Answer:
If you know your current index in code-units, then you can use ICU::ubrk_current() to return the the cude unit index most recently returned by ICU::ubrk_next(). See: <
I was mostly confused by the ambiguity in the descriptions of the UBreakIterator methods. However, after contacting ICU support, "Character Index" is equivalent to the code-unit index in this case.
With this information, a simple implementation is as follows:
(ubrk_current(m_breakIterator) - currentIndexInCodeUnits) * INTERNAL_ENCODING_BYTE_LENGTH;
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "unicode, iterator, icu"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.