qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
1,911,426 |
In one customer computer (windows vista) almost all forms of my app are oddly unnaligned.
Making some investigation I noticed that every component with akRight anchor acts oddly, being positioned way more for the right.
Searching in SO I found [this](https://stackoverflow.com/questions/1355258/delphi-7-forms-anchors-not-working-in-vista) issue wich is similar to mine but not exacly the same.
Since I cannot reproduce the issue in my computer and my access to my customer´s computer is restrict to a few minutes and via remote desktop I´d like to know if my issue described here could be solved by the same fix.
|
2009/12/16
|
[
"https://Stackoverflow.com/questions/1911426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19224/"
] |
Aren't you experiencing the problem described in the following question?
[Why do my Borland C++Builder 5 forms with right-anchored controls appear incorrectly on Vista?](https://stackoverflow.com/questions/525517/why-do-my-borland-cbuilder-5-forms-with-right-anchored-controls-appear-incorrec)
Maybe the answer is of some help.
|
35,813,854 |
I want to join more than two collections in MongoDB using the aggregate `$lookup`. Is it possible to join? Give me some examples.
Here I have three collections:
`users`:
```
{
"_id" : ObjectId("5684f3c454b1fd6926c324fd"),
"email" : "[email protected]",
"userId" : "AD",
"userName" : "admin"
}
```
`userinfo`:
```
{
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"phone" : "0000000000"
}
```
`userrole`:
```
{
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"role" : "admin"
}
```
|
2016/03/05
|
[
"https://Stackoverflow.com/questions/35813854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5492366/"
] |
The join feature supported by **Mongodb 3.2** and later versions. You can use joins by using **aggregate** query.
You can do it using below example :
```
db.users.aggregate([
// Join with user_info table
{
$lookup:{
from: "userinfo", // other table name
localField: "userId", // name of users table field
foreignField: "userId", // name of userinfo table field
as: "user_info" // alias for userinfo table
}
},
{ $unwind:"$user_info" }, // $unwind used for getting data in object or for one record only
// Join with user_role table
{
$lookup:{
from: "userrole",
localField: "userId",
foreignField: "userId",
as: "user_role"
}
},
{ $unwind:"$user_role" },
// define some conditions here
{
$match:{
$and:[{"userName" : "admin"}]
}
},
// define which fields are you want to fetch
{
$project:{
_id : 1,
email : 1,
userName : 1,
userPhone : "$user_info.phone",
role : "$user_role.role",
}
}
]);
```
This will give result like this:
```
{
"_id" : ObjectId("5684f3c454b1fd6926c324fd"),
"email" : "[email protected]",
"userName" : "admin",
"userPhone" : "0000000000",
"role" : "admin"
}
```
Hope this will help you or someone else.
Thanks
|
126,378 |
I just reinstalled Windows 7 on my Dell Inspiron 15R SE 7520 and I'm trying to get the dicrete GPU selected. But even though I got the High Performance option selected on Catalyst Control Center, I can't get Skyrim to run on the discrete GPU. How can I get it working?
EDIT:
I forgot to mention this is a hybrid GPU, it needs the on chip intel one to perform in any level... IMHO, a crappy design.
|
2013/08/03
|
[
"https://gaming.stackexchange.com/questions/126378",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/53082/"
] |
No guarantee to work (don't have a onboard card to test), but I'd assume the following should work:
* Go to `[my documents]\My Games\Skyrim` and open `SkyrimPrefs.ini` with your favorite text editor.
* Look for a line starting with `iAdapter=`. Actually it should state `iAdapter=0`. Change it to `iAdapter=1`.
Try launching the game again, avoid going into the launcher's settings.
|
13,797 |
I would like to force an update of App Store applications from the command line.
How can I do this?
|
2011/05/09
|
[
"https://apple.stackexchange.com/questions/13797",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/1916/"
] |
Apple doesn't supply a command line helper or any scriptable cocoa classes you can latch on to for automation. Unlike the overall software update, which allows updates and installs out of the box, you can script the process of clicking buttons with a mouse using Automator.
However, the app store has been reverse engineered and released open source [as well as a binary form](https://github.com/argon/mas/blob/master/ghreleases):
* <https://github.com/argon/mas>
The install is quick and it appears to be quite reliable on the current version of OS X 10.11:
```
brew install argon/mas/mas
```
With the source released, I would expect some other implementations of this tool to pop up, perhaps even one scripted with python.
If someone is logged into the mac (windowmanager is running), you can use Automator and the "watch me do" function to automate updates and storing your store password in the script fairly insecurely.
Here are two tutorials to get you started if this meets your needs.
<http://www.tuaw.com/2009/01/19/mac-automation-creating-watch-me-do-workflows/>
<http://automator.us/leopard/features/virtual-user.html>
Once you have a working script, you can use the command line `open` command to kick it off.
If the App Store app ever exposes that function to scripting you will have more options from the command line. It would be easy to use `sdef`, `sdp` and `gen_bridge_metadata` to [dump the entire scriptable dictionary and script things using ruby](http://www.macruby.org/trac/wiki/MacRubyTutorial) from the command line, but at present the best option would be to use the `mas` command line tool.
|
4,244,896 |
I'm trying to access a property of an object using a dynamic name. Is this possible?
```
const something = { bar: "Foobar!" };
const foo = 'bar';
something.foo; // The idea is to access something.bar, getting "Foobar!"
```
|
2010/11/22
|
[
"https://Stackoverflow.com/questions/4244896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/471628/"
] |
There are [two ways to access properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) of an object:
* Dot notation: `something.bar`
* Bracket notation: `something['bar']`
The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:
```js
var something = {
bar: 'foo'
};
var foo = 'bar';
// both x = something[foo] and something[foo] = x work as expected
console.log(something[foo]);
console.log(something.bar)
```
|
33,489,517 |
I'm trying to build a speech recognition in Windows 10 (using Cortana) in Visual C#.
This is part of my code for speech recognition using old System.Speech.Recognition and works great, but it only support english.
```
SpeechSynthesizer sSynth = new SpeechSynthesizer();
PromptBuilder pBuilder = new PromptBuilder();
SpeechRecognitionEngine sRecognize = new SpeechRecognitionEngine();
Choices sList = new Choices();
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
pBuilder.ClearContent();
pBuilder.AppendText(textBox2.Text);
sSynth.Speak(pBuilder);
}
private void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
button3.Enabled = true;
sList.Add(new string[] { "who are you", "play a song" });
Grammar gr = new Grammar(new GrammarBuilder(sList));
try
{
sRecognize.RequestRecognizerUpdate();
sRecognize.LoadGrammar(gr);
sRecognize.SpeechRecognized += sRecognize_SpeechRecognized;
sRecognize.SetInputToDefaultAudioDevice();
sRecognize.RecognizeAsync(RecognizeMode.Multiple);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
private void sRecognize_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
textBox1.Text = textBox1.Text + " " + e.Result.Text.ToString() + "\r\n";
}
```
How can I do it using new speech recognition in windows 10?
|
2015/11/03
|
[
"https://Stackoverflow.com/questions/33489517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1430781/"
] |
Use [Microsoft Speech Platform SDK v11.0](https://msdn.microsoft.com/en-us/library/office/hh361572%28v=office.14%29.aspx) (*Microsoft.Speech.Recognition*).
It works like System.Speech, but you can use Italian language (separeted install) and also use [SRGS Grammar](https://msdn.microsoft.com/en-us/library/office/hh361653%28v=office.14%29.aspx). I work with both kinect (*SetInputToAudioStream*) and default input device (*SetInputToDefaultAudioDevice*) without hassle.
Also it works offline, so no need to be online as with Cortana.
With the SRGS grammar you can get a decent level of complexity for your commands
**UPDATE**
Here is how I initialize the recognizer
```
private RecognizerInfo GetRecognizer(string culture, string recognizerId)
{
try
{
foreach (var recognizer in SpeechRecognitionEngine.InstalledRecognizers())
{
if (!culture.Equals(recognizer.Culture.Name, StringComparison.OrdinalIgnoreCase)) continue;
if (!string.IsNullOrWhiteSpace(recognizerId))
{
string value;
recognizer.AdditionalInfo.TryGetValue(recognizerId, out value);
if ("true".Equals(value, StringComparison.OrdinalIgnoreCase))
return recognizer;
}
else
return recognizer;
}
}
catch (Exception e)
{
log.Error(m => m("Recognizer not found"), e);
}
return null;
}
private void InitializeSpeechRecognizer(string culture, string recognizerId, Func<Stream> audioStream)
{
log.Debug(x => x("Initializing SpeechRecognizer..."));
try
{
var recognizerInfo = GetRecognizer(culture, recognizerId);
if (recognizerInfo != null)
{
recognizer = new SpeechRecognitionEngine(recognizerInfo.Id);
//recognizer.LoadGrammar(VoiceCommands.GetCommandsGrammar(recognizerInfo.Culture));
recognizer.LoadGrammar(grammar);
recognizer.SpeechRecognized += SpeechRecognized;
recognizer.SpeechRecognitionRejected += SpeechRejected;
if (audioStream == null)
{
log.Debug(x => x("...input on DefaultAudioDevice"));
recognizer.SetInputToDefaultAudioDevice();
}
else
{
log.Debug(x => x("SpeechRecognizer input on CustomAudioStream"));
recognizer.SetInputToAudioStream(audioStream(), new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null));
}
}
else
{
log.Error(x => x(Properties.Resources.SpeechRecognizerNotFound, recognizerId));
throw new Exception(string.Format(Properties.Resources.SpeechRecognizerNotFound, recognizerId));
}
log.Debug(x => x("...complete"));
}
catch (Exception e)
{
log.Error(m => m("Error while initializing SpeechEngine"), e);
throw;
}
}
```
|
15,564 |
I am trying to install latest GIMP on Loki 0.4.1.
But every time I try to download the packages I get error like the following :
```
E: Unable to locate package pythonany
```
Note : I am trying to install by using the following commands :
```
sudo add-apt-repository ppa:otto-kesselgulasch/gimp
sudo apt-get update
```
and then :
getdebs.sh
```
#!/bin/bash
package=gimp
apt-cache depends "$package" | grep Depends: >> deb.list
sed -i -e 's/[<>|:]//g' deb.list
sed -i -e 's/Depends//g' deb.list
sed -i -e 's/ //g' deb.list
filename="deb.list"
while read -r line
do
name="$line"
apt-get download "$name"
done < "$filename"
apt-get download "$package"
```
for downloading them for offline install.
---
**Maccer**
: Thanks for replying. I was quite anxious.
I am totally new to Linux. Elementary OS is my first Linux distro.
Anyway, I can install GIMP 2.8.16 without that ppa.
But I should be able to install GIMP 2.8.22 using that ppa.
So I want to install GIMP 2.8.22 or later in any possible ways. [ Except compile from source ]
The problem is the following :
* I should be able to install GIMP 2.10.0 using that ppa.
* But even with the ppa I can only get access to GIMP 2.8.22.
* 2.8.22 is no problem.
* I just want to use latest 2.8.x if I will get access only to older
versions.
I tried to install 2.8.22 and got that error :
```
E: Unable to locate package pythonany
```
Where can I get "pythonany" ?
Is 16.04.3 supported anymore ?
Why does the repository offer 2.8.16 instead of 2.8.22?
Anyway, I just want to use at least 2.8.22 or 2.10.0.
How can I do that?
|
2018/05/17
|
[
"https://elementaryos.stackexchange.com/questions/15564",
"https://elementaryos.stackexchange.com",
"https://elementaryos.stackexchange.com/users/14710/"
] |
There is an update that fixes this issue. Just update in AppCentre or run the following commands in terminal:
```
sudo apt update
sudo apt full-upgrade
```
|
25,741,563 |
So I constructed my `unordered_set` passing 512 as min buckets, i.e. the `n` parameter.
My hash function will always return a value in the range `[0,511]`.
My question is, may I still get collision between two values which the hashes are not the same? Just to make it clearer, I tolerate any collision regarding values with the same hash, but I may not get collision with different hashes values.
|
2014/09/09
|
[
"https://Stackoverflow.com/questions/25741563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/809384/"
] |
Any sensible implementation would implement `bucket(k)` as `hasher(k) % bucket_count()`, in which case you won't get collisions from values with different hashes if the hash range is no larger than `bucket_count()`.
However, there's no guarantee of this; only that equal hash values map to the same bucket. A bad implementation could (for example) ignore one of the buckets and still meet the container requirements; in which case, you would get collisions.
If your program's correctness relies on different hash values ending up in different buckets, then you'll have to either check the particular implementation you're using (perhaps writing a test for this behaviour), or implement your own container satisfying your requirements.
|
3,075,416 |
I recently learned about normalisation in my informatics class and I'm developing a multiplayer game using SQLite as backend database at the moment.
Some information on it:
The simplified structure looks a bit like the following:
```
player_id | level | exp | money | inventory
---------------------------------------------------------
1 | 3 | 120 | 400 | {item a; item b; item c}
```
Okay. As you can see, I'm storing a table/array in string form in the column "inventory". This is against normalization.
**But the thing is: Making an extra table for the inventory of players brings only disadvantages for me!**
* The only points where I access the database is:
+ When a player joins the game and his profile is loaded
+ When a player's profile is saved
When a player joins, I load his data from the DB and store it in memory. I only write to the DB like every five minutes when the player is saved. So there are actually very few SQL queries in my script.
If I used an extra table for the inventory I would have to, upon loading:
* Perform an performance and probably more data-intensive query to fetch all items from the inventory table which belong to player X
* Walk through the results and convert them into a table for storage in memory
And upon saving:
* Delete all items from the inventory table which belong to player X (player might have dropped/sold some items?)
* Walk through the table and perform a query for each item the player owns
If I kept all the player data in one table:
* I'd only have one query for saving and loading
* Everything would be in one place
* I would only have to (de)serialize the tables upon loading and saving, in my script
**What should I do now?**
**Do my arguments and situation justify working against normalisation?**
|
2010/06/19
|
[
"https://Stackoverflow.com/questions/3075416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/370999/"
] |
Are you saying that you think parsing a string out of "inventory" *doesn't* take any time or effort? Because everything you need to do to store/retrieve inventory items from a sub table is something you'd need to do with this string, and with the string you don't have any database tools to help you do it.
Also, if you had a separate subtable for inventory items, you could add and remove items in real time, meaning that if the app crashes or the user disconnects, they don't lose anything.
|
66,219,282 |
I need to remove the outer key from array and reindex the left array. I have array in this format:
```
Array (
[0] => Array (
[0] => Array(
[id] => 123
),
[1] => Array (
[id] => 144
)
),
[1] => Array (
[0] => Array (
[id] => 354
)
)
)
```
I want to format this to this one:
```
Array (
[0] => Array (
[id] => 123
),
[1] => Array (
[id] => 144
),
[2] => Array (
[id] => 354
)
)
```
|
2021/02/16
|
[
"https://Stackoverflow.com/questions/66219282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/584259/"
] |
You can use `call_user_func_array()` with `array_merge`:
```php
$array = call_user_func_array('array_merge', $array);
```
|
11,001,178 |
I have a function-like macro that takes in an enum return code and a function call.
```
#define HANDLE_CALL(result,call) \
do { \
Result callResult = call; \
Result* resultVar = (Result*)result; \
// some additional processing
(*resultVar) = callResult; \
} while(0)
```
Does fancy pointer casting to `Result*` and subsequent de-referencing gain you anything? That is, is there any advantage to doing this over just:
```
callResult = call;
// additional processing
*result = callResult;
```
The macro is used like this:
```
Result result;
HANDLE_CALL(&result,some_function());
```
By the way, this isn't my code and I'm not a power C user so I'm just trying to understand if there is any logic behind doing this.
|
2012/06/12
|
[
"https://Stackoverflow.com/questions/11001178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/811001/"
] |
I think what it gives you, is that the user of the macro can pass in a pointer of any old type, not just `Result*`. Personally I'd either do it your way, or if I really wanted to allow (for example) a `void*` macro argument I'd write `*(Result*)(result) = callResult;`.
There's another thing it *might* be, depending what the rest of the macro looks like. Does "some additional processing" mention `resultVar` at all, or is the line `(*resultVar) = callResult;` conditional? If so, then `resultVar` exists in order to ensure that the macro evaluates each of its arguments *exactly* once, and therefore behaves more like a function call than it would if it evaluated them any other number of times (including zero).
So, if you call it in a loop like `HANDLE_CALL(output++, *input++)` then it does something vaguely predictable. At least, it does provided that `output` is a `Result*` as the macro author intended. I'm still not sure what the cast gives you, other than allowing different argument types like `void*` or `char*`.
There are some situations where it could make another difference whether you have that extra cast or not. For example, consider:
```
typedef double Result;
int foo() { return 1; }
int i;
HANDLE_CALL(&i, foo());
```
if `typedef double Result;` isn't visible on screen, the other three lines appear pretty innocuous. What's wrong with assigning an int to an int, right? But once the macro is expanded, bad stuff happens when you cast an `int*` to `double*`. With the cast, that bad stuff is undefined behavior, most likely `double` is bigger than `int` and it overruns the memory for `i`. If you're lucky, you'll get a compiler warning about "strict aliasing".
Without the cast you can't do `double* resultVar = &i;`, so the original macro with that change catches the error and rejects the code, instead of doing something nasty. Your version with `*result = callResult;` actually works, provided that `double` can accurately represent every value of `int`. Which with an IEEE double and an `int` smaller than 53 bits, it can.
Presumably `Result` is really a struct, and nobody would really write the code I give above. But I think it serves as an example why macros always end up being more fiddly than you think.
|
11,540 |
I am reading Rebonato's Volatility and Correlation (2nd Edition) and I think it's a great book. I'm having difficulty trying to derive a formula he used that he described as the expression for standard deviation in a simple binomial replication example:
\begin{eqnarray}\sigma\_S\sqrt{\Delta t}=\frac{\ln S\_2-\ln S\_1}{2}\end{eqnarray}
This expression is equation (2.48) on page 45. You can read that page and get some context from Google Books:
<http://goo.gl/uDgYg3>
I understand continuous compounding is used in the example, if that helps any. It's a little confusing because the equations he listed a few pages above (pg.43; not available in Google Books) use a discrete rate of return, not continuous compounding. But in any case, this discrepancy does not seem to provide any hint as to how the standard deviation is obtained.
Any help is much appreciated.
|
2014/06/03
|
[
"https://quant.stackexchange.com/questions/11540",
"https://quant.stackexchange.com",
"https://quant.stackexchange.com/users/3510/"
] |
To solve the expectation directly, you need to remember that a density function is not the same as the probability of the event.
We have, $\frac{S\_1}{S\_0} \sim \ln \mathcal{N} \left(-\frac{\sigma^2}{2},\sigma\right)$, therefore,
\begin{eqnarray}
\mathbb{E}\left(\frac{S\_1}{S\_0}\right) &=& \int\_{-\infty}^\infty x\, f\_{\frac{S\_1}{S\_0}}(x)dx\\
&=&\int\_{-\infty}^\infty x \, \frac{1}{x\sqrt{2\pi}\sigma}\exp\left[-\frac{\left(\ln x+\frac{\sigma^2}{2}\right)^2}{2\sigma^2}\right]dx.
\end{eqnarray}
The usual substitution method aims to manipulate the expression into looking like a standard normal. To do this we use $z=\frac{\ln x + \frac{\sigma^2}{2}}{\sigma}-\sigma$ and we get the substitutions $dx=x \sigma dz$ and $x=\exp(\sigma z + \frac{\sigma^2}{2})$.
\begin{eqnarray}
\mathbb{E}\left(\frac{S\_1}{S\_0}\right) &=& \int\_{-\infty}^\infty \frac{1}{\sqrt{2\pi} \sigma} \sigma \exp\left(\sigma z + \frac{\sigma^2}{2}\right) \exp\left( \frac{-z^2 - 2\sigma z -\sigma^2}{2} \right)dz\\
&=&\int\_{-\infty}^\infty \frac{1}{\sqrt{2\pi}}\exp\left(-\frac{z^2}{2}\right) dz\\
&=&1.
\end{eqnarray}
|
799,049 |
I have this regular expression that extracts meta tags from HTML documents but it gives me errors while I incorporate it in my web application.
the expression is
```
@"<meta[\\s]+[^>]*?name[\\s]?=[\\s\"\']+(.*?)[\\s\"\']+content[\\s]?=[\\s\"\']+(.*?)[\"\']+.*?>" ;
```
is there anything wrong with it?
|
2009/04/28
|
[
"https://Stackoverflow.com/questions/799049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/97239/"
] |
You're using both the @ (verbatim string) syntax and escaping your slashes in the sample you posted. You need to either remove the @, or remove the extra slashes and escape your double quotes by doubling them up, then it should work.
(For what it's worth, if you're going to be working with regular expression on an ongoing basis, I would suggest investing in a copy of [RegExBuddy](http://www.regexbuddy.com/).)
|
18,647 |
One of the comments on [this question](https://mechanics.stackexchange.com/questions/18623/mileage-varies-by-driving-at-different-speeds) reminded me of something I've been wondering for a while. Given that engines get the best efficiency at peak torque, why do most hybrid cars still use a mechanical transmission (which requires the engine to change speed with roadspeed, as in a conventional car), rather than electrical, with the engine running at a constant rate as a generator?
Is it simply a case of giving people what they are used to? bearing in mind that pure-electric cars obviously have electric transmission...
Trains have been using diesel-electric transmission since at least the 1950s, so it's not exactly a new concept...
|
2015/07/21
|
[
"https://mechanics.stackexchange.com/questions/18647",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/373/"
] |
It depends on the type of hybrid car you are talking about. In one type of hybrid, there will be a gasoline engine and at least one electric engine capable of driving the wheels. In this case, the gasoline engine must still use a transmission because it cannot be revved too high without causing major damage or shortened life. One possible solution to this transmission issue would be to use a Continuously Variable Transmission (CVT), which can be more expensive to manufacture but keeps the engine at peak efficiency.
The other type of hybrid, where the wheels are driven entirely by electric motors (and has a gasoline generator to charge the battery) does not require a transmission because electric motors have a very wide range of acceptable RPM. Additionally, electric motors have a relatively flat torque curve and the max torque is available instantly. I should note that this type of "hybrid" car is generally just called an electric vehicle (EV) since the gasoline motor is used to charge the battery only and does not drive the wheels.
I was going to comment this, but don't have the reputation:
The diesel-electric transmission you referred to is more closely related to today's EVs in that a diesel engine charges batteries, which then in turn power electric motors at the wheels. Transmissions in trains are impractical for several reasons (such as need to power up to four axles and the number of gears that would be required to keep it at peak efficiency) and this eliminates the need for a true transmission.
|
62,180,045 |
I have a github [repo](https://github.com/NEOdinok/lcthw_ex29) representing my exercise folder. Upon running `make all` the compiler throws error messages saying (Ubuntu):
```
cc -g -O2 -Wall -Wextra -Isrc -DNDEBUG -fPIC -c -o src/libex29.o src/libex29.c
src/libex29.c: In function ‘fail_on_purpose’:
src/libex29.c:36:33: warning: unused parameter ‘msg’ [-Wunused-parameter]
int fail_on_purpose(const char* msg)
^~~
ar rcs build/libex29.a src/libex29.o
ranlib build/libex29.a
cc -shared -o build/libex29.so src/libex29.o
cc -g -Wall -Wextra -Isrc test/ex29_test.c -o test/ex29_test
/tmp/cc7dbqDt.o: In function `main':
/home/givi/Desktop/lcthw_dir/29/test/ex29_test.c:21: undefined reference to `dlopen'
/home/givi/Desktop/lcthw_dir/29/test/ex29_test.c:22: undefined reference to `dlerror'
/home/givi/Desktop/lcthw_dir/29/test/ex29_test.c:25: undefined reference to `dlsym'
/home/givi/Desktop/lcthw_dir/29/test/ex29_test.c:26: undefined reference to `dlerror'
/home/givi/Desktop/lcthw_dir/29/test/ex29_test.c:33: undefined reference to `dlclose'
collect2: error: ld returned 1 exit status
<builtin>: recipe for target 'test/ex29_test' failed
make: *** [test/ex29_test] Error 1
```
i spent quite a lot trying to figure out how to `fix undefined references`. dlfcn.h is included, everything seems to be ok. Am i missing something? Please help
|
2020/06/03
|
[
"https://Stackoverflow.com/questions/62180045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12868956/"
] |
You must add following option when linking code using [dlopen(3)](https://man7.org/linux/man-pages/man3/dlopen.3.html) :
```
-ldl
```
Here is a demo for Ubuntu 18:
```
$ cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.4 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.4 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic
$ cat dl.c
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
void *r;
r = dlopen("", RTLD_LAZY);
if (r != NULL)
printf("r is not null \n");
return 0;
}
$ gcc -o dl -Wall -pedantic -std=c11 dl.c -ldl
$ echo $?
0
```
Here is a very simple Makefile(note position of `-ldl`) and related make commands:
```
$ cat Makefile
CFLAGS=-g -O2 -Wall -Wextra -Isrc -DNDEBUG $(OPTFLAGS) $(OPTLIBS)
dl.o :dl.c
$(CC) -c $< $(CFLAGS)
dl :dl.o
$(CC) -o $@ $^ $(CFLAGS) -ldl
clean :
rm -f dl dl.o
$ make clean
rm -f dl dl.o
$ make dl
cc -c dl.c -g -O2 -Wall -Wextra -Isrc -DNDEBUG
dl.c: In function ‘main’:
dl.c:5:14: warning: unused parameter ‘argc’ [-Wunused-parameter]
int main(int argc, char **argv)
^~~~
dl.c:5:27: warning: unused parameter ‘argv’ [-Wunused-parameter]
int main(int argc, char **argv)
^~~~
cc -o dl dl.o -g -O2 -Wall -Wextra -Isrc -DNDEBUG -ldl
$ ./dl
r is not null
```
|
152,186 |
I have an attribute of type CustomSetting\_\_c(which is a list type of CUSTOM SETTING) and I want to iterate over it to fetch its each record, and print that record's certain fields. I am unable to iterate over it and '.length' property is givng me error as:
>
> [Cannot read property 'length' of undefined]
>
>
>
Please find related code:
>
> Lightning component attribute:
>
>
>
```
<aura:attribute name="customSettingList" type="CustomSetting__c[]" />
```
On click of certain button, I want to go to helper of this component and execute this code:
>
> Helper.js:
>
>
>
```
//some code before this
component.set("v.customSettingList", response.getReturnValue());
//some code after this statement
var customSettingList=[];
customSettingList=component.get("v.customSettingList");
for(var i=0;i<customSettingList.length;i++){
console.log('customSettingList type: '+ customSettingList[i].Type__c);
}
```
where Type\_\_c is a custom field of this custom setting.
What is the reason for this? How can I access the field values of individual records from list?
Note: This is a list type of custom setting if that has to do anything with this.(Can we not access list custom setting in JS?)
|
2016/12/12
|
[
"https://salesforce.stackexchange.com/questions/152186",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/31234/"
] |
The issue you are facing here is the fact that your customSettingList is undefined.
This means you have not assigned any values to it.
This being said I'm missing the part where you are actually fetching the custom settings list.
Simply declaring this on your component is not sufficient:
```
<aura:attribute name="customSettingList" type="CustomSetting__c[]" />
```
The above code is simply telling lightning/aura that your component has an attribute of type CustomSetting\_\_c[]. By default this attribute has no values assigned, nor is lightning capable of doing this for you.
You will need to access the server yourself in order to get the list of custom settings and assign it to your attribute. You can do this by adding an Apex controller to your component.
More details can be found here:
<https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/apex_intro.htm>
|
32,657,517 |
When I run this:
```
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
try {
$("#div1").load("demoddd.txt"); //there is no demoddd.txt
}
catch (err)
{
alert("Error: " + err); //this never runs
}
finally {
alert("Finally");
}
});
});
</script></head>
<body>
<button id="btn">Load file</button>
<div id="div1"></div>
</body>
</html>
```
I get "Finally" but no error. In the debug console, I see the 404. Can I trap 404 errors when using the load() function?
|
2015/09/18
|
[
"https://Stackoverflow.com/questions/32657517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1649677/"
] |
Use the `complete` function as shown in the [**documentation**](http://api.jquery.com/load/):
```
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
```
|
71,950,079 |
Im trying to link my git repo to an azure synapse sandbox and Im facing this error
```
Failed to list GitHub repositories. Please make sure account name is correct and you have permission to perform the action.
```
Im using a personal access token, an enterprise git account, and full repo access for the token.
[](https://i.stack.imgur.com/BJBfl.png)
Could someone please point what I maybe missing. Does it require any permission on the azure side as well ?
|
2022/04/21
|
[
"https://Stackoverflow.com/questions/71950079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6666008/"
] |
>
> **Configure a Repository**
>
>
>
**Go** to ***GitHub*** -> open code and ***copy HTTPS Link*** use this link to ***GitHub enterprise URL Login*** on synapse -> Creating a [**personal access token**](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token) on GitHub -> connect to GitHub.
[](https://i.stack.imgur.com/gVsHx.png)
[](https://i.stack.imgur.com/kVCtH.png)
***Creating a personal access token***
[](https://i.stack.imgur.com/hMWnK.png)
[](https://i.stack.imgur.com/1wlfz.png)
[](https://i.stack.imgur.com/n1sm2.png)
**Reference**:
<https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token>
<https://www.reviewboard.org/docs/manual/dev/admin/configuration/repositories/github-enterprise/>
|
30,275,753 |
I am trying to do something like this
```
var teller = 1;
if (teller % 2 === 0) {
"do this"
} else {
"do something else"
}
teller++;
```
The problem is that he always comes into the else loop.
Someone knows why?
|
2015/05/16
|
[
"https://Stackoverflow.com/questions/30275753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4695733/"
] |
because `1 % 2 === 0` returns `false`
you might want to put it inside a loop
```
var teller = 1;
while(teller < 100){ //100 is the range, just a sample
if (teller % 2 === 0) {
"do this"
} else {
"do something else"
}
teller++;
}
```
|
26,288 |
A commercial came on the radio last night while I was driving home that was a spoof on the old [news reels of the 30s and 40s](https://en.wikipedia.org/wiki/Newsreel). And, being radio, the spoof was entirely centered on the iconic 'voice' of those old news reals...quick talking with an inflection unique enough that when you hear it you immediately think "ah, news reels!"
That got me wondering what the history of that voice is. Did news reels typically sound like that? Or is that a stereotype that, overtime, has become emblematic of those reels even if not entirely accurate? If news reels did sound like that, was that a general style adopted by narrators, or was it something that came from one prominent/prolific narrator in particular?
If you look through old newsreels on YouTube, they definitely do *not* all share that iconic narration voice, so I'm assuming this was a fabrication at some point in time.
(PS, I wasn't sure which site to post this on...perhaps this would be better asked on Moviews/TV?)
UPDATE:
Trying to find some specific examples. The one I heard on the radio was actually a Geico commercial. But can't find that.
The Legend of Korra uses this stereotypical news reel voice as a recap for each episode. You can see an example here: <https://www.youtube.com/watch?v=bigqWlscHYc> It's not quite as over-the-top as you find in more satirical uses but seems to be fairly consistent with the style elsewhere.
If I had to describe the style I'd say it's"
* fast talking
* un-natural inflection
* 'showmanship'
* a trace of an accent...maybe New-Englandish?
|
2015/11/09
|
[
"https://history.stackexchange.com/questions/26288",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/10250/"
] |
It wasn't just the newsreels. The ultra-fast talking high-pitched (and almost rhythmic) voice was actually common in media of that era. For example, here's the [final scene from Casablanca](https://www.youtube.com/watch?v=5kiNJcDG4E0) in 1942. By modern standards, it sounds like a lot of bursts of rapid-fire dialog, interspersed by pauses for you to mentally catch your breath and process what you just heard. Dialog bits from [Dragnet](https://www.youtube.com/watch?v=sHmw2RgznSo&t=4m50s) are also famous for this, particularly when interrogating suspects.
Another thing one may notice is that women are typically portrayed speaking much slower (as are the aforementioned Dragnet interrogation subjects). This is a big clue. Dialog speed was used as a marker for dispassionate intelligence. People talking slower and lower were indicating that they were being more emotional and/or not thinking clearly.
A great illustration of this is this other [classic Cassablanca scene](https://www.youtube.com/watch?v=1_a57ZNlU6o). Look away from the screen, and pay attention to how fast and low the actors (particularly Ingrid Bergman) speak depending on who they are speaking to and how emotional they are about what they are saying (or how emotional they are *trying* to be). For instance, whenever anyone is talking about the sentimental song, their voice gets lower and slower. In contrast, when her husband and the Chief show up, both Bergman and Bogart start talking much quicker and higher.
To the best of my knowledge, the only person who has looked at this effect from a historical perspective is Maria DiBattista in her book [Fast Talking Dames](http://rads.stackoverflow.com/amzn/click/0300099037). "Fast Talking" in this context is explained to be an indicator of intelligence and power.
As for the unusual accent you are hearing, CGCambell in the comments pointed out that this would have been the ["Transatlantic" accent](https://en.wikipedia.org/wiki/Mid-Atlantic_accent). It was common among the upper class in New York around the turn of the 20th century. Since those were the people who patronized the theater, it was common there as well. When the first media companies started up in New York, they tended to pick it up, as it was a much more "prestigious" accent than the other locally-available alternatives. This was the accent of the late George Plimpton and William F. Buckley Jr.
It started to wane after the movie companies moved out to California and much of television production followed. Today most of the accents you hear in American media are a kind of homogenized [American Midlands](https://en.wikipedia.org/wiki/Midland_American_English) (which many Americans consider "no accent"), with a smattering of weak [AAVE](https://en.wikipedia.org/wiki/African_American_Vernacular_English) used to indicate someone from a rougher background.
|
22,953,730 |
I want to put an capital E infront of every string.
It is important that I use sed.
Such that
```
(260,'\"$40 a Day\"',2002,'Color','USA','','2000100002',131,6.1,'2002-04-24')
```
becomes
```
(260,E'\"$40 a Day\"',2002,E'Color',E'USA',E'',E'2000100002',131,6.1,E'2002-04-24')
```
I have tried
```
sed "s/'.*'/E&/g"
```
but it only puts an E infront of the first string!
Regards Kim
|
2014/04/09
|
[
"https://Stackoverflow.com/questions/22953730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1818419/"
] |
You misunderstand what that cascade means. It only applies to the foreign key column(s), not the whole record. If you change the value in the PK field in the parent record then the new value will cascade to the FK field in the child record(s). No other fields are affected.
That begs the question, why do you have data duplicated in the first place? If you have the name stored in the parent record then why do you have it in the child record as well? It should only be in one or the other. If you need data from both tables then you perform a join.
|
7,414,303 |
As the title, the code itself as following
```
internal static class ThumbnailPresentationLogic
{
public static string GetThumbnailUrl(List<Image> images)
{
if (images == null || images.FirstOrDefault() == null)
{
return ImageRetrievalConfiguration.MiniDefaultImageFullUrl;
}
Image latestImage = (from image in images
orderby image.CreatedDate descending
select image).First();
Uri fullUrl;
return
Uri.TryCreate(new Uri(ImageRetrievalConfiguration.GetConfig().ImageRepositoryName), latestImage.FileName,
out fullUrl)
? fullUrl.AbsoluteUri
: ImageRetrievalConfiguration.MiniDefaultImageFullUrl;
}
}
```
I don't want the unit test go through any methods in `ImageRetrievalConfiguration` class, so how can I mock `ImageRetrievalConfiguration` and pass it into `ThumbnailPresentationLogic` class ??
|
2011/09/14
|
[
"https://Stackoverflow.com/questions/7414303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877438/"
] |
How about you split the method into two - one of which takes a "base URI" and "default Url" and one of which doesn't:
```
internal static class ThumbnailPresentationLogic
{
public static string GetThumbnailUrl(List<Image> images)
{
return GetThumbnailUrl(images,
new Uri(ImageRetrievalConfiguration.GetConfig().ImageRepositoryName),
ImageRetrievalConfiguration.MiniDefaultImageFullUrl);
}
public static string GetThumbnailUrl(List<Image> images, Uri baseUri,
string defaultImageFullUrl)
{
if (images == null || images.FirstOrDefault() == null)
{
return defaultImageFullUrl;
}
Image latestImage = (from image in images
orderby image.CreatedDate descending
select image).First();
Uri fullUrl;
return
Uri.TryCreate(baseUri, latestImage.FileName, out fullUrl)
? fullUrl.AbsoluteUri
: defaultImageFullUrl;
}
}
```
Then you can test the logic in the "three-parameter" overload, but the public method doesn't really contain any logic. You won't get 100% coverage, but you'll be able to test the real *logic* involved.
|
61,567,981 |
```
MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
2020-05-02T19:00:36.477-0500 E QUERY [js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:341:17
@(connect):2:6
2020-05-02T19:00:36.483-0500 F - [main] exception: connect failed
2020-05-02T19:00:36.483-0500 E - [main] exiting with code 1
```
That is the error that I am getting after running Mongo and this is the response that I get after running mongod
```
2020-05-02T19:00:34.303-0500 I CONTROL [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2020-05-02T19:00:34.309-0500 I CONTROL [initandlisten] MongoDB starting : pid=3964 port=27017 dbpath=/data/db 64-bit host=Mateos-MBP.attlocal.net
2020-05-02T19:00:34.309-0500 I CONTROL [initandlisten] db version v4.2.3
2020-05-02T19:00:34.309-0500 I CONTROL [initandlisten] git version: 6874650b362138df74be53d366bbefc321ea32d4
2020-05-02T19:00:34.309-0500 I CONTROL [initandlisten] allocator: system
2020-05-02T19:00:34.309-0500 I CONTROL [initandlisten] modules: none
2020-05-02T19:00:34.309-0500 I CONTROL [initandlisten] build environment:
2020-05-02T19:00:34.309-0500 I CONTROL [initandlisten] distarch: x86_64
2020-05-02T19:00:34.309-0500 I CONTROL [initandlisten] target_arch: x86_64
2020-05-02T19:00:34.309-0500 I CONTROL [initandlisten] options: {}
2020-05-02T19:00:34.310-0500 I STORAGE [initandlisten] exception in initAndListen: NonExistentPath: Data directory /data/db not found., terminating
2020-05-02T19:00:34.310-0500 I NETWORK [initandlisten] shutdown: going to close listening sockets...
2020-05-02T19:00:34.313-0500 I - [initandlisten] Stopping further Flow Control ticket acquisitions.
2020-05-02T19:00:34.313-0500 I CONTROL [initandlisten] now exiting
2020-05-02T19:00:34.313-0500 I CONTROL [initandlisten] shutting down with code:100
```
I have looked at multiple other questions and still can't seem to figure it out any help would be appreciated.
|
2020/05/03
|
[
"https://Stackoverflow.com/questions/61567981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12802757/"
] |
Create a directory /data/db and give permission to the MongoDB user so that MongoDB can access it. To create the directory:
```
sudo mkdir -p /data/db
```
To change owner:
```
sudo chown -R $USER /data/db
```
|
4,429,853 |
I have homework which is about CFGs, their simplification, and their normalized forms. I have also seen some examples on the internet, but unfortunately, I could not solve the below question.
>
> All the binary numbers, in which the $i$th character is equal to the
> character which is located in $i + 2$ th position, and the length of
> these strings is at least $2$.
>
>
>
My problem is with positions, and how to show them using our grammar.
My idea was to have $S$ as our initial state, and then have a production like this:
$S\Rightarrow A|B$
------------------
And then $A$ be for all the strings which start by $0$, and $B$ be for all the strings which start by $1$.
But I will be really grateful for your help.
|
2022/04/17
|
[
"https://math.stackexchange.com/questions/4429853",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1003105/"
] |
The subsequence $\left((-1)^{2n}\frac{2n}{2n+1}\right)\_{n\in\Bbb N}$ of the sequence$$\left((-1)^n\frac n{n+1}\right)\_{n\in\Bbb N}\tag1$$ is the sequence $\left(\frac{2n}{2n+1}\right)\_{n\in\Bbb N}$ whose limit is $1$. Since the sequence $(1)$ has a subsequence which converges to a number different from $0$, it does not converge to $0$, and therefore your series diverges.
|
188,013 |
By an algebraic number field, we mean a finite extension field of the field of rational numbers.
Let $k$ be an algebraic number field, we denote by $\mathcal{O}\_k$ the ring of algebraic integers in $k$.
Let $K$ be a finite extension field of an algebraic number field $k$.
Suppose for every ideal $I$ of $\mathcal{O}\_k$, $I\mathcal{O}\_K$ is principal.
Then $K$ is called a PIT(Principal Ideal Theorem) field over $k$.
Let $K$ be a PIT field over $k$.
We say $K$ is a minimal PIT field over $k$ if $L/k$ is not PIT
for every proper subextension $L/k$ of $K/k$.
(1) Let $k$ be an algebraic number field and $K/k$ be a finite extension.
Is $K/k$ a minimal PIT if and only if $K/k$ is the Hilbert class field?
(2) Let $K/k$ and $L/k$ be minimal PITs.
Are $K/k$ and $L/k$ isomorphic?
|
2014/11/25
|
[
"https://mathoverflow.net/questions/188013",
"https://mathoverflow.net",
"https://mathoverflow.net/users/37646/"
] |
The answer to your first question is "no". In general, if $K/k$ is a cyclic unramified Galois extension of odd order, then the order of the capitulation kernel (the subgroup of the class group of $k$ that dies when base-changing to $K$), is $[K:k]\cdot [\mathcal{O}\_k^\times: N\_{K/k}\mathcal{O}\_K^\times]$. The second factor is the index in the integral units of $k$ of the subgroup generated by norms of units of $K$, and it can be non-trivial. See [Iwasawa, A Note on Capitulation Problem for Number Fields](http://projecteuclid.org/download/pdf_1/euclid.pja/1195513002) for a concrete example of a field $k$ whose class group capitulates in a proper subfield of the Hilbert class field, using the above observation.
|
4,241,980 |
In Python there is `iter()` used like this:
```
>>> a=[1,2,4]
>>> b=iter(a)
>>> b.next()
1
>>> b.next()
2
>>> b.next()
4
>>> b.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
```
Does Ruby have the same feature?
I tried this but it seems there is an issue:
```
ruby-1.9.2-p0 > a=[1,2,3]
=> [1, 2, 3]
ruby-1.9.2-p0 > def b()
ruby-1.9.2-p0 ?> for i in a
ruby-1.9.2-p0 ?> yield i
ruby-1.9.2-p0 ?> end
ruby-1.9.2-p0 ?> end
=> nil
ruby-1.9.2-p0 > b
NameError: undefined local variable or method `a' for #<Object:0xb7878950>
```
Why didn't Ruby find the `a` variable?
|
2010/11/22
|
[
"https://Stackoverflow.com/questions/4241980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446929/"
] |
Ruby has iterators also.
The basic use is:
```
>> iter = [0,1,2,3].each #=> #<Enumerator: [0, 1, 2, 3]:each>
>> iter.next #=> 0
>> iter.next #=> 1
>> iter.next #=> 2
>> iter.next #=> 3
>> iter.next
StopIteration: iteration reached an end
from (irb):6:in `next'
from (irb):6
from /Users/greg/.rvm/rubies/ruby-1.9.2-p0/bin/irb:16:in `<main>'
>>
```
You can use that in a method:
```
def iter(ary)
ary.each do |i|
yield i
end
end
iter([1,2,3]) { |i| puts i}
# >> 1
# >> 2
# >> 3
```
Your Ruby code is failing because `a` is not in scope, in other words, Ruby doesn't see `a` inside the `b` method. The typical way it would be defined is as I show it above. So, your code is close.
Also, note that we seldom write a for/loop in Ruby. There are reasons such as `for` loops leaving a local variable behind after running, and potential for running off the end of an array if the loop isn't defined correctly, such as if you are creating an index to access individual elements of an array. Instead we use the `.each` iterator to return each element in turn, making it impossible to go off the end, and not leaving a local variable behind.
|
22,661,767 |
I am attempting to write C functions with these two prototypes:
```
int extract_little (char* str, int ofset, int n);
int extract_big(char* str, int ofset, int n);
```
Now the general idea is I need to return a n byte integer in both formats starting from address str + ofset. P.S. Ofset doesn't do anything yet, I plan on (trying) to shuffle the memory via an offset once I figure out the little endian, for the big.
I'v trying to get it to output like this; for little endian, based off of `i=0xf261a3bf;`,
0xbf 0xa3 0x61 0xf2
```
int main()
{
int i = 0xf261a3bf;
int ofset = 1; // This isn't actually doing anything yet
int z;
for (z = 0; z < sizeof(i); z++){
printf("%x\n",extract_little((char *)&i,ofset, sizeof(i)));
}
return 0;
}
int extract_little(char *str,int offs, int n) {
int x;
for (x = 0; x < n; x++){
return str[x];
}
}
```
I'm not sure what else to try. I figured out the hard way that even thought I put it in a for loop I still can't return more than 1 value from the return.
Thanks!
|
2014/03/26
|
[
"https://Stackoverflow.com/questions/22661767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3464245/"
] |
It is possible to recover the data:
```
In [41]: a = {'0': {'A': array([1,2,3]), 'B': array([4,5,6])}}
In [42]: np.savez('/tmp/model.npz', **a)
In [43]: a = np.load('/tmp/model.npz')
```
Notice that the dtype is 'object'.
```
In [44]: a['0']
Out[44]: array({'A': array([1, 2, 3]), 'B': array([4, 5, 6])}, dtype=object)
```
And there is only one item in the array. That item is a Python dict!
```
In [45]: a['0'].size
Out[45]: 1
```
You can retrieve the value using the `item()` method (NB: this is *not* the
`items()` method for dictionaries, nor anything intrinsic to the `NpzFile`
class, but is the [`numpy.ndarray.item()` method](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ndarray.item.html)
that copies the value in the array to a standard [Python scalars](http://docs.scipy.org/doc/numpy-1.10.1/user/basics.types.html#array-scalars). In an array of `object` dtype any value held in a cell of the array (even a dictionary) is a Python scalar:
```
In [46]: a['0'].item()
Out[46]: {'A': array([1, 2, 3]), 'B': array([4, 5, 6])}
In [47]: a['0'].item()['A']
Out[47]: array([1, 2, 3])
In [48]: a['0'].item()['B']
Out[48]: array([4, 5, 6])
```
---
To restore `a` as a dict of dicts:
```
In [84]: a = np.load('/tmp/model.npz')
In [85]: a = {key:a[key].item() for key in a}
In [86]: a['0']['A']
Out[86]: array([1, 2, 3])
```
|
70,443,180 |
I am having an error with my dart code, which I tried using "?" but still it didn't work.
I am seeing this error message "Non-nullable instance field '\_bmi' must be initialized flutter"
```
import 'dart:math';
class CalculatorBrain {
final height;
final weight;
double _bmi;
CalculatorBrain({
this.height,
this.weight,
});
String calculateBMI() {
_bmi = weight / pow(height / 100, 2);
return _bmi.toStringAsFixed(1);
}
String getResult() {
if (_bmi >= 25) {
return 'overweight';
} else if (_bmi > 18.5) {
return 'Normal';
} else {
return 'underweight';
}
}
String interpretation() {
if (_bmi >= 25) {
return 'you have a higher than normal body weight. try to exercise more';
} else if (_bmi > 18.5) {
return 'you have a normal body weight';
} else {
return 'you have a normal body weight you can eat a little bit more';
}
}
}
```
How do I fix this?
|
2021/12/22
|
[
"https://Stackoverflow.com/questions/70443180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17712351/"
] |
Oh, I found @Peter Cordes 's comment and I combined with my initial answer:
<https://gcc.godbolt.org/z/bxzsfxPGx>
and `-fopt-info-vec-missed` doesn't say anything to me
```
void f(const unsigned char *input, const unsigned size, unsigned char *output) {
constexpr unsigned MAX_SIZE = 2000;
unsigned char odd[MAX_SIZE / 2];
unsigned char even[MAX_SIZE / 2];
for (unsigned i = 0, j = 0; size > i; i += 2, ++j) {
even[j] = input[i];
odd[j] = input[i + 1];
}
for (unsigned i = 0; size / 2 > i; ++i) {
output[i] = (even[i] << 4) | odd[i];
}
}
```
|
36,815,928 |
I was wondering why the result of the following code is 0 and not 3.
```
var fn = function(){
for (i = 0; i < 3; i++){
return function(){
console.log(i);
};
}
}();
fn();
```
|
2016/04/23
|
[
"https://Stackoverflow.com/questions/36815928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3654400/"
] |
You should do this **properly**:
* define your parameters **once** outside the loop
* define the **values** of your parameters inside the loop for each iteration
* use `using(...) { ... }` blocks to get rid of the `try ... catch ... finally` (the `using` block will ensure proper and speedy disposal of your classes, when no longer needed)
* stop using a `try...catch` if you're not actually *handling* the exceptions - just rethrowing them (makes no sense)
Try this code:
```
public static void featuresentry()
{
string connectionString = HandVeinPattern.Properties.Settings.Default.HandVeinPatternConnectionString;
string insertQuery = "INSERT INTO FEATURES(UserID, Angle, ClassID, Octave, PointX, PointY, Response, Size) VALUES(@UserID, @Angle, @ClassID, @Octave, @PointX, @PointY, @Response, @Size)";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(insertQuery, connection))
{
// define your parameters ONCE outside the loop, and use EXPLICIT typing
command.Parameters.Add("@UserID", SqlDbType.Int);
command.Parameters.Add("@Angle", SqlDbType.Double);
command.Parameters.Add("@ClassID", SqlDbType.Double);
command.Parameters.Add("@Octave", SqlDbType.Double);
command.Parameters.Add("@PointX", SqlDbType.Double);
command.Parameters.Add("@PointY", SqlDbType.Double);
command.Parameters.Add("@Response", SqlDbType.Double);
command.Parameters.Add("@Size", SqlDbType.Double);
connection.Open();
for (int i = 0; i < Details.modelKeyPoints.Size; i++)
{
// now just SET the values
command.Parameters["@UserID"].Value = Details.ID;
command.Parameters["@Angle"].Value = Convert.ToDouble(Details.modelKeyPoints[i].Angle);
command.Parameters["@ClassID"].Value = Convert.ToDouble(Details.modelKeyPoints[i].ClassId);
command.Parameters["@Octave"].Value = Convert.ToDouble(Details.modelKeyPoints[i].Octave);
command.Parameters["@PointX"].Value = Convert.ToDouble(Details.modelKeyPoints[i].Point.X);
command.Parameters["@PointY"].Value = Convert.ToDouble(Details.modelKeyPoints[i].Point.Y);
command.Parameters["@Response"].Value = Convert.ToDouble(Details.modelKeyPoints[i].Response);
command.Parameters["@Size"].Value = Convert.ToDouble(Details.modelKeyPoints[i].Size);
command.ExecuteNonQuery();
}
}
}
```
|
44,447,194 |
I'm very new to all of this, so please tell me anything I'm doing wrong!
I wrote a little bot for Discord using Node.js.
I also signed up for the free trial of Google Cloud Platform wth $300 of credit and all that. After creating a project, I started the cloud shell and ran my Node.js Discord bot using:
```
node my_app_here.js
```
The cloud shell is running and the bot is working correctly. Will the cloud shell run indefinitely and keep my bot running? It seems hard to believe that Google would host my bot for free. I have billing disabled on the project, but I'm afraid of getting hit with a huge bill.
Thanks for any help or recommendations!
|
2017/06/08
|
[
"https://Stackoverflow.com/questions/44447194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8134123/"
] |
It is free but intended for interactive usage. I guess you could get away with using it for other purposes but it would probably be a hassle. If you want to go free you could consider if what you try to do would fit into the free tier on [google app engine standard environment](https://cloud.google.com/products/calculator/#).
>
> Cloud Shell is intended for interactive use only. Non-interactive
> sessions will be ended automatically after a warning. Prolonged usage
> or computational or network intensive processes are not supported and
> may result in session termination without a warning.
>
>
>
[Documentation](https://cloud.google.com/shell/docs/limitations#usage_limits)
|
6,195,404 |
I'm trying to create a hangman program that uses file io/ file input. I want the user to choose a category (file) which contains 4 lines; each has one word. The program will then read the line and convert it into `_`s , this is what the user will see.
Where would I insert this -->
{
lineCount++;
output.println (lineCount + " " + line);
line = input.readLine ();
}
/\*
* Hangman.java
* The program asks the user to choose a file that is provided.
* The program will read one line from the file and the player will guess the word.
* and then outputs the line, the word will appear using "\_".
* The player will guess letters within the word or guess entire word,
* if the player guesses correctly the "\_" will replaced with the letter guessed.
* But, if the player guesses incorrectly the a part of the stickman's body will be added,
* then the user will be asked to guess again. The user can also enter "!" to guess the entire word,
* if the guess correctly they win, but if they guess incorrectly they will be asked to guess again.
* Once it has finished reading the file, the program outputs the number of guesses.
\*/
import java.awt.\*;
import hsa.Console;
//class name
public class Hangman
{
static Console c;
public static void main (String [] args)
{
c = new Console ();
```
PrintWriter output;
String fileName;
```
//ask user to choose file; file contains words for user to guess
c.println ("The categories are: cartoons.txt, animals.txt, and food.txt. Which category would you like to choose?");
```
fileName = c.readLine ();
// E:\\ICS\\ICS 3U1\\Assignments\\JavaFiles\\+fileName
```
try {
```
/* Sets up a file reader to read the file passed on the command
line one character at a time */
FileReader input = new FileReader(args[0]);
/* Filter FileReader through a Buffered read to read a line at a
time */
BufferedReader bufRead = new BufferedReader(input);
String line; // String that holds current file line
int count = 0; // Line number of count
// Read first line
line = bufRead.readLine();
count++;
// Read through file one line at time. Print line # and line
while (line != null){
c.println(count+": "+line);
line = bufRead.readLine ();
count++;
}
bufRead.close();
}
catch (FileNotFoundException e)
{
c.println("File does not exist or could not be found.");
c.println("FileNotFoundException: " + e.getMessage());
}
catch (IOException e)
{
c.println("Problem reading file.");
c.println("IOException: " + e.getMessage());
}
```
|
2011/06/01
|
[
"https://Stackoverflow.com/questions/6195404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776107/"
] |
Take a step back and look at your code from a high level:
```
print "which file?"
filename = readline()
open(filename)
try {
print "which file?"
filename = readline()
open(filename)
create reader (not using the File object?)
create writer (not using the File object, but why a writer??)
while ...
```
It sure feels like you've sat down, coded 53 odd lines without testing *anything*, copy-and-pasted code around without understanding why you had it in the first place, and didn't understand what you were aiming for in the first place. (Sorry to be this blunt, but you did ask for advice and I'm not good at sugar coating.)
I suggest writing your program entirely by *hand* on a sheet of paper with a pencil first. You'll want it to look more like this:
```
while user still wants to play
ask for category
open file
read file contents into an array
close file
select array element at random
while user still has guesses left
print a _ for each character
ask user to guess a letter
if letter is in the word
replace the _ with the letter in the output
if the word is complete, success!
else
guesses left --
user ran out of guesses, give condolences
```
Once you've thought through all the cases, all the wins and losses, and so forth, then start coding. **Start small**. Get something to compile and run immediate, even if it is just the usual Java noise. Add a few lines, re-run, re-test. Never add more than four or five lines at a time. And don't hesitate to add plenty of `System.out.println(...)` calls to show you what your program internal state looks like.
As you get more experienced, you'll get better at recognizing the error messages, and maybe feel confident enough to add ten to twenty lines at a time. Don't rush to get there, though, it takes time.
|
29,330,708 |
Can anyone please tell me the reason that why we can't use **Console.WriteLine** in Class without Method. I am trying to do this but complier is putting a error. I know its wrong but just want to know the valid reason for that .
```
public class AssemblyOneClass2
{
Console.WriteLine("");
}
```
|
2015/03/29
|
[
"https://Stackoverflow.com/questions/29330708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2750155/"
] |
A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method.
Therefore must be written inside of a method. otherwise CLR don't know when it is supposed to execute that code. This is basic for C#.
|
104,648 |
Most people say that it is because the 3p orbital of chlorine when overlapping with the s orbital of hydrogen covers more area than when 4p orbital of bromine overlaps with the s orbital of hydrogen which makes bond between H and Cl more stronger than the bond between H and Br. But how can we say that the area of overlapping is more for 3p and s orbital compared to overlapping of 4p and s orbital?
|
2018/11/21
|
[
"https://chemistry.stackexchange.com/questions/104648",
"https://chemistry.stackexchange.com",
"https://chemistry.stackexchange.com/users/70394/"
] |
You can think of the overlapping volume between the electron clouds, but a simpler form to show why this happens is when you consider the electrical potential between the atoms. Even tough this isn't an ionic compound, it has many characteristics that are similar.
If I remember correctly, this is the expression for the potential energy between charged particles: $E\_p = k\frac{Q\_1 \cdot Q\_2}{d}$
Since the radius of $\ce{Br}$ is greater than the radius of $\ce{Cl}$, the potential energy involved in $\ce{H-Br}$ bond will be smaller than $\ce{H-Cl}$ bond.
Another thing that came to my mind, and I'm not sure, is that as the 4p cloud of $\ce{Br}$ is bigger than that of $\ce{Cl}$, the relative amount of the volume that is overlapped with the 1s cloud of $\ce{H}$ gets smaller with $\ce{Br}$ than with $\ce{Cl}$, which means the connection is weaker.
|
13,351,653 |
I get the following error
```
No route matches [POST] "/events"
```
with this setup:
### config/routes.rb
```
namespace :admin do
#...
resources :events
#...
end
```
---
### (...)admin/events\_controller.rb
```
class Admin::EventsController < Admin::AdminController
def index
@events = Event.all
end
def new
@event = Event.new
end
def create
@event = Event.new(params[:event])
if @event.save
redirect_to [:admin, admin_events_url]
else
render :action => "new"
end
end
def edit
@event = Event.find(params[:id])
end
end
```
---
### (...)admin/events/\_form.html.erb
```
<%= form_for([:admin, @event]) do |f| %>
```
---
I can't figure out what I am doing wrong!
Update
------
I get this error when I try to POST the from data while creating a new event entry
---
Update 2
--------
The opening form tag inside `events/new`:
```
<form accept-charset="UTF-8" action="/admin/events" enctype="multipart/form-data" id="new_event" method="post">
```
the result of `rake routes`:
```
admin_events GET /admin/events(.:format) admin/events#index
POST /admin/events(.:format) admin/events#create
```
Navigating to `/admin/events/` using `GET` works just fine.
---
Update 3
--------
It works fine on Windows 8 x64 bit with Ruby 1.9.3, Rails 3.2 and Mongrel. It *doesn't* work with Ruby 1.8.7, Rails 3.2 and Phusion Passenger on a linux server (the host).
Update 4
========
Oh. It appears Rails isn't very happy if you send it a form with `multipart/form-data` encoding! Removing the file-upload fixed this issue.
|
2012/11/12
|
[
"https://Stackoverflow.com/questions/13351653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2133758/"
] |
For what it's worth the only thing that looks fishy to me about your controller is your redirect. You should be able to just do:
```
redirect_to admin_events_path
```
|
31,157,803 |
I am working on spring web app using maven. I am trying to make localhost a secure connection.I am using tomcat server. I used this [link](http://docs.oracle.com/cd/E19798-01/821-1841/bnbyb/index.html) for creating my own CA and added it to JVM.
This is what I added in pom.xml.
```
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/security</path>
<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol" SSLEnabled="true" maxThreads="200" scheme="https" secure="true" keystoreFile="/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.71.x86_64/jre/lib/security/cacerts.jks" keystorePass="security"
clientAuth="false" sslProtocol="TLS" />
</configuration>
</plugin>
```
I went to the link:<https://localhost:8443> . But no app is running on that port. Could someone please help?
|
2015/07/01
|
[
"https://Stackoverflow.com/questions/31157803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2213010/"
] |
Go to sever.xml and add following xml
```
<Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" keystoreFile="{path}/mycer.cert" keystorePass="{password}"/>
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>
```
1. first you want to create one CA certificate
2. you can use java key tool for certificate creation
3. store that certificate on your server .
4. add connector config with in your tomcat server.xml
5. you should provide certificate path and password that given
6. restart server
if any problem for restarting comment stack trace
<http://www.mkyong.com/tomcat/how-to-configure-tomcat-to-support-ssl-or-https/>
|
26,957,743 |
Suppose one has a java project which consists of several packages, subpackages etc, all existing in a folder "source". Is there a direct way to copy the structure of the folders in "source" to a "classes" folder and then recursively compile all the .java files, placing the .class files in the correct locations in "classes"?
|
2014/11/16
|
[
"https://Stackoverflow.com/questions/26957743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1333200/"
] |
For larger projects a recommend using a build tool like [Maven](http://maven.apache.org) or the newer and faster [Gradle](http://gradle.org). Once you've configured one of them for your needs, it's very easy to do the job by calling `mvn build` or `gradle build`.
If these tools seem to heavy for your purpose, you may have a look at [Ant](http://ant.apache.org). A simple ant example:
```
<project default="compile">
<target name="compile">
<mkdir dir="bin"/>
<javac srcdir="source" destdir="bin"/>
</target>
</project>
```
and then run `ant` from the command line. See [this thread for further information](https://stackoverflow.com/questions/6623161/javac-option-to-compile-recursively).
|
37,686,247 |
I'm trying to convert the following curl post to a Python request:
```
curl -k -i -H "Content-Type: multipart/mixed" -X POST --form
'session.id=e7a29776-5783-49d7-afa0-b0e688096b5e' --form 'ajax=upload'
--form '[email protected];type=application/zip' --form 'project=MyProject;type/plain' https://localhost:8443/manager
```
I used [curl.trillworks.com](http://curl.trillworks.com) to make an auto conversion but it didn't work. I also tried the following:
```
sessionID = e7a29776-5783-49d7-afa0-b0e688096b5e
project = 'file.zip'
metadata = json.dumps({"documentType":"multipart/mixed"})
files = {
'meta' : ('', metadata , 'application/zip'),
'data':(project, 'multipart/mixed', 'application/octet-stream')}
data = {'ajax':'upload','project':'test','session.id':sessionId}
cookie = {'azkaban.browser.session.id':sessionId}
response=requests.post('https://'+azkabanURL+'/manager',
data=data,verify=False,files=files)
print response.text
```
I got the following error:
```
<p>Problem accessing /manager. Reason:
<pre> INTERNAL_SERVER_ERROR</pre></p><h3>Caused by:</h3><pre>java.lang.NullPointerException
at azkaban.webapp.servlet.ProjectManagerServlet.ajaxHandleUpload(ProjectManagerServlet.java:1664)
at azkaban.webapp.servlet.ProjectManagerServlet.handleMultiformPost(ProjectManagerServlet.java:183)
at azkaban.webapp.servlet.LoginAbstractAzkabanServlet.doPost(LoginAbstractAzkabanServlet.java:276)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:401)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:945)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)
at org.mortbay.jetty.security.SslSocketConnector$SslConnection.run(SslSocketConnector.java:713)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
```
Can't figure out what I'm missing here??
|
2016/06/07
|
[
"https://Stackoverflow.com/questions/37686247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1762447/"
] |
I found the answer after trying out some of the examples from [requests](http://docs.python-requests.org/en/master/user/quickstart/#make-a-request) site and finally it worked.
```
data = {'ajax':'upload','project':'test','session.id':sessionId}
files = {'file':('projects.zip',open('projects.zip','rb'),'application/zip')}
response=requests.post('https://'+azkabanURL+'/manager',data=data,verify=False,files=files)
print response.text
print response.status_code
```
|
66,628 |
My employer offers an ESPP with the following details:
* 15% discount
* Max contribution is 15% of base salary
* Purchase transaction occurs on the last business day of the month
* Transaction settles 3 days after purchase
* No obligation to hold the stock for minimum duration
* No restrictions on sell timing (except during earnings lock-out period)
* Brokerage fees
+ $0.05 per share sold (approximately 0.08% of the stock price today)
+ $0 per share bought
Given these parameters...
What is the safest way to play the ESPP?
What is (likely) the most lucrative way to play the ESPP?
Assume I contribute the maximum amount allowable.
Assume I can hold the stock for up to you year before I may need to cash it out.
|
2016/06/26
|
[
"https://money.stackexchange.com/questions/66628",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/22298/"
] |
A 15% discount is a 17.6% return. (100/85 = 1.176). For a holding period that's an average 15.5 days, a half month. It would be silly to compound this over a year as the numbers are limited.
The safest way to do this is to sell the day you are permitted. In effect, you are betting, 12 times a year, that the stock won't drop 15% in 3 days. You can pull data going back decades, or as long as your company has been public, and run a spreadsheet to see how many times, if at all, the stock has seen this kind of volatility over 3 day periods. Even for volatile stocks, a 15% move is pretty large, you're likely to find your stock doing this less than once per year. It's also safest to not accumulate too many shares of your company for multiple reasons, having to do with risk spreading, diversification, etc.
2 additional points -
the Brexit just caused the S&P to drop 4% over the last 3 days trading. This was a major world event, but, on average we are down 4%. One would have to be very unlucky to have their stock drop 15% over the specific 3 days we are discussing.
The dollars at risk are minimal. Say you make $120K/yr. $10K/month. 15% of this is $1500 and you are buying $1765 worth of stock. The gains, on average are expected to be $265/mo. Doesn't seem like too much, but it's $3180 over a years' time. $3180 in profit for a maximum $1500 at risk at any month's cycle.
|
11,324 |
I need to annotate a text file, so I would like to add a `|` pipe character to the end of each line to put my annotations relatively close to the original text. Each line is *up to* 72 characters in length. How might I move to the 74th character of the line, even if the line itself is shorter (i.e. add spaces if needed)?
My current solution is to simply add 72 spaces to the line, then to move to position 74 and delete the remaining spaces. Is there not a more elegant method in VIM?
My current (inelegant) macro:
```
qq$74a<space><esc>74|i|<esc>lDjq
```
I'm currently using VIM 8.0.133 on CentOS 7.3.
|
2017/02/09
|
[
"https://vi.stackexchange.com/questions/11324",
"https://vi.stackexchange.com",
"https://vi.stackexchange.com/users/989/"
] |
You could also enable `'virtualedit'` option and directly jump to the column you're interested in.
A very similar question as been asked lately on SO: <https://stackoverflow.com/questions/41964261/how-do-i-put-the-character-in-6th-column-and-80th-column-in-vi/41964372#41964372>
|
105,982 |
My barbarian will be level 3 soon, and I'm looking forward to choosing the Path of the Totem Warrior.
|
2017/08/26
|
[
"https://rpg.stackexchange.com/questions/105982",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/34635/"
] |
The most thematically appropriate option would be for your Barbarian to hunt the relevant animal of your choice.
The PHB of 50 states
>
> ...
>
>
> You must make or acquire a physical totem object -an amulet or similar adornment—that incorporates fur or feathers, claws, teeth, or bones of the totem animal.
>
>
> ...
>
>
>
Your choice of totem animal is Bear, Eagle or Wolf.
In order to facilitate this I would speak to your DM and set out what type of totem you wish to get, and ask if they could facilitate a hunt scenario for this particular animal into your campaign.
|
16,368,230 |
I am looking at the Webapi Help Page to generated docmentation but all the tutorials I see leave me wondering.
Q1.
How do I populate the sample data myself? From my understanding it looks at the data type and makes some data based on the datatype. Some of my data has specific requirements(ie length can't be more than 5 characters).
How do I write my own sample data for each method?
Q2
How can I hide warning messages.
I get this message
>
> Failed to generate the sample for media type
> 'application/x-www-form-urlencoded'. Cannot use formatter
> 'JQueryMvcFormUrlEncodedFormatter' to write type 'ProductDM'.
>
>
>
I am not really sure what "x-www-form-urlencoded" is but say if I don't support that how can I just hide that message or say "not supported"?
Q3 How can I write a description for each parameter. In most cases it is clear what they are but in some cases maybe not. Also it would be nice if it automatically took the annotations and put that beside them as well to show that maybe parameter A is option while parameter B is not.
|
2013/05/03
|
[
"https://Stackoverflow.com/questions/16368230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130015/"
] |
Q1: Have you taken a look at "Areas\HelpPage\App\_Start\HelpPageConfig.cs" file. You should see a bunch of commented out with examples how you could define your own samples.
Example:
```
public static class HelpPageConfig
{
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
```
Q2: You are seeing the error for "application/x-www-form-urlencoded" mediatype because the formatter which we use for it can only deserialize or read the data and cannot write. Here the error is to indicate that it only cannot write the sample, but if you infact are sending data in this media type, it could be deserialized correctly. Instead of hiding this section, you could provide an explicit sample for this media type. The HelpPageConfig.cs has examples for this:
```
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
```
Q3: For documentation about parameters of an action, you can always use the regular comments(summary, param etc) and generate the documentation file and point it like the following:
```
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
```
We currently do not have support for generating documentation out of Data Annotations, we currently have an issue tracing it: <http://aspnetwebstack.codeplex.com/workitem/877>
|
17,298,631 |
In an effort to learn C programming, I'm attempting to translate some Lua Code into C. I know C is not considered a "functional" language in the same vein as Lua, but I want to know how/if it's possible.
Lua Code:
```
function Increment(a)
a = a + 1
if a == 100 then return 0
else return Increment(a) end end
```
In this code, Lua cleverly exits the function after calling it again to avoid creating a huge stack of nested functions.
Is there a method for this sort of recursion in C that exits a function before calling it again, to avoid forming a large group of nested functions?
I understand functions can be used in this way to avoid side effects; How can I write this in C to avoid them as well?
|
2013/06/25
|
[
"https://Stackoverflow.com/questions/17298631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2395058/"
] |
Try this code if you want a global, but there is side effect :
```
int a;
int increment()
{
a = a + 1;
if (a == 100)
return 0;
else
return increment();
}
```
Prefer to use if you don't want side effect, and this solution DO NOT stack lot of function, because you call your function at the last statement.
```
int increment(int a)
{
if (a == 100)
return a;
else
return increment(a + 1);
}
```
For example this one create stack of function :
```
int increment(int a)
{
if (a == 100)
return a;
else
{
a = increment(a);
return (a + 1);
}
}
```
|
26,093,827 |
I need to find a value wherever present in database.
Consider I need to find value "Fish" from Database.
Output I need is
```
Table Name | Column Name
--------------------------
Table 1 | columnName
Table 12 | columnName
```
and so on..
|
2014/09/29
|
[
"https://Stackoverflow.com/questions/26093827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3540786/"
] |
First, download the source version of Thrift. I would strongly recommend using a newer version if possible. There are several ways to include the Thrift Java library (may have to change slightly for your Thrift version):
If you are using maven, you can add the maven coordinates to your pom.xml:
```
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.9.1</version>
</dependency>
```
Alternatively you can just download the JAR and add it your project:
<http://central.maven.org/maven2/org/apache/thrift/libthrift/0.9.1/libthrift-0.9.1.jar>
If you are using a version that has not been published to the central maven repositories, you can download the source tarball and navigate to the lib/java directory and build it with Apache Ant by typing:
```
ant
```
The library JAR will be in the lib/java/build directory. Optionally you can add the freshly built JAR to your local Maven repository:
```
mvn install:install-file -DartifactId=libthrift -DgroupId=org.apache.thrift -Dvers
```
For the PHP library, navigate to the `lib/php/src` directory and copy the PHP files into your project. You can then use the Thrift\ClassLoader\ThriftClassLoader class or the autoload.php script to include the Thrift PHP library. No build necessary unless you are trying to use the native PHP extension that implements the thrift protocol.
|
58,526,031 |
I would like to check myself whether I understand correctly the following quote below from the C++ 20 Standard (English is not my native language).
Section 9.7.1 Namespace definition:
>
> 2 In a named-namespace-definition, the identifier is the name of the
> namespace. If the identifier, when looked up (6.4.1), refers to a
> namespace-name (but not a namespace-alias) that was introduced in the
> namespace in which the named-namespace-definition appears or that was
> introduced in a member of the inline namespace set of that namespace,
> the namespace-definition extends the previously-declared namespace.
> Otherwise, the identifier is introduced as a namespace-name into the
> declarative region in which the named-namespacedefinition appears.
>
>
>
That is may a namespace be defined in a namespace and then extended in one of its inline namespace? Or vice versa. May a namespace be defined in an inline namespace and then be extended in its enclosing namespace?
Here is a demonstrative program.
```
#include <iostream>
inline namespace N1
{
inline namespace N2
{
namespace N3
{
void f( int ) { std::cout << "f( int )\n"; }
}
}
namespace N3
{
void f( char ) { std::cout << "f( char )\n"; }
}
}
int main()
{
N3::f( 10 );
N3::f( 'A' );
}
```
The program output is
```
f( int )
f( char )
```
However for this program the compiler issues an error saying that reference to 'N3' is ambiguous.
```
#include <iostream>
inline namespace N1
{
namespace N3
{
void f( int ) { std::cout << "f( int )\n"; }
}
inline namespace N2
{
namespace N3
{
void f( char ) { std::cout << "f( char )\n"; }
}
}
}
int main()
{
N3::f( 10 );
N3::f( 'A' );
}
```
|
2019/10/23
|
[
"https://Stackoverflow.com/questions/58526031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2877241/"
] |
There in no variable named `good` or `wrong` in your main module. However you passed them to this function:
```
selected_function.randomfunction(good, wrong)
```
|
21,355,784 |
I need to be able to rotate whole layouts on the fly (on the click of a button).
I am able to rotate the layouts using, eg. `layout.setRotation(270.0f)`. **The problem is, after the rotation, the layout `height` and `width` are not matching its parent's**.
I have tried inverting `height` and `width` like so,
```
RelativeLayout layout = (RelativeLayout)findViewById(R.id.rootLayout);
LayoutParams layoutParams = layout.getLayoutParams();
int height = layout.getHeight();
int width = layout.getWidth();
layoutParams.height = width;
layoutParams.width = height;
```
Which does nothing at all.
I am working with `sdk 14`.
The first image below is the app as it starts. The second one, after a rotation. I wish to fill the black "space". Any help would be appreciated.
The images below show only a button in the layout. However, in reality, the layout are a lot more complex. What I am trying to achieve is "faking" a landscape view.


**Edit:** Changed images and added descriptions.
|
2014/01/25
|
[
"https://Stackoverflow.com/questions/21355784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845253/"
] |
Not sure why this is useful, but it's a nice puzzle. Here is something that works for me:
On rotate click, do this:
```
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.main);
int w = mainLayout.getWidth();
int h = mainLayout.getHeight();
mainLayout.setRotation(270.0f);
mainLayout.setTranslationX((w - h) / 2);
mainLayout.setTranslationY((h - w) / 2);
ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) mainLayout.getLayoutParams();
lp.height = w;
lp.width = h;
mainLayout.requestLayout();
```
And the layout:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/main"
android:layout_height="match_parent"
android:background="#ffcc88"
tools:context=".TestRotateActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
/>
<Button
android:id="@+id/rotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rotate"
android:layout_centerInParent="true"
/>
</RelativeLayout>
```
|
42,087,917 |
When i search results, my data takes some time to show,So i want a progress bar should show after click on search button.It takes 5-8 second to show data.If i add below div after [div class="k-grid-content] div in inspect element then loading bar work well but not hide after data load.How can i add below code before data load and remove after load. Thanks !!
```
<div class="k-loading-mask" style="width: 100%; height: 100%; top: 0px; left: 0px;">
<span class="k-loading-text">Loading...</span>
<div class="k-loading-image"></div>
<div class="k-loading-color"></div>
</div>
```
|
2017/02/07
|
[
"https://Stackoverflow.com/questions/42087917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7218492/"
] |
If you are interested in Sql Server you can use something like this:
```
using System.Data;
using System.Data.Sql;
var instances = SqlDataSourceEnumerator.Instance.GetDataSources();
foreach (DataRow instance in instances.AsEnumerable())
{
Console.WriteLine($"ServerName: {instance["ServerName"]}; "+
" Instance: {instance["InstanceName"]}");
}
```
More information about the `SqlDataSourceEnumerator` class you can find on [MSDN](https://msdn.microsoft.com/en-us/library/system.data.sql.sqldatasourceenumerator(v=vs.110).aspx).
Note:
-----
This class will look into the local network for servers, if your network is large then there might be a delay in acquiring the response. Also for the empty string instance name, that should be the default instance for that SQL Server.
You can get this information using the SMO too, if you want.
|
55,879,345 |
```
var request: [String: Any] = [
"Token": "Token",
"Request": [
"CityID": "CityID",
"Filters": [
"IsRecommendedOnly": "0",
"IsShowRooms": "0"
]
]
]
//
print(request)
```
Console output:
```
["Token": "Token", "Request": ["CityID": "CityID", "Filters": ["IsRecommendedOnly": "0", "IsShowRooms": "0"]]]
```
Here I want to update value of **"IsShowRooms"** key from value **"0"** to value **"1"**, I was tried different steps but I am unable to do so, can anyone help me out in this?
|
2019/04/27
|
[
"https://Stackoverflow.com/questions/55879345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6511607/"
] |
You can get the value by typecasting Any to its type and store its value back
```
if var requestVal = request["Request"] as? [String: Any], var filters = requestVal["Filters"] as? [String: String] {
filters["IsShowRooms"] = "1"
requestVal["Filters"] = filters
request["Request"] = requestVal
}
```
Output
>
> ["Token": "Token", "Request": ["CityID": "CityID", "Filters": ["IsRecommendedOnly": "0", "IsShowRooms": "1"]]]
>
>
>
OR
Instead of storing values in Dictionary create a struct. It will be easier to update its properties
|
20,671 |
I have an apex test code,
That passes in the sandbox and gives an 89% code coverage for a specific code,
And the code and the test code are validated and deployed in production,
Without problems,
And the APEX code works in fine in production,
But when I try to run the test code in production it fails,
How is this possible?
I would like to add that the test code uses :seealldata=false,
And i looked at the APEX debug log file for my account after execution of the test,
The log file does not show any errors,
It just shows the step by step execution,
Which seems all fine,
|
2013/11/14
|
[
"https://salesforce.stackexchange.com/questions/20671",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/2780/"
] |
There are many reasons why tests fail after deployment to production. This can include additions or changes to validation rules, dependency on unique ID values that represent records that were later deleted, changes to a field's requiredness or uniqueness attributes, and other similar changes. In summation, you would have to actually read the debug logs from the tests to determine what change may have caused the failures.
|
10,414,489 |
I'm evaluating Knockout to use with JayData to create a standalone web application.
Following this tutorial (http://jaydata.org/tutorials/creating-a-stand-alone-web-application) it seems that I will be able to store my data on iPhone, Android and in HTML5 browsers...
I'm not sure how can I use JavaScript Query Language with Knockout. I've seen they will have some support it, but I probably you have an idea how can I do it myself.
I'm not sure if Knockout is the appropriate UI library for hybrid applications, hopefully you can share some know-how.
Thank you!
|
2012/05/02
|
[
"https://Stackoverflow.com/questions/10414489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
**UPDATE**:
From version 1.1.0 JayData has knockoutjs integration module. Include "jaydatamodules/knockout.js" in your html page, and have JayData provide Knockout observables with entity.asKoObservable(). With this module queryable.toArray() accepts ko.ObservableArrays as targets populating it with kendo observable entities.
Custom Bindings is just the way for the integration you are after. You have to connect the knockoutjs way of interacting with the JavaScript objects with the JayData entity metadata functions and its `propertyChanged / propertyChanging` events.
It shouldn't be difficult a task to do, as JayData supports simple property notation (`object.property`) and async property accessor pattern (get\_property(cb), set\_property(cb)) as well.
|
126,060 |
i wanted to remove "billing agreement" "recurring profile" "customer token" "My Downloadable Products" in account navigation.
Magento ver. 1.9.2.4
please help me .
|
2016/07/17
|
[
"https://magento.stackexchange.com/questions/126060",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/37698/"
] |
Billing Agreements :
copy this file
`app/design/frontend/base/default/layout/sales/billing_agreement.xml`
in your current theme and remove below lines
```
<reference name="customer_account_navigation" >
<action method="addLink" translate="label"><name>billing_agreements</name><path>sales/billing_agreement/</path><label>Billing Agreements</label></action>
</reference>
```
Recurring Profiles :
copy this file
`app/design/frontend/base/default/layout/sales/recurring_profile.xml`
in your current theme and remove below lines
```
<reference name="customer_account_navigation" >
<action method="addLink" translate="label"><name>recurring_profiles</name><path>sales/recurring_profile/</path><label>Recurring Profiles</label></action>
</reference>
```
My Downloadable Products :
copy this file
`app/design/frontend/base/default/layout/downloadable.xml`
in your current theme and remove below lines
```
<reference name="customer_account_navigation">
<action method="addLink" translate="label" module="downloadable"><name>downloadable_products</name><path>downloadable/customer/products</path><label>My Downloadable Products</label></action>
</reference>
```
|
4,523,604 |
I have a problem with fitting all my annotations to the screen... sometimes it shows all annotations, but some other times the app is zooming in between the two annotations so that none of them are visible...
I want the app to always fit the region to the annotations and not to zoom in between them... what do I do wrong?
```
if ([mapView.annotations count] == 2) {
CLLocationCoordinate2D SouthWest = location;
CLLocationCoordinate2D NorthEast = savedPosition;
NorthEast.latitude = MAX(NorthEast.latitude, savedPosition.latitude);
NorthEast.longitude = MAX(NorthEast.longitude, savedPosition.longitude);
SouthWest.latitude = MIN(SouthWest.latitude, location.latitude);
SouthWest.longitude = MIN(SouthWest.longitude, location.longitude);
CLLocation *locSouthWest = [[CLLocation alloc] initWithLatitude:SouthWest.latitude longitude:SouthWest.longitude];
CLLocation *locNorthEast = [[CLLocation alloc] initWithLatitude:NorthEast.latitude longitude:NorthEast.longitude];
CLLocationDistance meter = [locSouthWest distanceFromLocation:locNorthEast];
MKCoordinateRegion region;
region.span.latitudeDelta = meter / 111319.5;
region.span.longitudeDelta = 0.0;
region.center.latitude = (SouthWest.latitude + NorthEast.latitude) / 2.0;
region.center.longitude = (SouthWest.longitude + NorthEast.longitude) / 2.0;
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
[locSouthWest release];
[locNorthEast release];
}
```
Any ideas?
Thanks!!
|
2010/12/24
|
[
"https://Stackoverflow.com/questions/4523604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/543570/"
] |
Use the following code
```
-(void)zoomToFitMapAnnotations:(MKMapView*)mapView{
if([mapView.annotations count] == 0)
return;
CLLocationCoordinate2D topLeftCoord;
topLeftCoord.latitude = -90;
topLeftCoord.longitude = 180;
CLLocationCoordinate2D bottomRightCoord;
bottomRightCoord.latitude = 90;
bottomRightCoord.longitude = -180;
for(FSMapAnnotation* annotation in mapView.annotations)
{
topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
}
MKCoordinateRegion region;
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
}
```
|
14,565,365 |
As from the jquery api page
<http://api.jquery.com/jQuery.getScript/>
>
> Success Callback
> ----------------
>
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
> ```
> $.getScript("test.js", function() {
> foo();
> });
>
> ```
>
>
if the `foo()` function depend on test.js, it cannot be execute successfully.
I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback?
|
2013/01/28
|
[
"https://Stackoverflow.com/questions/14565365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018232/"
] |
I know it is an old question but i think both answers containing "done" are not explained by their owners and they are in fact the best answers.
The most up-voted answer calls for using "async:false" which will in turn create a sync call which is not optimal. on the other hand promises and promise handlers were introduced to jquery since version 1.5 (maybe earlier?) in this case we are trying to load a script asynchronously and wait for it to finish running.
The callback by definition [getScript documentation](https://api.jquery.com/jquery.getscript/)
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
what you need to look for instead is how promises act. In this case as you are looking for a script to load asynchronously you can use either "then" or "done"
have a look at [this thread](https://stackoverflow.com/questions/5436327/jquery-deferreds-and-promises-then-vs-done) which explains the difference nicely.
Basically done will be called only when a promise is resolved. in our case when the script was loaded successfully and finished running. So basically in your code it would mean:
```
$.getScript("test.js", function() {
foo();
});
```
should be changed to:
```
$.getScript("test.js").done(function(script, textStatus) {
console.log("finished loading and running test.js. with a status of" + textStatus);
});
```
|
42,756,655 |
I have this function that finds the preorder of a binary tree. I'm a bit unsure how I can edit this to store the traversal instead of printing it. I want to store it in an array possibly so I can compare it to another traversal, but creating an array within this function will be an issue since I implemented it recursively. Any ideas?
I was thinking of passing it an empty array, but how I can't seem to picture how I'd increment through the array due to the function being recursive.
```
void preorder(node *node)
{
if(node == NULL)
return;
printf("%d", node->data);
preorder(node->left);
preorder(node->right);
}
```
|
2017/03/13
|
[
"https://Stackoverflow.com/questions/42756655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7608519/"
] |
You are on the right track. Yes, pass in an array that is initially empty. Also pass an index initialized to 0 to keep track of how much of the array you have filled in. `*index` represents the next array index available for filling in data. You increment the index only when you fill data in the array. The recursive cases will be handled naturally. Each invocation of `inorder` will increment the index by 1.
```
void inorder(node *node, int *array, int *index)
{
if (node == NULL)
return;
inorder(node->left, array, index);
array[(*index)++] = node->data;
inorder(node->right, array, index);
}
```
|
62,707,612 |
I tried to create a login system, but the logic to load user is not working (the error is that it does't varify the password it only varify user if user exist then it will print ('login sucessfull') no matter what the password is can't able to find mistake)
```
class SaveUser:
user = {}
def inputUserInfo(self):
self.username = input('Create Username:')
self.email = input('Create Email:')
self.password = input('Create Password:')
def saveUser(self):
self.user[self.username] = self.password
print(self.user)
def askUserToLoad(self):
self.enterUsername = input('Enter Username:')
self.enterPassword = input('Enter password:')
if self.enterUsername in self.user and self.user[self.username] == self.password:
print('User Logged in Successfully')
else:
print('sorry user not found')
def runProgram(self):
self.inputUserInfo()
self.saveUser()
self.askUserToLoad()
run = SaveUser()
run.runProgram()
```
|
2020/07/03
|
[
"https://Stackoverflow.com/questions/62707612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11656340/"
] |
You mixed up some variables in the `askUserToLoad` method:
```py
if self.enterUsername in self.user and self.user[self.enterUsername] == self.enterPassword:
print('User Logged in Successfully')
else:
print('sorry user not found')
```
|
238,782 |
CONTEXT : I'm building a website where users can upload many files. [WEB SERVER, no gpu]
WHAT I WANT : that an uploaded .obj => render an image preview as a .png
WHY : to manage a library of multiple files so the image is to have a preview, imagine a multimedia library like google photo, but with videos, audios, photos, 3d files (with their thumbnail), ETC.
I CAN : with aasimp : I can easily convert from .obj, .fbx..... to .glb or .gltf [but aasimp have no solution to render an image from a 3d file]
I ALSO CAN : render 1 frame to png (( but only from a .blend ))
SEE HOW I SUCCESSFULLY INSTALLED BLEND + RENDER .blend TO .PNG ON LINUX : <https://almalinux.discourse.group/t/how-to-install-blender-3d-withtout-snap-and-without-a-desktop/526>
**QUESTION** : is it possible to invoke from the command line (linux web server without a desktop...) to create a new .blend and import a .obj or .fbx into that new .blend and than I can do my render?
WHY THE QUESTION : the command "--render-frame" accepts only .blend so the only "missing" stuff I need is to convert a .obj or .fbx from the command line (shell or python script) to convert to .blend
when I TRY this
```
xvfb-run -a --server-args="-screen 0, 1280x720x24" /opt/blender293/blender pathtoOBJ.obj --render-frame 1 -F PNG -b
```
I get this
```
Error: File format is not supported in file 'pathtoOBJ.obj'
```
---
when I do the same command with a .blend it's working fine see this. This image was generated from a .blend via a linux COMMAND LINE (shell) without GPU, without desktop
[](https://i.stack.imgur.com/4AV2U.png)
|
2021/09/22
|
[
"https://blender.stackexchange.com/questions/238782",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/132680/"
] |
Assuming you have this animation:
[](https://i.stack.imgur.com/2iKxG.png)
[](https://i.stack.imgur.com/1IfRm.gif)
and now you want the same animation on another y-value you can do this:
select your animation, press SHIFT-D to copy all keyframes, move it with your mouse where you want to have it and you get something like this:
[](https://i.stack.imgur.com/UwH8N.png)
Now go to frame 1 and keyframe delta transform - location:
[](https://i.stack.imgur.com/M2cgg.png)
Then go 1 frame before your first copied keyframe and keyframe again:
[](https://i.stack.imgur.com/GTjwB.png)
then it looks like this:
[](https://i.stack.imgur.com/Q41Xb.png)
Then change your timeline +1 frame and change the y-value (or other values as you need) and keyframe the delta again.
done.
result:
[](https://i.stack.imgur.com/Foh8H.gif)
|
72,495,735 |
I have the following two common table expressions:
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
```
Notice that both CTEs are exactly the same (with the exception of `HAVING COUNT(o.id) > 0` clause in `cte_2`).
If I independently run the query inside of `cte_1`, I get a value of 200. If I independently run the query inside of `cte_2`, I get a value of 75. I'm trying to run a single query using these CTEs to get the following counts:
```
foo bar
200 75
```
I tried the following (which is syntactically incorrect):
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
SELECT count(users) as foo
FROM cte_1
SELECT count(order_count) as bar
from cte2
```
Any assistance you can give this SQL newbie would be greatly appreciated! Thanks!
|
2022/06/03
|
[
"https://Stackoverflow.com/questions/72495735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18908491/"
] |
```
WITH
cte as (
SELECT
u.id AS userid,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY
u.id
)
SELECT
count(userid) as foo,
sum(case when order_count > 0 then 1 else 0 end) as bar
FROM
cte
```
|
2,592,292 |
Let's say I have a standalone windows service running in a windows server machine. How to make sure it is highly available?
1). What are all the design level guidelines that you can propose?
2). How to make it highly available like primary/secondary, eg., the clustering solutions currently available in the market
3). How to deal with cross-cutting concerns in case any fail-over scenarios
If any other you can think of please add it here ..
**Note:**
The question is only related to windows and windows services, please try to obey this rule :)
|
2010/04/07
|
[
"https://Stackoverflow.com/questions/2592292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125904/"
] |
To keep the service at least running you can arrange for the Windows Service Manager to automatically restart the service if it crashes (see the Recovery tab on the service properties.) More details are available here, including a batch script to set these properties - [Restart a windows service if it crashes](https://serverfault.com/questions/48600/how-can-i-automatically-restart-a-windows-service-if-it-crashes)
High availability is more than just keeping the service up from the outside - the service itself needs to be built with high-availabiity in mind (i.e. use good programming practices throughout, appropriate datastructures, pairs resource aquire and release), and the whole stress-tested to ensure that it will stay up under expected loads.
For idempotent commands, tolerating intermittent failures (such as locked resources) can be achieved by re-invoking the command a certain number of times. This allows the service to shield the client from the failure (up to a point.) The client should also be coded to anticipate failure. The client can handle service failure in several ways - logging, prompting the user, retrying X times, logging a fatal error and exiting are all possible handlers - which one is right for you depends upon your requirements. If the service has "conversation state", when service fails hard (i.e. process is restarted), the client should be aware of and handle ths situation, as it usually means current conversation state has been lost.
A single machine is going to be vulnerable to hardware failure, so if you are going to use a single machine, then ensure it has redundant components. HDDs are particularly prone to failure, so have at least mirrored drives, or a RAID array. PSUs are the next weak point, so redundant PSU is also worthwhile, as is a UPS.
As to clustering, Windows supports service clustering, and manages services using a Network Name, rather than individual Computer names. This allows your client to connect to any machine running the service and not a hard-coded name. But unless you take additional measures, this is Resource failover - directing requests from one instance of the service to another. Converstaion state is usually lost. If your services are writing to a database, then that should also be clustered to also ensure reliabiity and ensure changes are available to the entire cluster, and not just the local node.
This is really just the tip of the iceberg, but I hope it gives you ideas to get started on further research.
[Microsoft Clustering Service (MSCS)](http://msdn.microsoft.com/en-us/library/ms952401.aspx)
|
4,648,533 |
I am using a jQuery UI Tabs widget that exists within an iframe on the page. From the parent document, I need to be able to access the tabs object and use its methods (the 'select' method in particular). I am using the following code currently:
```
var iframe = $('#mainFrame').contents().get(0);
$('#tabs', iframe).tabs('select', 1);
```
The code does not throw any errors/warnings in the console and the jquery object for $('#tabs', iframe) does seem to be selecting the correct elements from the DOM of the iframe, however nothing happens when this is executed.
|
2011/01/10
|
[
"https://Stackoverflow.com/questions/4648533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192694/"
] |
You're turning the jQuery object reference into a `DOM node` by calling `.get(0)`. Try instead:
```
var iframe = $('#mainFrame').contents();
iframe.find('#tabs').tabs('select', 1);
```
ref.: [.find()](http://api.jquery.com/find/)
|
1,362,764 |
$$\int\frac{1-v}{(v+1)^2}dv$$
>
> I think I am supposed to do PFD, but solving for A and B I get zero for both.
>
>
>
$$(1-v) = A(v+1) + B(v+1)$$
>
> let $v = -1$
>
>
>
$$A = \frac{2}{0}, B = \frac{2}{0}$$
>
> So this is undefined? (or infinity?)
>
>
>
|
2015/07/16
|
[
"https://math.stackexchange.com/questions/1362764",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/167946/"
] |
When the denominator has multiple roots, the method changes a bit. Try
$$\frac A{v+1}+\frac B{(v+1)^2}=\frac{1-v}{(v+1)^2}$$
|
2,943,502 |
The system in question is:
$$
x' = y\\
y' = \mu x+x^2
$$
This has a fixed point at $x=0,-\mu$ and $y=0$ and after computing the Jacobian I find eigenvalues of
$$
\lambda = \pm \sqrt{\mu}
$$
for the $x=0 ,y=0$ solution. This is a saddle point for $\mu>0$ but becomes completely imaginary for $\mu<0.$ I am not sure how to determine the stability for $\mu<0$
|
2018/10/05
|
[
"https://math.stackexchange.com/questions/2943502",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/146286/"
] |
You cannot conclude anything about the stability of a fixed point through linearization whenever the Jacobian has at least one purely imaginary eigenvalue.
However, what you can do, is to express the system as a second-order system by letting $\ddot{x} = \dot{y}$:
$$\ddot{x}-\mu x - x^2 = 0$$
We can interpret this system as a generalized harmonic oscillator with an amended potential. To see this, recall that the equation for a harmonic oscillator is $\ddot{x}+x=0$, where the spring constant is 1 and the potential is given by $\int\_0^x y \ dy = x^2/2$. So in our case, we have a negative spring constant when $\mu>0$ and a negative spring constant when $\mu<0$. The potential in our case is given by:
$$\int\_0^x (-\mu y -y^2) \ dy = -\mu x^2/2 - x^3/3$$
Furthermore, you can have more fun by writing down the Hamiltonian for your system:
$$H = T + V = \dot{x}^2/2 - \mu x - x^2 = p^2/2 - \mu x - x^2$$
So now you can draw the potential and use it to sketch the phase portrait of your system, from which you can infer the stability of the equilibrium points.
Here is an example of what this looks like for a different system with a different potential:
[](https://i.stack.imgur.com/1czIw.png)
So basically, for your system, you can look at the potential and say that the quadratic term dominates over the cubic when $x$ is close to 0, which means that for $\mu<0$ the potential will have a valley at $x=0$ and, therefore, solutions that start around it on a sufficiently low energy level, will get trapped (i.e., the equilibrium point $x=0,y=0$ is a center).
Hope this helps!
|
29,600,941 |
I want to add data in drop down list,I am able to add the data and view it but for that i have to refresh the page again, I want to do that in jQuery without refreshing the page.
|
2015/04/13
|
[
"https://Stackoverflow.com/questions/29600941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4781955/"
] |
The problem is
* Caused by: java.lang.UnsupportedOperationException: Can't convert to color: type=0x2 at android.content.res.TypedArray.getColor(TypedArray.java:326)
The code or id of the color is invalid.
|
16,108,745 |
I have Radmenu placed in master page and if I click any item ,page will get post back so its difficult to maintain item selected focused with the color.I tried placing an ajaxpanel,still its getting post backed.
```
<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server">
<telerik:RadMenu ID="Menu1" runat="server" Skin="Office2010Silver"
Width="100%" Font-Bold="true"
Visible ="false">
<Items>
< <telerik:RadMenuItem runat="server" NavigateUrl="~/Home.aspx" Text="Home">
</telerik:RadMenuItem>
</Items>
</telerik:RadMenu>
```
Any suggestions will be of great help.
Thanks
|
2013/04/19
|
[
"https://Stackoverflow.com/questions/16108745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046415/"
] |
You can create a new `ApplicationContext` to represent multiple forms:
```
public class MultiFormContext : ApplicationContext
{
private int openForms;
public MultiFormContext(params Form[] forms)
{
openForms = forms.Length;
foreach (var form in forms)
{
form.FormClosed += (s, args) =>
{
//When we have closed the last of the "starting" forms,
//end the program.
if (Interlocked.Decrement(ref openForms) == 0)
ExitThread();
};
form.Show();
}
}
}
```
Using that you can now write:
```
Application.Run(new MultiFormContext(new Form1(), new Form2()));
```
|
55,859,542 |
```
var state = Vue.observable({
selectedTab: ''
});
Vue.component('block-ui-tab', {
props: ['name', 'handle', 'icon'],
template: '<li :handle="handle" :class="{ active: state.selectedTab === handle }"><i :class="icon"></i>{{ name }}</li>'
});
var app = new Vue({
el: '#app',
data: {},
methods: {},
computed: {},
watch:{},
mounted: function(){},
});
```
This doesn't work, so I'm wondering how to use the observable in the component and the vue root instance? Pass it as a prop, or?
|
2019/04/26
|
[
"https://Stackoverflow.com/questions/55859542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] |
First, I think you can use any serializer to convert your objects to the format you want.
```
var serialized = JsonConvert.SerializeObject(data)
```
Second, back to your question, here is the code. However, you need to add " around your variables and get rid of string concatenation I added for readability. Also, this code is so specific to your problem and for more generic solution go for the first approach.
```
var mainData = string.Join(',', data.Select(x => $" {{ {nameof(x.Id)} : {x.Id}, " +
$"{nameof(User)}s: " +
$"[ {string.Join(',', x.Users.Select(y => $"{{ {nameof(User.T_Id)} : {y.T_Id} }}"))}]" +
$"}}"));
var result = $"[{mainData}]" ;
```
As you changed the question, I updated my answer. So, you need to first join someView and user to get them together and then group by someView.id. Here is the code
```
var someViewsUsersJoin = someViews.Join(users, l => l.t_id, r => r.t_id, (someView, user) => new {someView, user});
var result = someViewsUsersJoin.GroupBy(x => x.someView.id).Select(x => new SomeViewModel()
{
Id = x.Key,
Users = x.Select(y => y.user).ToList()
});
```
|
25,772 |
A stranger walks up to you on the street. They say they lost their phone and need to make a phone call (has happened to me twice, and maybe to you). What's the worst a phone call could do?
Let's assume they don't run, don't plug any devices into the phone, they just dial a number and do whatever, and hang up.
|
2012/12/21
|
[
"https://security.stackexchange.com/questions/25772",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/17662/"
] |
A few scams I've seen making the rounds:
* Use it to dial a premium rate number owned by the group. In the UK, 09xx numbers can cost up to £1.50 per minute, and most 09xx providers charge around 33%, so a five minute call syphons £5 into the group's hands. If you're a good social engineer, you might only have a 10 minute gap between calls as you wander around a busy high-street, so that's £15 an hour (tax free!) - almost triple minimum wage.
* Use it to send premium rate texts. The regulations on there are tighter, but if you can get a premium rate SMS number set up, you can charge up to £10 per text. A scammer would typically see between £5 and £7 of that, after the provider takes a cut. It's also possible to set up a recurring cost, where the provider sends you messages every day and charges you up to £2.50 for each one. By law the service provider must automatically cancel it if they send a text sayin STOP, but every extra message you send gains you money.
* Set up an app in the app store, then buy it on peoples' phones. This can be very expensive for the victim, since apps can be priced very high - some up to £80. In-app purchases also work. This is precisely why you should be prompted for your password on *every* app purchase and in-app purchase, but not all phones do so!
* Install a malicious app, such as the mobile Zeus trojan. This can then be used to steal banking credentials and email accounts. This seems to be gaining popularity on Android phones.
|
6,659,360 |
I connected with VPN to setup the inventory API to get product list and it works fine. Once I get the result from the web-service and i bind to UI. And also I integrated PayPal with my application for make Express checkout when I make a call for payment I'm facing this error. I use servlet for back-end process. Can any one say how to fix this issue?
```
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
```
|
2011/07/12
|
[
"https://Stackoverflow.com/questions/6659360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504130/"
] |
First, you need to obtain the public certificate from the server you're trying to connect to. That can be done in a variety of ways, such as contacting the server admin and asking for it, [using OpenSSL to download it](http://www.madboa.com/geek/openssl/#cert-retrieve), or, since this appears to be an HTTP server, connecting to it with any browser, viewing the page's security info, and saving a copy of the certificate. (Google should be able to tell you exactly what to do for your specific browser.)
Now that you have the certificate saved in a file, you need to add it to your JVM's trust store. At `$JAVA_HOME/jre/lib/security/` for JREs or `$JAVA_HOME/lib/security` for JDKs, there's a file named `cacerts`, which comes with Java and contains the public certificates of the well-known Certifying Authorities. To import the new cert, run keytool as a user who has permission to write to cacerts:
```
keytool -import -file <the cert file> -alias <some meaningful name> -keystore <path to cacerts file>
```
It will most likely ask you for a password. The default password as shipped with Java is `changeit`. Almost nobody changes it. After you complete these relatively simple steps, you'll be communicating securely and with the assurance that you're talking to the right server and only the right server (as long as they don't lose their private key).
|
858,161 |
The question regards the Poisson distribution function as given by:
$$\frac{x^k e^{-x}}{k!}$$
The distribution's domain (x) goes from 0 to $\infty$, and $k \in \mathbb{N\_0}$
I tried the distribution as the following function:
$$\frac{x^r e^{-x}}{\Gamma(r + 1)}$$
To my surprise, the integral
$$\int\_0^\infty \frac{x^{r}e^{-x}}{\Gamma(r + 1)} dx = 1$$
At least, that's what I deduce from my tests of 0.5, 1.5, 1.2, and 7.9. I have done so non-algebraically, only numerically.
So my question is; is this a valid form of distribution? And should we perhaps replace the one currently on wikipedia stating the requirement of k to be a natural number?
|
2014/07/06
|
[
"https://math.stackexchange.com/questions/858161",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/132716/"
] |
"The distribution's domain" is a phrase I would not have understood if you hadn't provided some context. The distribution's **support** is the set of values the random variable can take, ~~or in the case of continuous distributions, the closure of that set.~~[Later edit: see **PS** below.] For the Poisson distribution whose probability mass function is
$$
k\mapsto\frac{x^k e^{-x}}{k!}
$$
the support is given by
$$
k\in\{0,1,2,3,\ldots\},
$$
the set of non-negative integers.
The set of possible values of $x$ is $[0,\infty)=\{x : x\ge 0\}$. That is the **parameter space**, not for a distribution, but for a family of distributions.
You leave us to infer, rather than explicitly saying, that $0.5$, $1.5$, $1.2$, and $7.9$ are values of $r$ rather than of $x$.
The fact that
$$
\int\_0^\infty \frac{x^r e^{-x}}{\Gamma(r + 1)} dx = 1
$$
is often taken to be the definition of the Gamma function, although the form in which it is most often stated is
$$
\Gamma(s) = \int\_0^\infty x^{s-1} e^{-x}\,dx,
$$
so the $s$ here is $r+1$. A continuous distribution called the Gamma distribution has probability density function
$$
x\mapsto\frac{x^{s-1} e^{-x}}{\Gamma(s)} \text{ for }x>0,
$$
and if one rescales it, putting $x/\lambda$ in place of $x$, one has the density
$$
x\mapsto\frac{(x/\lambda)^{s-1} e^{-x/\lambda}}{\Gamma(s)}\cdot\frac 1 \lambda \text{ for } x>0
$$
and that is also considered a "Gamma distribution". The extra $1/\lambda$ at the end comes from the chain rule. I like to write it is
$$
\frac{(x/\lambda)^{s-1} e^{-x/\lambda}}{\Gamma(s)}\cdot\frac {dx} \lambda\text{ for }x>0.\tag 1
$$
A connection between the Gamma distribution and the Poisson distribution is this: suppose the number of "occurrences" during a particular time interval has a Poisson distribution whose expected value is $\lambda$ times the amount of time, and that the numbers of "occurrences" in different time intervals are independent if the time intervals don't overlap. In that case, the time you wait until the $s$th occurence has the Gamma distribution $(1)$.
**PS:** I was not too precise about what "support" means". For distributions for which the set of values is topologically discrete, the support is indeed the set of values that can be attained. Thus for the Poisson distribution it is $\{0,1,2,3,\ldots\}$. But technically a "discrete distribution" is one for which all the probability is in point masses, and that need not be discrete in the topological sense: it could, for example, be the set of all rational numbers. So here's a **definition:** The support of a distribution is the smallest closed set whose complement has probability $0$. For the Poisson distribution, the set of possible values is $\{0,1,2,3,\ldots\}$, and that's *already* a closed set, so we don't need to take its closure and we get no complications or subtleties.
|
31,594,880 |
I am a complete beginner with the [D language](http://dlang.org/).
How to get, as an `uint` unsigned 32 bits integer in the D language, some hash of a string...
I need a quick and dirty hash code (I don't care much about the "randomness" or the "lack of collision", I care slightly more about performance).
```
import std.digest.crc;
uint string_hash(string s) {
return crc320f(s);
}
```
is not good...
(using `gdc-5` on Linux/x86-64 with phobos-2)
|
2015/07/23
|
[
"https://Stackoverflow.com/questions/31594880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841108/"
] |
A really quick thing could just be this:
```
uint string_hash(string s) {
import std.digest.crc;
auto r = crc32Of(s);
return *(cast(uint*) r.ptr);
}
```
Since `crc32Of` returns a `ubyte[4]` instead of the `uint` you want, a conversion is necessary, but since `ubyte[4]` and `uint` are the same thing to the machine, we can just do a reinterpret cast with the pointer trick seen there to convert types for free at runtime.
|
6,183,063 |
I am going to use on of the tooltip plugins listed in this question: [jquery tooltip, but on click instead of hover](https://stackoverflow.com/questions/1313321/jquery-tooltip-but-on-click-instead-of-hover)
How would I also setup a tooltip that randomized the text shown. For instance if you click a link you could be shown one of three possible messages:
Message 1
Message 2
Message 3
ideas?
|
2011/05/31
|
[
"https://Stackoverflow.com/questions/6183063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282789/"
] |
You usually have an array of messages and then generate a random index onclick.
something like
```
var messageArray = ["message 1", "message 2", "message 3"];
var randomNum = Math.floor(Math.random()*messageArray.size);
var myMessage = messageArray[randomNum];
```
or something like that. refactor to use ajax/your db if you need to
|
43,971,329 |
I have this query on mySQL
```
SELECT updated_at
FROM products
WHERE updated_at >= DATE_ADD(NOW(), INTERVAL -7 DAY)
GROUP BY day(updated_at)
ORDER BY updated_at desc
```
and I try to apply it on Laravel like this
```
$date = Products::select('updated_at')
->where('updated_at', '>=', 'DATE_ADD(NOW(), INTERVAL -7 DAY)')
->groupBy('updated_at')
->orderBy('updated_at', 'desc')
->get()
```
and the results on Laravel is show all data in updated\_at column, not just 6 days before now. Is there anything wrong with my query on Laravel, thank you
|
2017/05/15
|
[
"https://Stackoverflow.com/questions/43971329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7882004/"
] |
You have to use `whereRaw` instead:
```
$date = Products::select('updated_at')
->whereRaw('updated_at >= DATE_ADD(NOW(), INTERVAL -7 DAY)')
->groupBy('updated_at')
->orderBy('updated_at', 'desc')
->get()
```
|
71,630 |
My question originates from the book of Silverman "The Aritmetic of Elliptic Curves", 2nd edition (call it [S]). On p. 273 of [S] the author is considering an elliptic curve $E/K$ defined over a number field $K$ and he introduces the notion of a $v$-adic distance from $P$ to $Q$. This is done as follows:
Firstly, let's fix an absolute value (archimedean or not) $v$ of $K$ and a point $Q\in E(K\_v)$ (here $K\_v$ is the completion of $K$ at $v$). Next let's pick a function $t\_Q \in K\_v(E)$ defined over $K\_v$ which vanishes at $Q$ to the order $e$ but has no other zeroes. Now the $v$-adic distance from $P \in E(K\_v)$ to $Q$ is defined to be $d\_v(P, Q) := \min (|t\_Q(P)|\_v^{1/e}, 1)$. We will say that $P$ goes to $Q$, written $P~\xrightarrow{v}~ Q$, if $d\_v(P, Q) \rightarrow 0$. Later in the text (among other places in the proof of IX.2.2) the author considers a function $\phi\in K\_v(E)$ which is regular at $Q$ and claims that this means that $|\phi(P)|\_v$ is bounded away from $0$ and $\infty$ if $P~\xrightarrow{v}~ Q$.
I have a couple of questions about this:
1. How does one choose a $t\_Q$ that works? In the footnote in [S] it is demonstrated how one could use Riemann-Roch to pick a $t\_Q$ that has a zero only at $Q$. It seems to me however that such a procedure will not make sure that $t\_Q$ is defined over $K\_v$ since $K\_v$ is not algebraically closed.
2. For $\phi$ as above which does not vanish nor has a pole at $Q$, how does one see that $|\phi(P)|\_v$ is bounded away from $0$ and $\infty$ as $P~\xrightarrow{v}~ Q$?
3. Do these $d\_v$ have anything to do with defining a topology on $E(K\_v)$? I assume not, since I don't see how to make sense of it; but then on the other hand they are called "distance functions"...
|
2011/07/30
|
[
"https://mathoverflow.net/questions/71630",
"https://mathoverflow.net",
"https://mathoverflow.net/users/5498/"
] |
* You can choose $t\_Q$ to be defined over $K\_v$, since the divisor $n(Q\_v)$ is defined over $K\_v$, and for large enough $n$ there will be a global section. Note that Riemann-Roch works over non-algebraically closed fields this way. Or you can choose a basis defined over some finite Galois extension of $K\_v$, and then taking appropriate linear combinations of the Galois conjugates, get a function defined over $K\_v$. See Proposition II.5.8 in [S].
* The function defined in the text is only a reasonable "distance function" in the sense that it measures the distance from $P$ to the fixed point $Q$. For the purposes of this proof, that's fine. If you want to define the $v$-adic topology, you need to be a little more careful. Locally around $Q$ you could use $$d\_v(P\_1,P\_2)=min(|t\_Q(P\_1)-t\_Q(P\_2)|^{1/e},1)$$, but that still only works in a neighborhood of $Q$, i.e., in a set $$\{P : d\_v(P,Q)<\epsilon\}$$ for a sufficiently small $\epsilon$. Using local height functions, more precisely the local height relative to the diagonal in $E(K\_v)\times E(K\_v)$, one gets a "good" distance function that is defined everywhere. See for example Lang's *Fundamentals of Diophantine Geometry* or the book *Diophantine Geometry* that Hindry and I wrote for the general construction of local height functions.
|
17,296,097 |
What is wrong in this error ?
>
> alter table INFO add constraint chk\_app check
> (CASE WHEN app IS NULL THEN app = 'A');
>
>
>
>
If its because *app = 'A'* I am calling it twice then how to have a check constraint to check if app is null then it should have value A
|
2013/06/25
|
[
"https://Stackoverflow.com/questions/17296097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2291869/"
] |
@FreefallGeek,
What do you mean by you can't filter AppointmentDate if you remove it from SELECT? Report Builder allows you do dataset filtering based on the user assigned parameter in run time with query like this,
```
SELECT DISTINCT PaientID, InsuranceCarrier
FROM Encounters
WHERE
AppointmentDate >= @beginningofdaterange
AND AppointmentDate <= @endofdaterange
```
With @beginningofdaterange and @endofdaterange as your report parameter. This should work unless you need to do additional filtering that require to return AppointmentDate as result.
If you really need to return the Appointment date as result or for additional filtering, then the next question is what should be the AppointmentDate when there are multiple visit with same patient and insurance carrier? The first visit or the last visit within the date range? If that is the case, you could use group by like this for first visit,
```
SELECT Min(AppointmentDate) AS FirstAppointmentDate, PaientID, InsuranceCarrier
FROM Encounters
WHERE
AppointmentDate >= @beginningofdaterange
AND AppointmentDate <= @endofdaterange
GROUP BY PaientID, InsuranceCarrier
ORDER BY AppointmentDate
```
However, from your description, it appears that you only need the distinct patient and insurance carrier with the capability to filter the date. If that understanding is correct, you could just filter the appointment with user input parameter in the WHERE clause without the SELECT.
|
42,001,511 |
I have got a Microsoft Access database in the resource folder of my Java application.
When the user clicks a button, this database is copied to the temp directory of the PC. Then I make a temporary VBS file in the same directory and execute it.
(This VBS file calls a VBA macro within the database, that deletes some records.)
However, as the macro attempts to delete the records an error is thrown stating that the database is read only.
Why does this happen?
Here is my code:
When the user clicks the button, some variables are set and then the following code is executed:
```java
private void moveAccess() throws IOException {
String dbName = "sys_cl_imp.accdb";
String tempDbPath = System.getenv("TEMP").replace('\\', '/') + "/" + dbName;
InputStream in = ConscriptioLegere.class.getResourceAsStream("res/" + dbName);
File f = new File(tempDbPath);
Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
this.dbFilePath = tempDbPath;
System.out.println("access in temp");
f = null;
}
```
Then a connection is made to the database to update some data;
with
```
Connection con = DriverManager.getConnection("jdbc:ucanaccess://" + dbFilePath);
Statement sql = con.createStatement();
...
sql.close();
con.close();
```
Afterwards this is executed:
```java
public boolean startImport() {
File vbsFile = new File(vbsFilePath);
PrintWriter pw;
try {
updateAccess();
} catch (IOException e) {
e.printStackTrace();
return false;
}
try{
pw = new PrintWriter(vbsFile);
pw.println("Set accessApp = CreateObject(\"Access.Application\")");
pw.println("accessApp.OpenCurrentDatabase (\"" + dbFilePath + "\")");
pw.println("accessApp.Run \"sys_cl_imp.importData\", \"" + saveLoc + "\"");
pw.println("accessApp.CloseCurrentDatabase");
pw.close();
Process p = Runtime.getRuntime().exec("cscript /nologo \"" + vbsFilePath + "\"");
```
While the process is running, the error occurres.
I don't understand why the database is open as ReadOnly.
I tried setting f to null after the copying of the db, but it proved not to work that way.
|
2017/02/02
|
[
"https://Stackoverflow.com/questions/42001511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4440871/"
] |
Based on [this dicussion](https://sourceforge.net/p/ucanaccess/discussion/help/thread/4539a56c/).
The solution is adding `;singleconnection=true` to JDBC url. `UCanAccess` will close the file after JDBC connection closed.
```
Connection con = DriverManager.getConnection("jdbc:ucanaccess://" + dbFilePath +";singleconnection=true");
```
|
31,974,011 |
I'm currently working on the following website:
<http://hmdesign.alpheca.uberspace.de/>
As you can see, I already managed to create a list of div.project-item elements. Due to the use of inline-blocks, it also reduces the number of columns when you resize the window. What I want to accomplish now is, when you resize the window, that the elements scale up/down in a certain range (between min-width and max-width) until it reaches the maximum/minimum and that it THEN removes/creates a column. The problem now is that there is a huge empty gap after removing a column. It would be much smarter to still show lets say 3 smaller columns in that situation instead of 2 big ones.
I already tried to use a flexbox which didn't really help and also to use block elements instead of inline-block and float them to the left. Then the resizing works but I also want the whole thing to be centered (like now), which I didn't found a way yet to do with floated elements.
Relevant code below:
HTML:
```
<div class="content-wrapper">
<div class="project-list">
<div class="project-item">
<a href="#">
<img class="project-image" src="res/img/Placeholder.jpg">
<div class="project-overlay">
<div class="project-desc">
<span class="project-title"></span>
<span class="project-text"></span>
</div>
</div>
</a>
</div>
<div class="project-item"...
```
CSS:
```
/* Wrapper */
div.nav-wrapper, div.content-wrapper {
max-width: 1280px;
padding: 0 25px;
position: relative;
margin: 0 auto;
height: 100%;
}
/* Portfolio Projektliste */
div.project-list {
padding-top: 150px;
max-width: 1300px;
margin: 0 10px;
text-align: center;
font-size: 0;
}
/* Projekt Item */
div.project-item {
display: inline-block;
position: relative;
width: 400px;
height: auto;
margin: 10px;
overflow: hidden;
}
div.project-item:after {
padding-top: 56.25%;
/* 16:9 ratio */
display: block;
content: '';
}
img.project-image {
position: absolute;
left: 50%;
top: 50%;
transform: translateY(-50%) translateX(-50%);
-webkit-transform: translateY(-50%) translateX(-50%);
-moz-transform: translateY(-50%) translateX(-50%);
max-width: 100%;
}
div.project-overlay {
position: absolute;
width: 100%;
height: 100%;
z-index: 10;
background-color: black;
opacity: 0;
}
```
|
2015/08/12
|
[
"https://Stackoverflow.com/questions/31974011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2738393/"
] |
Take a look at the "Gang of Four" *composite* pattern:
======================================================
The Child classes should not be derived from the Parent class.
Instead, Child and Parent classes should implement the same Interface,
let's call it `IAlgorithm`.
This Interface should have a pure `virtual` method `start()`...
Here is an example (using C++11 `auto` and Range-based for loop):
```
#include <iostream>
#include <vector>
/* parents and children implement this interface*/
class IAlgorithm {
public:
virtual int start() = 0;
};
class Parent : public IAlgorithm {
private:
std::vector<IAlgorithm*> children;
public:
void addChild(IAlgorithm* child) {
children.push_back(child);
}
int start() {
std::cout << "parent" << std::endl;
for (auto child: children)
child->start();
return 0;
}
};
class Child1 : public IAlgorithm {
public:
int start() {
std::cout << "child 1" << std::endl;
return 1;
}
};
class Child2 : public IAlgorithm {
public:
int start() {
std::cout << "child 2" << std::endl;
return 2;
}
};
class Child3 : public IAlgorithm {
public:
int start() {
std::cout << "child 3" << std::endl;
return 3;
}
};
int main()
{
Parent parent;
Child1 child_1;
Child2 child_2;
Child3 child_3;
parent.addChild(&child_1);
parent.addChild(&child_2);
parent.addChild(&child_3);
parent.start();
return 0;
}
```
The output:
```
parent
child1
child2
child3
```
|
12,070,394 |
In my Events table I have a column called Pos1, which contains IDs from A to E. I need to count how many times 'E' appears in the column and where it ranks alongside the other numbers.
For example in this table 'E' occurs **1** time and is ranked **4** (D=3, A=2, C=2, E=1, B=0).
```
Pos1
E
C
D
C
D
D
A
A
```
I'm a complete SQL amateur so the closest I've got is an array printing the count of each ID, but I need this to be limited to counting a single ID *and* printing the rank.
```
$query = "SELECT Pos1, COUNT(Pos1) FROM Events GROUP BY Pos1";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['COUNT(Pos1)'] ."<br />";
}
```
|
2012/08/22
|
[
"https://Stackoverflow.com/questions/12070394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/310174/"
] |
try this:
```
SELECT Pos1, a.cnt, rank
FROM(
SELECT a.Pos1, a.cnt, (@rank := @rank + 1) AS rank
FROM(
SELECT Pos1, COUNT(Pos1) cnt
FROM Events
GROUP BY Pos1
) a, (SELECT @rank := 0) b
ORDER BY a.cnt DESC
)a
WHERE a.pos1 = 'E';
```
[SQLFIDDLE DEMO HERE](http://sqlfiddle.com/#!2/a1e4e/2)
EDIT: php code
```
$query = "SELECT Pos1, a.cnt, rank
FROM(
SELECT a.Pos1, a.cnt, (@rank := @rank + 1) AS rank
FROM(
SELECT Pos1, COUNT(Pos1) cnt
FROM Events
GROUP BY Pos1
) a, (SELECT @rank := 0) b
ORDER BY a.cnt DESC
)a
WHERE a.pos1 = '$pos1'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
echo $row['Pos1']." ".$row['cnt']." ".$row['rank']."<br />";
```
|
18,109,625 |
I sometimes need to write the whole alphabet `abcd…z` and I hate typing it letter by letter in Vim's insert mode. Does there exist any method to do this more efficiently?
I know about the `ga` command which gives me the ascii code of the character where the cursor is … but don't know anything about how to mix it with my standard solution to type numbers from 1 to (for example) 5000: `a1ESCqqyyp^Aq4998@q` …
|
2013/08/07
|
[
"https://Stackoverflow.com/questions/18109625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282982/"
] |
Using `set nrformats+=alpha`:
```
ia<Esc>qqylp<C-a>q24@q
```
Step by step:
```
ia<Esc> " Start with 'a'
qqylp<C-a>q " @q will duplicate the last character and increment it
24@q " Append c..z
```
|
48,270,808 |
Not exactly sure what I am doing wrong here, I have looked at other forum post and this is what they say to do to re-auth a user. But I am getting an error of:
`TypeError: Cannot read property 'credential' of undefined` on this line here:
`const credentials = fire.auth.EmailAuthProvider.credential(currentUser.email, user.currentPass);`
Here is the code:
```
const currentUser = fire.auth().currentUser;
const credentials = fire.auth.EmailAuthProvider.credential(currentUser.email, user.currentPass);
currentUser
.reauthenticateWithCredential(credentials)
.then(() => {
alert('Success');
})
.catch(err => {
alert(err);
});
```
|
2018/01/15
|
[
"https://Stackoverflow.com/questions/48270808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8551819/"
] |
Like @bojeil answered, it's a namespace so, for instance and if you're using typescript and you used `firebase.initializeApp(config);` in another class, just add again the import in the class where you user the credential method with `import * as Firebase from 'firebase/app';`
As u can see in the doc `credential` it's a static method in a static class that's why you need the namespace.
|
148,103 |
[](https://i.stack.imgur.com/VlYZM.png)
I have a fictional world, consisting of a federation of 17 provinces (in blue on the map extract). Currently, it is in the late 1920's. The Dzevogurski and Quidthovitse provinces are on the brink of war. Historically, the province of Ladies Beach was part of Dzevogurski but split away peacefully several years ago for admisitrative reasons. The mountain range running NW-SE formed a natural boundry.
In the region concerned, there are two major railway lines involved in trans-continental transport. The Fyonas River - Kandice Beach line runs through two districts of Dzevogurski. To Quidthovice, this is a major point of 'pain': Their tracks run through their 'rivals' territory.
Also, in the 1890's Quidthovice managed to convince the Kimberley-district government to deny the builders of the Vaenesston-Tannith Beach line access to the 'easy' pass between Kimberley and St. Marias Stone, where the Quidthovice-based railroad company had its tracks laid already. To avoid conflict, the Dzevogurski-Ladies Beach government (sitting in Vaenesston) let this slide.
Now, Quidthovice is trying to 'persuade' the two districts of Kimberley and Murrayville (in red/pink) to join their province. Their current 'parent' (the Dzevogurski province) naturally resists. This time, the Dzevogurski government will fight.
If Kimberley and Murrayville do flip, this will [exclave](https://en.wikipedia.org/wiki/Enclave_and_exclave) Yadzor.
The districts of Kimberley, Murrayville, Yadzor are mainly cattle ranches, with some fruit (in the mountains) and dairy production. The population is being influeced by both sides.
The question which I'm asking is this: Can two provinces in a federation have a war between themselves, with everybody else staying neutral?
Can you still call it a 'civil war'?
I know that opinion-based questions are frowned upon in this forum, hence this is an optional question: How would this conflict be resolved?
|
2019/05/31
|
[
"https://worldbuilding.stackexchange.com/questions/148103",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/6500/"
] |
**It depends**
I would say that if the question is purely about semantics, we do not have an internationally accepted definition of civil war. I think that the conflict between two provinces in a federation is not a civil war. Presumably, there is some sort of a federal government, and it's not taking part in it in the situation you describe. Nor is either of the two sides trying to overthrow the federal government.
It can be called 'civil war' in quotes later, if the conflict was especially long or bloody, and the description may stick. Or it may be treated as a big [range war](https://en.wikipedia.org/wiki/Range_war).
Most of other parts of your question depend on the strength of the federal government, the acceptable policies in your world. Will other provinces join in the war - depends on what they stand to win by participating and whether that's an acceptable part of their political culture. They may be content to solve some conflicts by proxy, supplying the combating provinces, but not risking their troops. Or they may treat it as a humanitarian catastrophe and declare strict policy of non-intervention in order to reap some political capital from it.
As for the ways to solve it - again, it severely depends on the structure of the federation and the strength of the federal government. It may be a literal intervention by federal troops that stops the silliness. Or, maybe, federal government is severely decentralized and has a huge latency - all other provinces need to summon a temporary Council in order to figure out what to do next. It also depends on the international conditions - what are the neighbors of your country like and what will they do when the shooting starts?
|
69,850,831 |
I have a dataframe which looks something like the following (for example):
```
set.seed(42) ## for sake of reproducibility
n <- 6
dat <- data.frame(date=seq.Date(as.Date("2020-12-26"), as.Date("2020-12-31"), "day"),
category=rep(LETTERS[1:2], n/2),
daily_count=sample(18:100, n, replace=TRUE)
)
dat
# date category daily_count
#1 2020-12-26 A 60
#2 2020-12-27 B 32
#3 2020-12-28 B 39
#4 2020-12-29 B 75
#5 2020-12-30 A 25
#6 2020-12-31 A 53
#7 2020-12-26 A 60
#8 2020-12-27 A 32
#9 2020-12-28 A 39
#10 2020-12-29 B 75
#11 2020-12-30 B 25
#12 2020-12-31 B 53
.
.
.
```
I am trying to create a boxplot with month and year on its X-Axis and it looks like this:
[](https://i.stack.imgur.com/kIInC.png)
I would like to create a vertical line on ***2013-08-23***. I am using the following code for this:
```
library(ggplot2)
ggplot(dat) +
geom_boxplot(aes(y=daily_count,
x=reorder(format(dat$date,'%b %y'),dat$date),
fill=dat$category)) +
xlab('Month & Year') + ylab('Count') + guides(fill=guide_legend(title="Category")) +
theme_bw()+
theme(axis.text=element_text(size=10),
axis.title=element_text(size=10))+
geom_vline(xintercept = as.numeric(as.Date("2013-08-23")), linetype=1, colour="red")
```
Any guidance please?
|
2021/11/05
|
[
"https://Stackoverflow.com/questions/69850831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17033294/"
] |
In this answer:
* I've created a much bigger sample
* I'm using `yearmonth` from `tsibble` for simplicity
* I've solved the issue with the vertical line
* I cleaned up a bit the use of labs for a cleaner code
```r
set.seed(42)
dates <- seq.Date(as.Date("2012-08-01"), as.Date("2014-08-30"), "day")
n <- length(dates)
dat <- data.frame(date = dates,
category = rep(LETTERS[1:2], n/2),
daily_count = sample(18:100, n, replace=TRUE))
library(ggplot2)
library(tsibble)
ggplot(dat) +
geom_boxplot(aes(y = daily_count,
x = yearmonth(date),
group = paste(yearmonth(date), category),
fill = category)) +
labs(x = 'Month & Year',
y = 'Count',
fill = "Category") +
theme_bw() +
theme(axis.text=element_text(size=10),
axis.title=element_text(size=10)) +
geom_vline(xintercept = lubridate::ymd("2013-08-23"), linetype=1, colour="red", size = 2)
```

Created on 2021-11-05 by the [reprex package](https://reprex.tidyverse.org) (v2.0.0)
I set the vertical line thicker so to be seen.
---
Unfortunately the chart is difficult to visualize. Why don't you use ribbons instead?
With random data is horrible, but with yours you should see something meaningful.
```
library(ggplot2)
library(tsibble)
library(dplyr)
library(tidyr)
dat %>%
group_by(category, yearmonth = yearmonth(date)) %>%
summarise(q = list(quantile(daily_count))) %>%
unnest_wider(q, names_sep = "_") %>%
ggplot(aes(x = yearmonth, fill = category, colour = category)) +
geom_ribbon(aes(ymin = `q_0%`, ymax = `q_100%`), alpha = 0.2) +
geom_ribbon(aes(ymin = `q_25%`, ymax = `q_75%`), alpha = 0.2) +
geom_line(aes(y = `q_50%`)) +
labs(x = 'Month & Year',
y = 'Count',
colour = "Category",
fill = "Category") +
theme_bw() +
theme(axis.text=element_text(size=10),
axis.title=element_text(size=10)) +
geom_vline(xintercept = lubridate::ymd("2013-08-23"), linetype=1, colour="red", size = 2)
```
[](https://i.stack.imgur.com/gBi9j.png)
|
13,612,837 |
I'm using boost::regex to parse some formatting string where '%' symbol is escape character. Because I do not have much experience with boost::regex, and with regex at all to be honest I do some trial and error. This code is some kind of prototype that I came up with.
```
std::string regex_string =
"(?:%d\\{(.*)\\})|" //this group will catch string for formatting time
"(?:%([hHmMsSqQtTlLcCxXmMnNpP]))|" //symbols that have some meaning
"(?:\\{(.*?)\\})|" //some other groups
"(?:%(.*?)\\s)|"
"(?:([^%]*))";
boost::regex regex;
boost::smatch match;
try
{
regex.assign(regex_string, boost::regex_constants::icase);
boost::sregex_iterator res(pattern.begin(), pattern.end(), regex);
//pattern in line above is string which I'm parsing
boost::sregex_iterator end;
for(; res != end; ++res)
{
match = *res;
output << match.get_last_closed_paren();
//I want to know if the thing that was just written to output is from group describing time string
output << "\n";
}
}
catch(boost::regex_error &e)
{
output<<"regex error\n";
}
```
And this works pretty good, on the output I have exactly what I want to catch. But I do not know from which group it is. I could do something like `match[index_of_time_group]!=""` but this is kind of fragile, and doesn't look too good. If I change `regex_string` index that was pointing on group catching string for formatting time could also change.
Is there a neat way to do this? Something like naming groups? I'll be grateful for any help.
|
2012/11/28
|
[
"https://Stackoverflow.com/questions/13612837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1788633/"
] |
You can use [`boost::sub_match::matched`](http://www.boost.org/doc/libs/release/libs/regex/doc/html/boost_regex/ref/sub_match.html#boost_regex.sub_match.matched) bool member:
```
if(match[index_of_time_group].matched) process_it(match);
```
It is also possible to use named groups in regexp like: `(?<name_of_group>.*)`, and with this above line could be changed to:
```
if(match["name_of_group"].matched) process_it(match);
```
|
38,817 |
In Windows Vista, whenever I open a folder, the selection of columns is nonsensical: album, date taken, etc., for folders that contain no music or pictures whatsoever. I can select the correct columns for a particular folder, but all the other folders are still wrong, even when I go in to Folder Options and click the button to set the current options to all folders of this type.
How can I tell Windows to use the current column selection for all folders, unless otherwise specified?
|
2009/09/10
|
[
"https://superuser.com/questions/38817",
"https://superuser.com",
"https://superuser.com/users/10624/"
] |
eZine Article: [Setup a Default Folder View in Windows Vista](http://ezinearticles.com/?Solved---Setup-a-Default-Folder-View-in-Windows-Vista!&id=1465143) talks about some registry stuff along with the points in `Daniel`'s answer. Below is from this link
>
> One of the problems many people face once they have installed Vista is
> that their folder view will change every time they close and reopen a
> folder. This is annoying right?
>
>
> Well here is the solution:
>
>
> 1 Open the registry: Simply click on the start orb and type in "regedit" into the search field. A file called regedit.exe will show
> up at the top, double-click it!
>
>
> 2 Locate the following folders in the registry editor by clicking on the small black arrows to expand the folder structure:
>
>
> [HKEY\_CURRENT\_USERSoftwareClassesLocal
> SettingsSoftwareMicrosoftWindowsShellBags]
>
>
> [HKEY\_CURRENT\_USERSoftwareClassesLocal
> SettingsSoftwareMicrosoftWindowsShellBagMRU]
>
>
> 3 Right click on the folder "Bags" and click on delete, do the same for BagMRU. This is how you get rid of disturbing folder view entries.
> Don't worry we will now create a new one called "DefaultFolders".
>
>
> 4 Right click on the folder "Shell" that is the parent folder of the folders you just deleted.
>
>
> Click on "New" -> "Key". Name it "DefaultFolders".
>
>
> 5 Repeat 4. but for the folder we just created and name the new folder "Shell". That way you will create a subfolder "Shell" inside
> the folder "DefaultFolders".
>
>
> 6 Now we right-click on the folder "Shell" and create a new String: "New" -> "String Value".
>
>
> Give the string the name "FolderType".
>
>
> 7 Double-click it and type "Documents" into the value field.
>
>
> 8 Almost done, now all folders will have the same folder view as the "Documents" folder. Time to set your default folder view. To do that
> open up the explorer (Windows-key + E is the shortcut).
>
>
> Now locate C:UsersYour\_User\_NameDocuments, where C: is the partition
> on which you installed Windows obviously. Make sure to set your
> favorite folder view (mine is Details) there.
>
>
> Click on "Organize" -> "Folder and Search Options".
>
>
> Now go to the tab "View" and finally click on "Apply to Folders"!
>
>
>
I have used the steps from `Daniel`'s answer on Windows XP machines.
If they do not work on the Vista, try the eZine article.
Meanwhile, this Vista64 thread suggests Vista SP2 has solved this problem.
|
113,574 |
In D&D 5th edition, there is a continuity among the spells that deal with returning life to the dead. Virtually all of them require an expenditure of diamond or diamond dust.
* **Revivify** diamonds worth 300 gp
* **Raise Dead** diamond worth at least 500 gp
* **Resurrection** a diamond worth at least 1,000 gp
* **True Resurrection** a sprinkle of holy water and diamonds worth at least 25,000gp
Additionally, some restorative spells require similar materials:
* **Clone** diamond worth at least 1,000 gp
* **Greater Restoration** diamond dust worth at least 100 gp
Because of this, my players have realized that there is a different order of value placed upon any diamonds they find. An opal or sapphire might be spent, but the diamonds they find are hoarded against possible future need.To be fair, diamonds are used in other spells, but in these they are thematically linked enough to impart the gem a symbolic meaning of restoration, at least in the games we play.
I realize that this doesn't change the value of diamonds in a monetary sense. 500 gp worth of diamonds is worth 500 gp, regardless if they are 10gp/carat, or 50 gp/carat. However, it has got me wondering. Since this does make diamonds special in the eyes of my players, setting them apart from other gems which are largely treated as high denomination currency, **are there other gems or substances (precious or not) among the material components in the spell list which are likewise identified with a certain *type* of spell?**
Such information would be good to have for anything from simple flavor to home brewing new spells.
---
Related:
[Material Component of Reviving Spells](https://rpg.stackexchange.com/questions/101979/material-component-of-reviving-spells)
|
2018/01/17
|
[
"https://rpg.stackexchange.com/questions/113574",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/28927/"
] |
Yes, some material components are thematically related to types of spells
-------------------------------------------------------------------------
I found [this spreadsheet](https://docs.google.com/spreadsheets/d/1KSibOeWub0_f79GYSnMu7om8kWwog1ob8dRY9LLoDAE/edit#gid=0) from this [reddit post](https://www.reddit.com/r/DnD/comments/5fz3k0/spreadsheet_all_material_spell_components_in_dd_5e/), where the user compiled the material components for a lot of spells.
Looking at this list, there are some thematic links, some more clear than others. The stronger ones that I noticed are:
* **Holy water:** Bless, Commune, Dispel Evil, Forbiddance, Magic Circle, Protection from Evil/Good, Regenerate, True Resurrection, Wind Walk
* **Feather:** Fly, Foresight, Identify, Wind Wall, Fear
* **Fleece:** Major Image, Minor Illusion, Phantasmal Force, Programmed Illusion, Silent Image
* **Phosphorous**: Conjure Elemental (Fire),
Dancing Lights,
Fire Shield,
Symbol,
Wall of Fire
* **Sulfur**: Conjure Elemental (Fire),
Delayed Blast Fireball,
Fireball,
Flame Strike
* **Water**: Armor of Agathys,
Conjure Elemental (Water),
Control Water,
Create Water,
Flesh to Stone,
Ice Knife (or as ice) (EEPC) (XGtE),
Ice Storm,
Sleet Storm,
Tidal Wave (EEPC) (XGtE),
Wall of Water (EEPC) (XGtE),
Watery Sphere (EEPC) (XGtE)
* **Lodestone**: Disintegrate, Mending, Reverse Gravity
However, there are a lot of spells that don't seem to have any thematic link but share similar material components. A handful of examples:
* **Ruby**: Infernal Calling, Forbiddance, Forcecage, Simulacrum, Continual Flame
* **Iron filings or powder**: Antimagic Field, Enlarge/Reduce, Flaming Sphere, Reverse Gravity
I'd suggest that you read through the entire list, as I'm sure you'll find something useful in it.
|
38,461,449 |
My Mac app has an NSMenu whose delegate functions `validateMenuItem` and `menuWillOpen` are never called. So far none of the solutions online have helped.
It seems like I'm doing everything right:
* The menu item's selectors are in the same class.
* The class managing it inherits from NSMenuDelegate
I suppose the best way to describe my problem is to post the relevant code. Any help would be appreciated.
```
import Cocoa
class UIManager: NSObject, NSMenuDelegate {
var statusBarItem = NSStatusBar.system().statusItem(withLength: -2)
var statusBarMenu = NSMenu()
var titleMenuItem = NSMenuItem()
var descriptionMenuItem = NSMenuItem()
// ...
override init() {
super.init()
createStatusBarMenu()
}
// ...
func createStatusBarMenu() {
// Status bar icon
guard let icon = NSImage(named: "iconFrame44")
else { NSLog("Error setting status bar icon image."); return }
icon.isTemplate = true
statusBarItem.image = icon
// Create Submenu items
let viewOnRedditMenuItem = NSMenuItem(title: "View on Reddit...", action: #selector(viewOnRedditAction), keyEquivalent: "")
let saveThisImageMenuItem = NSMenuItem(title: "Save This Image...", action: #selector(saveThisImageAction), keyEquivalent: "")
// Add to title submenu
let titleSubmenu = NSMenu(title: "")
titleSubmenu.addItem(descriptionMenuItem)
titleSubmenu.addItem(NSMenuItem.separator())
titleSubmenu.addItem(viewOnRedditMenuItem)
titleSubmenu.addItem(saveThisImageMenuItem)
// Create main menu items
titleMenuItem = NSMenuItem(title: "No Wallpaperer Image", action: nil, keyEquivalent: "")
titleMenuItem.submenu = titleSubmenu
getNewWallpaperMenuItem = NSMenuItem(title: "Update Now", action: #selector(getNewWallpaperAction), keyEquivalent: "")
let preferencesMenuItem = NSMenuItem(title: "Preferences...", action: #selector(preferencesAction), keyEquivalent: "")
let quitMenuItem = NSMenuItem(title: "Quit Wallpaperer", action: #selector(quitAction), keyEquivalent: "")
// Add to main menu
let statusBarMenu = NSMenu(title: "")
statusBarMenu.addItem(titleMenuItem)
statusBarMenu.addItem(NSMenuItem.separator())
statusBarMenu.addItem(getNewWallpaperMenuItem)
statusBarMenu.addItem(NSMenuItem.separator())
statusBarMenu.addItem(preferencesMenuItem)
statusBarMenu.addItem(quitMenuItem)
statusBarItem.menu = statusBarMenu
}
// ...
// Called whenever the menu is about to show. we use it to change the menu based on the current UI mode (offline/updating/etc)
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
NSLog("Validating menu item")
if (menuItem == getNewWallpaperMenuItem) {
if wallpaperUpdater!.state == .Busy {
DispatchQueue.main.async {
self.getNewWallpaperMenuItem.title = "Updating Wallpaper..."
}
return false
} else if wallpaperUpdater!.state == .Offline {
DispatchQueue.main.async {
self.getNewWallpaperMenuItem.title = "No Internet Connection"
}
return false
} else {
DispatchQueue.main.async {
self.preferencesViewController.updateNowButton.title = "Update Now"
}
return true
}
}
return true
}
// Whenever the menu is opened, we update the submitted time
func menuWillOpen(_ menu: NSMenu) {
NSLog("Menu will open")
if !noWallpapererImageMode {
DispatchQueue.main.async {
self.descriptionMenuItem.title = "Submitted \(self.dateSimplifier(self.updateManager!.thisPost.attributes.created_utc as Date)) by \(self.updateManager!.thisPost.attributes.author) to /r/\(self.updateManager!.thisPost.attributes.subreddit)"
}
}
}
// ...
// MARK: User-initiated actions
func viewOnRedditAction() {
guard let url = URL(string: "http://www.reddit.com\(updateManager!.thisPost.permalink)")
else { NSLog("Could not convert post permalink to URL."); return }
NSWorkspace.shared().open(url)
}
// Present a save panel to let the user save the current wallpaper
func saveThisImageAction() {
DispatchQueue.main.async {
let savePanel = NSSavePanel()
savePanel.makeKeyAndOrderFront(self)
savePanel.nameFieldStringValue = self.updateManager!.thisPost.id + ".png"
let result = savePanel.runModal()
if result == NSFileHandlingPanelOKButton {
let exportedFileURL = savePanel.url!
guard let lastImagePath = UserDefaults.standard.string(forKey: "lastImagePath")
else { NSLog("Error getting last post ID from persistent storage."); return }
let imageData = try! Data(contentsOf: URL(fileURLWithPath: lastImagePath))
if (try? imageData.write(to: exportedFileURL, options: [.atomic])) == nil {
NSLog("Error saving image to user-specified folder.")
}
}
}
}
func getNewWallpaperAction() {
updateManager!.refreshAndReschedule(userInitiated: true)
}
func preferencesAction() {
preferencesWindow.makeKeyAndOrderFront(nil)
NSApp.activateIgnoringOtherApps(true)
}
func quitAction() {
NSApplication.shared().terminate(self)
}
}
```
|
2016/07/19
|
[
"https://Stackoverflow.com/questions/38461449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3517395/"
] |
`menuWillOpen:` belongs to the `NSMenuDelegate` protocol; for it to be called the menu in question needs a delegate:
```
let statusBarMenu = NSMenu(title: "")
statusBarMenu.delegate = self
```
---
`validateMenuItem:` belongs to the `NSMenuValidation` informal protocol; for it to be called the relevant menu *items* must have a `target`. The following passage is taken from Apple's [Application Menu and Pop-up List Programming Topics](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MenuList/Articles/EnablingMenuItems.html) documentation:
>
> When you use automatic menu enabling, NSMenu updates the status of every menu item whenever a user event occurs. To update the status of a menu item, NSMenu first determines the target of the item and then determines whether the target implements validateMenuItem: or validateUserInterfaceItem: (in that order).
>
>
>
```
let myMenuItem = NSMenuItem()
myMenuItem.target = self
myMenuItem.action = #selector(doSomething)
```
|
10,858,505 |
I'm trying to run around 15000 soap requests through JMeter. I have 15000 individual soap files in a folder.
I know that the [WebService(SOAP) Request](http://jmeter.apache.org/usermanual/component_reference.html#WebService%28SOAP%29_Request) component has the option to point to a folder.
But, the problem is that the files in the folder will get picked up and run randomly and a file can get run multiple times.
This is not ideal because each request has a unique correlation id and if a file get's run twice, the second run will fail due to a duplicated correlation id.
Is there anyway, I could tell jmeter to run the files only once?
Also, as certain soap requests are dependent upon other request having already run, the ability to run these in a specified order would be desirable. Is this possible?
These seem like common problems that should have already been solved. But, I can't find much on google.
Do you guys have any ideas?
|
2012/06/01
|
[
"https://Stackoverflow.com/questions/10858505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/499635/"
] |
I would use [the JSR223 Sampler](http://jmeter.apache.org/usermanual/component_reference.html#JSR223_Sampler) to run a script (e.g. Groovy) to iterate through the files in the directory and store the text of each file in a String.
See, for example, [this other answer](https://stackoverflow.com/a/9733568/62667) about using a Groovy script to iterate a list of values.
|
64,231,141 |
For tableviews, I have never had an issue with a text label persisting after a cell is reused.
When you reload a tableview after the datasource has changed, the tableviewcells get the latest data and draw themselves accordingly.
However, I am now having this problem with an attributed label. After removing an item from the datasource so that the tableviewcell gets re-used the attributed label persists in the cell. Needless to say, the leftover attributed label has nothing to do with what should be in the cell. It's just attached to the cell and won't go away.
The problem is described [here:](https://stackoverflow.com/questions/58628067/cant-reset-uilabel-attributedtext-when-a-uitableviewcell-is-reused)
In the above answer, the person said he got rid of the attributed label by setting it to nil prior to doing anything with the regular text label.
```
transactionDescriptionLabel.attributedText = nil
transactionValueLabel.attributedText = nil
Or, if I reset the attributedText first, and then reset the text, it also works:
transactionDescriptionLabel.attributedText = nil
transactionValueLabel.attributedText = nil
transactionDescriptionLabel.text = nil
transactionValueLabel.text = nil
```
Setting the attributed label to nil seems to solve the problem for me but I have never had to set a regular textLabel to nil before and am trying to get my arms around why I would have to set the attribute label to nil.
When you have an attribute label, is it necessary to set it to nil when you dequeue the cell? Or, apart from setting it to an empty string, what is the proper way to get it to disappear when you are no longer displaying it in the tableview?
Thanks in advance for any suggestions.
|
2020/10/06
|
[
"https://Stackoverflow.com/questions/64231141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6631314/"
] |
I just stumbled upon the exact same issue with `NSUnderlineStyleAttributeName`. I have to underline some text in a `UILabel` inside a `UITableViewCell` only if a condition is met. After scrolling through the cell, the label keeps reusing the attributes.
I tried several workaround, by setting `label.text` and `label.attributedText` to `nil`, removing attributes etc... nothing worked.
Finally, I found the actual solution looking at `NSAttributedString` documentation (RTFM, is always the answer):
There are enums defined for underline, and strikethrough attributes :
**NSUnderlineStyleNone = 0x00**
```
UIKIT_EXTERN NSAttributedStringKey const NSStrikethroughStyleAttributeName API_AVAILABLE(macos(10.0), ios(6.0)); // NSNumber containing integer, default 0: no strikethrough
UIKIT_EXTERN NSAttributedStringKey const NSUnderlineStyleAttributeName API_AVAILABLE(macos(10.0), ios(6.0)); // NSNumber containing integer, default 0: no underline
```
---
In conclusion, the actual way to remove underline or strikeThrough attribute is to set it to `NSUnderlineStyleNone` or `0`.
```
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:text];
[attributeString setAttributes:@{NSUnderlineStyleAttributeName:@(NSUnderlineStyleNone)} range:(NSRange){0, [attributeString length]}];
label.attributedText = attributeString;
```
|
22,934,720 |
I have a problem about create a query for text-searching starting at begining of column character. For example: I have a table 'BOOK' with a column 'TITLE'. I have 3 rows in 'BOOK' table with 'TITLE' values are: 'ANDROID APPLICATION', 'ANDROID APP DEVELOPMENT' and 'ANDROID APPLICATION PROGRAMMING'.
Now when my input is 'ANDROID APP', I need all 3 rows matched. When I type 'ANDROID APPLICATION', I need 2 rows matched: 'ANDROID APPLICATION' and 'ANDROID APPLICATION PROGRAMMING'. And when I type 'APP' or 'APPLICATION', I need no row matched (because we want to start searching at begining character of column value).
I've read the SQLite FTS document but I dont know how to use prefix query, phrase query... together with AND, OR, NOT operation to solve my problem? Anyone could give me an approriate query syntax?
|
2014/04/08
|
[
"https://Stackoverflow.com/questions/22934720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1679361/"
] |
FTS cannot search from the beginning of a column value.
(Actually, it can, but this is undocumented and not enabled in Android.)
To search from the beginning, you have to use `LIKE 'pattern%'`.
If you want this to be efficient, you have to use this with a normal table and a case-insensitive index ([COLLATE NOCASE](http://www.sqlite.org/lang_createindex.html)).
|
872,891 |
I wish to use the following sentence as the comment on a form field. I have already come up with a short-form label for the field. This text is meant to explain the field in a bit more detail:
**The country [where] you come from.**
The question is: is this "where" needed there, can be used there (optional) or cannot be used there (error).
As English is not my mother language, sometimes these things come up. Please don't be hard on me.
EDIT: I'm somewhat overwhelmed by the answers and appearing complexity of the issue. Yes, I have an input field and I wish to write a label to it. We all know the basic phrases like "I come from Australia" - "Where do you come from?". Cannot it be turned around in the form like "The country you come from"?
And if the following would be correct: "The country I live **in**"? Or I may only put the preposition to the end if it's not an independent clause but a subordinate one (terms may not be correct, forgot them): I've returned to the country I live **in**.
|
2009/05/16
|
[
"https://Stackoverflow.com/questions/872891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62830/"
] |
Where is required for written English (UK), but would commonly be dropped in spoken (colloquial) English.
|
24,019,364 |
To make changes in several files I use the following script:
```
echo search('publications.html"') | normal o<li><a href="./book_series.html">Книжные серии</a></li>
echo search('collections.html"') | d
echo search('photo.html"') | d
wq
```
Then I do `for file in *.html do; vim -e $file < script; done`
As a result a string "^Z=86=K5 A5@88" is inserted instead of "Книжные серии".
All html files as well as the script itself are utf-8 encoded, and no other problems with Cyrillic revealed.
What's going on?
Thanks in advance for any comment!
|
2014/06/03
|
[
"https://Stackoverflow.com/questions/24019364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1881022/"
] |
Probably
```
num2=`obase=16;ibase=16; echo $start_num \\+ $num | bc`
```
should be
```
num2=`echo "obase=16;ibase=16;$start_num + $num" | bc`
```
You weren't calculating hex at all.
I also suggest a simpified version like this:
```
#!/bin/zsh
step_size=10
start_num=20000000
size=64
for (( i = 0; i < 1000; i += step_size )); do
for (( j = 0; j < step_size; ++j )); do
(( temp = (i * step_size) + (j * size) ))
num=$(echo "obase=16; $temp" | bc)
echo "$num"
num2=$(echo "obase=16;ibase=16;$start_num + $num" | bc)
echo "$start_num $num $num2"
echo "****"
done
done
```
And it works both in Zsh and Bash.
```
# bash temp.zsh | head -20
0
20000000 0 20000000
****
40
20000000 40 20000040
****
80
20000000 80 20000080
****
C0
20000000 C0 200000C0
****
100
20000000 100 20000100
****
140
20000000 140 20000140
****
180
20000000 180 20000180
```
|
37,727 |
As we all know that Upanishads were written to understand Vedas. Some great scholars also said that they are the branches of Vedas. My question is related to it. Yesterday in a library, I was reading some books and then I found a book written by Dr. Surendra KR Sharma. The name of the book was in Hindi **Kya baloo ki bhit par khada hai Hindu dharma (Does Hinduism stand on the wall of sand)**. On page no. 344.
In this book he quoted Mundak Upanishad 1:1:5. I am giving the English translation by Dr. Sarvepalli Radhakrishnan.

So my question I am confused now that **Why Vedas are called inferior in Upanishads?**
|
2020/01/04
|
[
"https://hinduism.stackexchange.com/questions/37727",
"https://hinduism.stackexchange.com",
"https://hinduism.stackexchange.com/users/19001/"
] |
We should also read the next verse (1:1:6) in continuation for understanding Mundak Upanishad 1.1.5
Please [read the following](https://www.swami-krishnananda.org/mundak1/mundak1_1.html):
>
> We cannot go to the Veda directly and understand anything out of it
> unless we are proficient in these six auxiliary shastras, or
> scriptures, called śikṣā kalpo vyākaraṇaṁ niruktaṁ chando jyotiṣam.
> All these, says the great Master, together with the original Vedas—the
> **Rigveda, Yajurveda, Samaveda and Atharvaveda—\*\*should be considered \*\*\*as lower knowledge.\***
>
>
> They purify our minds and enlighten us into the mysteries of the whole
> of creation. They purify our minds because of ***the power that is
> embedded in the mantras*** and the emotional or religious awareness that
> is stimulated within us on account of the meaning that we see in the
> mantras, the blessing that we receive from the sages, who composed the
> mantras, and also the special power that is generated by the metre.
>
>
> All these put together create a religious atmosphere in the person who
> takes to the study of the Veda. It is great and grand, worth studying.
> It will lift us to the empyrean of a comprehension of values that are
> not merely physical, but ***superphysical***. Yet, it is not enough. There
> is a ‘but’ behind it. What is that greater knowledge, which is higher
> than this mentioned?
>
>
> ***Atha parā yayā tad akṣaram adhigamyate***: That is the ***higher knowledge*** with which alone can we reach the imperishable Reality. Learning is
> different from wisdom; scholarship is not the same as insight. One may
> be a learned Vedic scholar and very proficient in the performance of
> sacrifices and the invocation of gods in the heavens, but eternity is
> different from temporality.
>
>
>
All these glories of the Veda are in the
region of time, and the Eternal is timeless. What is that timeless
thing, that which is called **Imperishable**?
>
> Yat tad adreśyam, agrāhyam, agotram, avarṇam, acakṣuḥ- śrotraṁ tad
> apāṇi-padām, nityam vibhuṁ sarva-gataṁ susūkṣmaṁ tad avyayam yad
> bhūta-yonim paripaśyanti dhīrāḥ (1.1.6)
>
>
>
That great Reality is to be encountered in ***direct experience***.
* **Adreśyam**: that Reality which is not capable of perception through the eyes;
* **agrāhyam**: that which cannot be grasped with the hands;
* **avarnam**: which has no origin;
* **agotram**: which has no shape or form;
* **acakṣuḥ-śrotraṁ**: which has no sense organs like us;
* **tad apāṇi-padam**: which has no limbs such as feet, hands, etc.;
* **nityam vibhum sarva-gataṁ susūkṣmaṁ**: which is permanent, eternal, all-pervading, subtler than the subtlest;
* **tad avyayam**: which is imperishable;
* **bhūta-yonim**: which is the origin of all beings;
* **paripaśyanti dhīrāḥ**: heroes on the path of the spirit will behold that great **Reality** ***within their own selves***.
---
Mundak Upanishad 1.1.5 was saying that mere learning Vedic mantras of Vedas is not sufficient to attain the Ultimate Wisdom. That is why it is calling the Vedas as Inferior to the ***ULTIMATE KNOWLEDGE***.
|
34,102,231 |
Good evening!
I'm a beginner programmer and am finishing up my first semester of C++. Currently I'm looking a final exam review sheet my professor gave us and I just don't understand exactly what it's asking me to do. I feel like if I saw an example I would get it immediately but as is I am rather lost.
Here's the review question.
```
Problem: Given the following class definition, implement the class methods.
class CreditCard {
public:
CreditCard(string & no, string & nm, int lim, double bal = 0);
string getNumber();
string getName();
double getBalance();
int getLimit();
// Does the card have enough to buy something?
bool chargelt(double price);
private:
string number;
string name;
int limit;
double balance;
};
```
I know there isn't much context here, but let's just say in the context of this being a introductory C++ course, what is likely asking me to do/learn? I'm really not sure what "implement the class methods" means here, and while it may be something that I've seen already, more than likely it's just an issue I have with not understanding it in plain English.
And I suppose it can also be asked that: If you were to teach an beginner student with this code, what would you expect them to do with it or learn from it?
Any insight would be greatly appreciated =)
|
2015/12/05
|
[
"https://Stackoverflow.com/questions/34102231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5026229/"
] |
Strictly speaking, the C++ language doesn't have "methods". It has "member functions", and perhaps that's the terminology that you're more familiar with. But many other languages do use the term "method", so it's actually fairly common for C++ programmers to say "methods" when what they're really talking about is member functions.
The class definition shows that the class defines four member functions:
```
string getNumber();
string getName();
double getBalance();
int getLimit();
```
The definition also shows that there is a constructor:
```
CreditCard(string & no, string & nm, int lim, double bal = 0);
```
A constructor is also a type of member function, but most people don't refer to constructors as "methods". Some probably do, though.
So, the instruction "implement the class methods" means: "write the code for the member functions `getNumber()` `getName()` `getBalance()` and `getLimit()`."
It might also mean "and write the code for the constructor, `CreditCard(string & no, string & nm, int lim, double bal)`", too.
|
20,950,967 |
I know that `UNIQUE` can be used for unique value on table creating.
I read in a database management book that
>
> When we apply UNIQUE to a subquery, the
> resulting condition returns true if no row appears twice in the answer to the
> subquery that is, there are no duplicates; in particular, it returns true if the
> answer is empty.
>
>
>
I didn't see any query like that ,Is it possible?
|
2014/01/06
|
[
"https://Stackoverflow.com/questions/20950967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2040375/"
] |
`UNIQUE` is defined by *SQL92* Section 8.9: `<unique predicate> ::= UNIQUE <table subquery>` so it certainly exists but is not widely supported by vendors.
As an alternative you could use EXISTS with a HAVING COUNT.
|
37,866,905 |
I'm wondering in which format the compiled source code of an program written (in C or Rust for example) will result.
I know that the output file is a binary coded file in machine language (like every handbook and documentation explains). I thought that opening the file with an editor of my choice like VIM should show me a lot of 1s and 0s, right? But every time I search the web for that topic, I only find how to open a binary file in VI in hex (mostly using 'xxd').
Isn't there a way to see the binary file like a binary file? --> 100101101111
What is the format of an compiled program?
|
2016/06/16
|
[
"https://Stackoverflow.com/questions/37866905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2349787/"
] |
Found the solution:
```
OkHttpClient client = new OkHttpClient.Builder().proxy(proxyTest).build();
```
If we use the builder to input the proxy, it will work like a charm =D
|
19,280,494 |
```
<html>
<head></head>
<body>
<h1>Welcome to Our Website!</h1>
<hr/>
<h2>News</h2>
<h4><?=$data['title'];?></h4>
<p><?=$data['content'];?></p>
</body>
</html>
```
Can anyone tell me what's the "=" sign before variable names ? I thought of some echo alias but I couldn't find anything, thanks for your help
|
2013/10/09
|
[
"https://Stackoverflow.com/questions/19280494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2802552/"
] |
`<?=$a?>` is the shortcut for `<? echo $a ?>`, they are called "short tags" in PHP terminology
Check PHP documentation [Escaping from HTML](http://www.php.net/manual/en/language.basic-syntax.phpmode.php) example #2 3rd item, and related ini setting [short-open-tag](http://www.php.net/manual/en/ini.core.php#ini.short-open-tag)
|
576,538 |
So, a little background. I work for a company that has a number of extremely important, non-public facing websites. People's safety and livelihoods depend on these staying up. We have very little downtime, but there are always catastrophic situations that mean restoring from bare metal.
Our current setup is inadequate, but I'd like opinions on what I see as the potential options. We host everything internally on an incredibly nice vSphere setup. Right now, we have one monstrous Ubuntu instance that hosts everything--all sites, databases, assets, et cetera.
We backup every way you can imagine, and one of the benefits of the vSphere setup is that we can restore offsite if we have to, but having one massive machine means the restore time isn't insignificant.
I see two roads I can head down.
1. Simple redundancy. Migrating from this one machine to a web server, a SAN and a database server, and then either having redundant machines ready full time, or be able to spin them up quickly. This is what I'd traditionally expect to exist, but I don't know that it helps us that much. Restoring offsite means taking hours to get *all* sites back up, and it seems difficult to restore in a way that I could give preference to the most mission critical things. Internally, with vSphere, this doesn't seem like a massive advantage. But, this is fairly easy to maintain.
2. Split everything up with vSphere. Each site could be its own vSphere instance (or small set of vSphere instances to split out database/assets). This means more work maintaining a number of small servers instead of the one monolithic one, but it also means I could easily choose to restore Site A and Site B in a catastrophic situation, and leave the non-mission critical things for later. This also allows things to diverge software wise where necessary, which is both a positive thing and a negative thing.
Opinions? Am I ignoring an obvious option?
|
2014/02/18
|
[
"https://serverfault.com/questions/576538",
"https://serverfault.com",
"https://serverfault.com/users/209899/"
] |
* Leverage VMware SRM, or at least VMware Replication. It will drastically reduce the amount of time it takes you to come online in a secondary datacenter. (Hyper-V Replica and HVRM are the equivalent in the Microsoft stack.
* Separate your front-end from your back-end. It sounds like you need a web tier and a database tier.
* Invest in proper load balancing for your front end. This can mean installing and configuring a multi-site Netscalar cluster, or configuring something like HAProxy.
* Introduce redundancy in your database tier. You don't mention which DB product you're using, but many have high availability, replication, clustering, etc available. Use this.
* Make your DR site a "warm site" where you have some servers running constantly, such as database mirrors. Then you don't have to restore them in a disaster, you just make them the active node.
vSphere makes backup and recovery easier by abstracting the hardware away, but it's no substitute for tried and true HA methods when availability is critical.
There's no reason to have a single vSphere instance per-website. This doesn't gain you anything.
|
54,910,019 |
I am new to Angular and I have two collapse div elements and when I click on button1 then div element-1 need to collapse and element-2 need to be hide.
And when I click button2 then div element-2 need to collapse and element-1 need to be hide, but it's not working using below code.
```
<div class="container">
<h2>Simple Collapsible</h2>
<button type="button" class="btn btn-info" (click)="selectItem='one'" data-toggle="collapse" data-target="#demo1">Simple
collapsible</button>
<button type="button" class="btn btn-info" (click)="selectItem='two'" data-toggle="collapse" data-target="#demo2">Simple
collapsible</button>
<div [ngClass]="(selectItem=='one')?'visiable':'hide'">
<div id="demo1" class="collapse">
<h2>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</h2>
</div>
</div>
<div [ngClass]="(selectItem=='two')?'visiable':'hide'">
<div id="demo2" class="collapse">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</div>
</div>
```
<https://stackblitz.com/edit/angular5-bootstrap4-crud-device-list-simple-zxunj1?file=app%2Fapp.component.html>
|
2019/02/27
|
[
"https://Stackoverflow.com/questions/54910019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5571461/"
] |
Try using single quote marks inside the ternary
```
<div
class='@(Model.HeroBannerImageSmall ? "--imageSmall" : "--image")'
style='@(Model.isSelected ? "background-position-x:@Model.CropPositionX" % "background-position-y:@Model.CropPositionY"&; : "background-position:@Model.UniformCropPosition"&;')
background-image: url(@Model.ContentUrl)'>
</div>
```
|
42,299,099 |
In a shared `std::forward_list` is it safe for multiple threads to call `insert_after` concurrently if they are guaranteed to never call it with the same position iterator? It seems like this could be safe given that insert is guaranteed not to invalidate other iterators, and the container has no `size()` method, but maybe I'm missing something?
Edit:
I wrote a small torture test program that seems to run fine in Clang without any locking:
```
#include <forward_list>
#include <iostream>
#include <thread>
#include <vector>
using List = std::forward_list< int >;
using It = List::const_iterator;
void insertAndBranch (List& list, It it, int depth)
{
if (depth-- > 0) {
It newIt = list.insert_after (it, depth);
std::thread thread0 ([&]{ insertAndBranch (list, it, depth); });
std::thread thread1 ([&]{ insertAndBranch (list, newIt, depth); });
thread0.join();
thread1.join();
}
}
int main()
{
List list;
insertAndBranch (list, list.before_begin(), 8);
std::vector< It > its;
for (It it = list.begin(); it != list.end(); ++it) {
its.push_back (it);
}
std::vector< std::thread > threads;
for (It it : its) {
threads.emplace_back ([&]{ list.insert_after (it, -1); });
}
for (std::thread& thread : threads) {
thread.join();
}
for (int i : list) {
std::cout << i << ' ';
}
std::cout << '\n';
}
```
I know this doesn't prove anything but it makes me hopeful that this is safe. I'm not sure I can use it without some confirmation from the standard though.
|
2017/02/17
|
[
"https://Stackoverflow.com/questions/42299099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683918/"
] |
>
> In a shared `std::list` is it safe for multiple threads to call insert
> concurrently if they are guaranteed to never call it with the same
> position iterator?
>
>
>
No. It wouldn't be safe...(No matter what).
Inserting into a `std::list` will require access to the `previous node` and `next node` to the iterator position, and the `size` of the list.
Even if the positions are far off each other, the simple fact that [`std::list::size()`](http://en.cppreference.com/w/cpp/container/list/size) is required to be *constant time* (C++11). It means each insertion will update `std::list::size()`.
---
Edit:
>
> In a shared `std::forward_list` is it safe for multiple threads to
> call insert\_after concurrently if they are guaranteed to never call it
> with the same position iterator?
>
>
>
It's not safe. and not recommended. No STL container was designed with thread safety.
---
Anyway, lets assume some basic guarantees, lets assume a very simple version of `std::forward_list`: `insert_after` modifies the node pointed to by your iterator so that the node now points to the newly inserted node, while the newly inserted node points to the next node. So its only going to be "safe" if the iterators are at least two nodes away from each other and your allocator is thread-safe.
Illustration:
```
Initial Forward_list
A -> B -> C -> D -> E
Insert K after C
A -> B -> C x D -> E
\ /
K
```
As you can see, `C` is read and modified. `D` may be read, while `K` is inserted.
---
As to why I said "at least two nodes away", lets take the case of one node away: Assuming two threads want to insert `K` after `C`, and `M` after `D` respectively:
```
Initial Forward_list
A -> B -> C -> D -> E
Insert K after C
A -> B -> C x D x E
\ / \ /
K M
```
From [cppreference](http://en.cppreference.com/w/cpp/language/memory_model#Threads_and_data_races):
>
> When an evaluation of an expression writes to a memory location and
> another evaluation reads or modifies the same memory location, the
> expressions are said to conflict.
>
>
>
|
50,574,593 |
I am trying to do a simple thing , navigate to an external url
```
<a href="http://18.217.228.108/angularapp1/book/"> Class Books </a>
```
However I am getting a 404 because the Http// portion is being deleted I am not sure if this is an mvc thing or html thing. Here is link <http://18.217.228.108/angularapp1>.
Here is a link to a screen shot of me accessing url
<https://gyazo.com/455b01f1ceded24f9b4ce6c58b0e10e1>
|
2018/05/28
|
[
"https://Stackoverflow.com/questions/50574593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8066170/"
] |
I do not agree to the formula "after certain number of words".
Note that the first target line has 4 words, whereas remaining 2 have
5 words each.
Actually you need to replace each comma and following sequence of
spaces (if any) with a comma and `\n`.
So the intuitive way to do it is:
```
$x =~ s/,\s*/,\n/g;
```
|
196 |
I have been working on dynamic programming for some time. The canonical way to evaluate a dynamic programming recursion is by creating a table of all necessary values and filling it row by row. See for example [Cormen, Leiserson et al: "Introduction to Algorithms"](http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&tid=11866) for an introduction.
I focus on the table-based computation scheme in two dimensions (row-by-row filling) and investigate the structure of cell dependencies, i.e. which cells need to be done before another can be computed. We denote with $\Gamma(\mathbf{i})$ the set of indices of cells the cell $\mathbf{i}$ depends on. Note that $\Gamma$ needs to be cycle-free.
I abstract from the actual function that is computed and concentrate on its recursive structure. Formally, I consider a recurrrence $d$ to be *dynamic programming* if it has the form
$\qquad d(\mathbf{i}) = f(\mathbf{i}, \widetilde{\Gamma}\_d(\mathbf{i}))$
with $\mathbf{i} \in [0\dots m] \times [0\dots n]$, $\widetilde{\Gamma}\_d(\mathbf{i}) = \{(\mathbf{j},d(\mathbf{j})) \mid \mathbf{j} \in \Gamma\_d(\mathbf{i}) \}$ and $f$ some (computable) function that does not use $d$ other than via $\widetilde{\Gamma}\_d$.
When restricting the granularity of $\Gamma\_d$ to rough areas (to the left, top-left, top, top-right, ... of the current cell) one observes that there are essentially three cases (up to symmetries and rotation) of valid dynamic programming recursions that inform how the table can be filled:

The red areas denote (overapproximations of) $\Gamma$. Cases one and two admit subsets, case three is the worst case (up to index transformation). Note that it is not strictly required that the *whole* red areas are covered by $\Gamma$; *some* cells in every red part of the table are sufficient to paint it red. White areas are explictly required to *not* contain any required cells.
Examples for case one are [edit distance](https://en.wikipedia.org/wiki/Edit_distance) and [longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution), case two applies to [Bellman & Ford](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) and [CYK](https://en.wikipedia.org/wiki/CYK). Less obvious examples include such that work on the diagonals rather than rows (or columns) as they can be rotated to fit the proposed cases; see [Joe's answer](https://cs.stackexchange.com/a/211/98) for an example.
I have no (natural) example for case three, though! So my question is: What are examples for case three dynamic programming recursions/problems?
|
2012/03/10
|
[
"https://cs.stackexchange.com/questions/196",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/98/"
] |
There are plenty of other examples of dynamic programming algorithms that don't fit your pattern at all.
* The longest increasing subsequence problem requires only a one-dimensional table.
* There are several natural dynamic programming algorithms whose tables require three or even more dimensions. For example: Find the maximum-area white rectangle in a bitmap. The natural dynamic programming algorithm uses a three-dimensional table.
* But most importantly, **dynamic programming isn't about tables**; it's about unwinding recursion. There are lots of natural dynamic programming algorithms where the data structure used to store intermediate results is not an array, because the recurrence being unwound isn't over a range of integers. Two easy examples are finding the largest independent set of vertices in a tree, and finding the largest common subtree of two trees. A more complex example is the $(1+\epsilon)$-approximation algorithm for the Euclidean traveling salesman problem by Arora and Mitchell.
|
28,872,375 |
```
SQL> desc invoices
Name Null? Type
----------------------------------------- -------- ----------------------------
INVOICE_ID NOT NULL NUMBER(6)
COMPANY_ID NUMBER(6)
STUDENT_ID NUMBER(6)
BILLING_DATE DATE
SQL>
```
I would like to insert some sample data into this table. The `company_id` and `student_id` are foreign keys. This is what I'am entering:
`INSERT INTO invoices
VALUES (SEQ_INVOICE.NEXTVAL,[what1],[what2],SYSDATE);`
I don't know what I am supposed to put in the what1 and what2
```
SQL> desc companies
Name Null? Type
----------------------------------------- -------- ----------------------------
COMPANY_ID NOT NULL NUMBER(6)
COMPANY_NAME VARCHAR2(30)
ADDRESS VARCHAR2(128)
CONTACT_NO VARCHAR2(11)
NO_OF_EMP NUMBER(10)
SQL>
SQL> desc students
Name Null? Type
----------------------------------------- -------- ----------------------------
STUDENT_ID NOT NULL NUMBER(6)
ST_FNAME VARCHAR2(16)
ST_SNAME VARCHAR2(16)
ADDRESS VARCHAR2(128)
DOB DATE
SQL>
```
|
2015/03/05
|
[
"https://Stackoverflow.com/questions/28872375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4592364/"
] |
you have to enter an existed `STUDENT_ID` from `students` table and an existed `COMPANY_ID` from `compaies` table to invoices.
Consider you have data like next
```
COMPANY_ID COMPANY_NAME ADDRESS CONTACT_NO NO_OF_EMP
----------- ------------ -------- ---------- ---------
1 Blah LLC blah st. 123456 100
2 My Company My Street 987654321 50
```
and
```
STUDENT_ID ST_FNAME ST_SNAME ADDRESS DOB
----------- --------- --------- -------- ------------
11 Jim Carrey .... 1900.25.04
22 Jack Sparrow Carrib st. 1700.30.08
```
then you can use `1` or `2` as `COMPANY_ID` (in your query [what1]) and `11` or `22` as `STUDENT_ID` (in your query [what2])
|
20,319,813 |
In my for loop, my code generates a list like this one:
```
list([0.0,0.0]/sum([0.0,0.0]))
```
The loop generates all sort of other number vectors but it also generates `[nan,nan]`, and to avoid it I tried to put in a conditional to prevent it like the one below, but it doesn't return true.
```
nan in list([0.0,0.0]/sum([0.0,0.0]))
>>> False
```
Shouldn't it return true?

Libraries I've loaded:
```
import PerformanceAnalytics as perf
import DataAnalyticsHelpers
import DataHelpers as data
import OptimizationHelpers as optim
from matplotlib.pylab import *
from pandas.io.data import DataReader
from datetime import datetime,date,time
import tradingWithPython as twp
import tradingWithPython.lib.yahooFinance as data_downloader # used to get data from yahoo finance
import pandas as pd # as always.
import numpy as np
import zipline as zp
from scipy.optimize import minimize
from itertools import product, combinations
import time
from math import isnan
```
|
2013/12/02
|
[
"https://Stackoverflow.com/questions/20319813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1610626/"
] |
I think this makes sense because of your pulling `numpy` into scope indirectly via the star import.
```
>>> import numpy as np
>>> [0.0,0.0]/0
Traceback (most recent call last):
File "<ipython-input-3-aae9e30b3430>", line 1, in <module>
[0.0,0.0]/0
TypeError: unsupported operand type(s) for /: 'list' and 'int'
>>> [0.0,0.0]/np.float64(0)
array([ nan, nan])
```
When you did
```
from matplotlib.pylab import *
```
it pulled in `numpy.sum`:
```
>>> from matplotlib.pylab import *
>>> sum is np.sum
True
>>> [0.0,0.0]/sum([0.0, 0.0])
array([ nan, nan])
```
You can test that **this** `nan` object (`nan` isn't unique in general) is in a list via identity, but if you try it in an `array` it seems to test via equality, and `nan != nan`:
```
>>> nan == nan
False
>>> nan == nan, nan is nan
(False, True)
>>> nan in [nan]
True
>>> nan in np.array([nan])
False
```
You could use `np.isnan`:
```
>>> np.isnan([nan, nan])
array([ True, True], dtype=bool)
>>> np.isnan([nan, nan]).any()
True
```
|
109,317 |
I have been reading quite a bit in order to make the following choice: which path-finding solution should one implement in a game where the world proceduraly generated, of really large dimensions?
Here is how I see the main solutions and their pros/cons:
1) grid-based path-finding - this is the only option that would not require any pre-processing, which fits well. However, as the world expands, memory used grows exponentially up to insane levels. This can be handled in terms of processing paths, trough solutions such as the Block A\* or Subgoal A\* algorithms. However, the memory usage is the problem difficult to circumvent;
2) navmesh - this would be lovely to have, due to its precision, fast path calculation and low memory usage. However, it can take an obscene pre-processing time.
3) visibility graph - this option also needs high pre-processing time, although it can be lessened by the use of fast pre-processing algorithms. Then, path calculation is generally fast too. But memory usage can get even more insane than grid-based depending on the configuration of the procedural world.
So, what would be best approach (others not present in this list are also welcome) for such a situation? Are there techniques or tricks that can be used to handle procedural infinite-like worlds?
Suggestions, ideas and references are all welcome.
EDIT:
Just to give more details, one should see the application I am talking about as a very very large office level, where rooms are generated prodecuraly. The algorithm works like the following. First, rooms are placed. Next, walls. Then the doors and later the furniture/obstacles that go in each room. So, the environment can get really huge and with lots of objects, since new rooms are generated once the players approaches the boundary of the already generated area. It means that there will be not large open areas without obstacles.
|
2015/10/06
|
[
"https://gamedev.stackexchange.com/questions/109317",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/72314/"
] |
Given that the rooms are procedural built, portals created and then populated, I have a couple of ideas.
A\* works really well on navigation meshes, and works hierarchically as well. I would consider building a pathfinding system that works at two levels - first, the room by room level, and second within each room, from portal to portal. I think you can do this during generation at an affordable rate. You only need to path from room to room once you enter it, so it's very affordable from a memory/cpu cost.
High level A\* can be done by creating a graph of each portal and room - a room is the node, and the 'path' or edge is the portal to another room. The cost of traversal has some options - it can be from the centre point of the room to the centre point of the other room, for example. Or you might want to make specific edges from portal to portal with real distances, which is more useful, I suspect. This let's you do high level pathfinding from room A to room B. Doors can be opened and closed, enabling or disabling specific paths, which is nice for certain types of game. Because it's room/portal based it should be pretty easy and affordable to calculate - just distance calculations and graph book keeping. The great thing about this is it reduces the pathfinding memory costs dramatically in large environments since you are doing only the room-to-room finding.
The harder part will be the low level A\* because it should be polygonal navigation mesh. If each room is square, you can start with a polygon. When you place obstacles, subtract the area occupied from the polygon, making holes in it. When it's all finished you'll want to tesselate it into triangles again, building up the graph. I don't think this is as slow as you think. The difficult part is performing the polygon hole cutting, which requires a good amount of book keeping on that kind of stuff, but it is well documented within half-edge structures, and established computer science graphics books. You can also perform this generation lazily, in a background graph, as you don't actual need the A\* results of this level until someone is in the room - the high level takes care of basic path planning for you. Someone may never even enter the room in a run, because the high level A\* never leads them there.
I know I have glossed over the low level navigation mesh generation, but I think it's one of those things you set your mind to and solve and then it's done. There are a bunch of libraries out there like CGAL (<http://www.cgal.org>) and others that can do this stuff, but really to get it going fast you might need to write it yourself so you only have the things you need.
Alternatively, you could make each room be a grid, and the obstacles fill up parts of the grid, and then do all the standard grid smoothing algorithms, but I like navmesh data as it is small and fast.
Hope that makes some sense.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.