qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
7,135,840 | I've been trying to parallelize a nested loop as shown here:
<http://pastebin.com/nkictYsw>
I'm comparing the execution time of a sequential version and parallelized version of this code, but the sequential version always seems to have shorter execution times with a variety of inputs?
The inputs to the program are:
* numParticles (loop index)
* timeStep (not important, value doesn't change)
* numTimeSteps (loop index)
* numThreads (number of threads to be used)
I've looked around the web and tried some things out (nowait) and nothing really changed. I'm pretty sure the parallel code is correct because I checked the outputs. Is there something wrong I'm doing here?
EDIT: Also, it seems that you can't use the reduction clause on C structures?
EDIT2: Working on gcc on linux with 2 core cpu. I have tried running this with values as high as numParticles = 40 and numTimeSteps = 100000. Maybe I should try higher?
Thanks | 2011/08/21 | [
"https://Stackoverflow.com/questions/7135840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/830854/"
] | If you want to accomplish something like this, you aren't going to be able to use `vector<foo>` to actually be in charge of the `foo` objects themselves. It looks to me like your sub-vector of `foo*`'s must be actually pointing to the memory that the `vector<foo>` is in charge of. (Thus, that's why you still see the additional pointer at the end that points to `d`, and you still have a length of 4.)
Seems to me, what you really want to do is use two `vector<foo*>`'s, and manually create the objects that are being stored in the first rather than having the vector itself in charge of the objects. Then have your second `vector<foo*>` simply copy the pointers to the objects you've created. That way when you delete an item from the first `vector<foo*>`, it will only remove its copy of the pointer, and your second `vector<foo*>` will be unaffected.
Think of it without the vector involved:
```
// create the initial storage for all the foo
foo* fooarray = new foo[foo_count];
// create all the foos for the array
for (int i=0; i < foo_count; ++i)
fooarray = new foo();
// get a pointer to a subset of foo
foo* foo_subset_pointer = &fooarray[10];
// make a list of a subset of the fooarray pointers
foo* foo_subset_list = new foo[10];
for (int i=0; i < 10; ++i)
foo_subset_list = fooarray[i];
```
so, now when you remove an element from fooarray:
```
// remove fooarray[3]
delete fooarray[3];
for (int i=4; i < 20; ++i)
fooarray[i-1] = fooarray[i];
```
`foo_subset_pointer` will have have its original item 3 removed, since it was just a pointer to the existing array. (And if you access `foo_subset_pointer[19]`, it will still have a pointer to the same thing as `foo_subset_pointer[18]`, because the items weren't zeroed...)
But worse, `foo_subset_list[3]` still points to the original location: but it's invalid because it was deleted! This is why you don't want to have the vector being in charge of your list items when you're dealing with a subset that you want to keep around.
Instead, it sounds like you want your first vector to only do the removal of the item (the `for` loop above) but not the `delete`. In this case, it leaves your `foo_subset_list[3]` untouched and still pointing to a valid `foo`. The additional difficulty is that you now have to be sure to do the `delete foo_subset_list[3];` at some point in the future. But it allows you to have the behavior that seems to be what you wanted. | When an object in a `vector` is removed, all the objects at larger indices in the `vector` are moved down to close up the "hole". Pointers to any of those objects become invalid. The only way to detect the situation is not to get into that situation in the first place -- don't store pointers to objects in non-`const` `vector`s, because it's dangerous. |
1,191 | When I run pdfLaTeX, I get very verbose output:
```
(/usr/local/texlive/2008/texmf-dist/tex/generic/pgf/frontendlayer/tikz/librarie
s/tikzlibrarycalc.code.tex)
...
```
Is there a script to soak up all the verbose output and allow the important stuff to pass through, like errors, overfull hboxes, and so on?
Also, is there a reason why it sends a hard return to the console for lines longer than 79 characters? | 2010/08/05 | [
"https://tex.stackexchange.com/questions/1191",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/512/"
] | This is what the [silence](http://ctan.org/pkg/silence) package is intended to help with. | In order to neatly format the output, I created my own solution: [pydflatex](https://github.com/olivierverdier/pydflatex).
You would compile a file with
```
pydflatex myfile.tex
```
And get an output along the lines of

On top of giving a neat, condensed output, it will also hide the auxilliary files, so as not to clutter your folder.
**Edit** It is now also possible to run
```
pydflatex -l file.tex
```
which will parse an existing log without typesetting. |
58,116,823 | I don't know whether this is only a matter of style.
There are at least 2 ways of handling async actions:
### subscribe after `dispatch`
```ts
// action is being dispatched and subscribed
this.store.dispatch(new LoadCustomer(customerId)).subscribe(); // <-- subscribe
```
In the State:
```ts
@Action(LoadCustomer)
loadCustomer(context: StateContext<CustomerStateModel>,
customerId: string) {
return this.customerService.loadById(customerId).pipe(
tap(c => context.setState(produce(context.getState(), draft => {
draft.byId[customerId] = c;
})))
); // <-- NO subscribe here, just return the Observable
}
```
### subscribe in `@Action` handler
```ts
// action is being dispatched
this.store.dispatch(new LoadCustomer(customerId)); // <-- no subscribe
```
In the State:
```ts
@Action(LoadCustomer)
loadCustomer(context: StateContext<CustomerStateModel>,
customerId: string) {
this.customerService.loadById(customerId).pipe(
tap(c => context.setState(produce(context.getState(), draft => {
draft.byId[customerId] = c;
})))
).subscribe(); // <-- subscribe is done in action handler
}
```
### Question
Which one is better and why?
### Edit / Hint
It turned out that the core issue leading to this question was following:
We had an HttpInterceptor caching "too much" which looked liked if some actions had not been executed. In fact the subscription is already handled correctly by NGXS, but in our case no effect was visible (no request in the network tab).
In our cases the `.subscribe()` calls could be eliminated. Only where we need to wait for an action to finish, a subscription after the dispatch makes sense. | 2019/09/26 | [
"https://Stackoverflow.com/questions/58116823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2176962/"
] | I think it is somewhat a matter of style, but I'd say (from my usage of NGXS) this is most typical:
On dispatch do this, and only subscribe here if there's some post-action you want to do.
`this.store.dispatch(new LoadCustomer(customerId));`
And in the state, the option 1 approach, to return the `Observable` to the NGXS framework and let it handle the subscription itself (see from the [docs](https://www.ngxs.io/concepts/state#async-actions) re: action handling).
[](https://i.stack.imgur.com/Udi3y.png) | Approach number one, as there will be only one subscription and the source component/service will be able to react to it. Subscribing in `@Action` means that whenever the `@Action` handled is called then new subscription will be created. |
23,595,858 | I'm trying to configure a build system for Scala with SublimeText, but I am having some difficulty. I have tried both of the following:
```
{
"shell_cmd": "scala",
"working_dir": "${project_path:${folder}}",
"selector": "source.scala"
}
{
"cmd": ["/path/to/bin/scala", "$file_name"],
"working_dir": "${project_path:${folder}}",
"selector": "source.scala",
"shell": true
}
```
Both of these attempts produce the same failed output - it seems to start up the interactive Scala shell rather than running my script. Any advice? | 2014/05/11 | [
"https://Stackoverflow.com/questions/23595858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506971/"
] | The answer that worked turned out to be very close to the second answer - apparently I'm not supposed to open up a new shell. If someone can clarify when to set `"shell": true` in the comments, that would be really helpful.
```
{
"cmd": ["/path/to/bin/scala", "$file_name"],
"working_dir": "${project_path:${folder}}",
"selector": "source.scala"
}
``` | This works for me:
```
{
"cmd": ["scala", "$file"],
"working_dir": "${project_path:${folder}}",
"selector": "source.scala",
"shell": true
}
```
given you set the system PATH thing:
```
Variable: %PATH%
Value: C:\Program Files (x86)\scala\bin
``` |
5,190,539 | Is there an equivalent to `app.config` for libraries (DLLs)? If not, what is the easiest way to store configuration settings that are specific to a library? Please consider that the library might be used in different applications. | 2011/03/04 | [
"https://Stackoverflow.com/questions/5190539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/385387/"
] | You **can** have separate configuration file, but you'll have to read it "manually", the `ConfigurationManager.AppSettings["key"]` will read only the config of the running assembly.
Assuming you're using Visual Studio as your IDE, you can right click the desired project → Add → New item → Application Configuration File
[](https://i.stack.imgur.com/CROdR.png) [](https://i.stack.imgur.com/igmeM.png)
This will add `App.config` to the project folder, put your settings in there under `<appSettings>` section. In case you're not using Visual Studio and adding the file manually, make sure to give it such name: *DllName.dll.config*, otherwise the below code won't work properly.
Now to read from this file have such function:
```
string GetAppSetting(Configuration config, string key)
{
KeyValueConfigurationElement element = config.AppSettings.Settings[key];
if (element != null)
{
string value = element.Value;
if (!string.IsNullOrEmpty(value))
return value;
}
return string.Empty;
}
```
And to use it:
```
Configuration config = null;
string exeConfigPath = this.GetType().Assembly.Location;
try
{
config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
}
catch (Exception ex)
{
//handle errror here.. means DLL has no sattelite configuration file.
}
if (config != null)
{
string myValue = GetAppSetting(config, "myKey");
...
}
```
You'll also have to add reference to System.Configuration namespace in order to have the ConfigurationManager class available.
When building the project, in addition to the DLL you'll have `DllName.dll.config` file as well, that's the file you have to publish with the DLL itself.
Within the VS project, you should set the .config file "Copy to output directory" setting to "Always Copy".
The above is basic sample code, for those interested in a full scale example, please refer to [this other answer](//stackoverflow.com/a/41993955/447356). | Why not to use:
* `[ProjectNamespace].Properties.Settings.Default.[KeyProperty]` for C#
* `My.Settings.[KeyProperty]` for VB.NET
You just have to update visually those properties at design-time through:
`[Solution Project]->Properties->Settings` |
4,001,576 | The question is as follows:
Give an example of a non-nilpotent linear transformation for some vector space with the following property, for every $v \in V$ there is an $n$ for which $A^n(v)=0$.
I really don't know how such a matrix would exist, since you can find a basis for this vector space, let's say $v\_1,v\_2,...$. Then we know for every $v\_i$ there is an $n\_i$ for which $A^{n\_i}(v\_i)=0$.
Then write $v$ as $\sum\_{i}^{k} \alpha\_i v\_i$ and consider $A^{\sum\_{i}^{k} n\_i} (v)$, which gives $\sum\_{i}^{k} \alpha\_i \cdot A^{\sum\_{i}^{k} n\_i} (v\_i)$ which should give zero for every $v\_i$.
Maybe they meant an infinite vector space, however I doubt it since we never touched the infinite vector spaces in our algebra course.
Then you can consider the basis $B=v\_1,v\_2, ...$ an infinite basis over some field and let $A(v\_1)=0$ and $A(v\_i)=v\_{i-1}$ then since there exist online finite amount of non-zero coordinates then there must be an $n$ for which $A^n(v)=0$, however the transformation is not nilpotent.
So my question is whether it's really true that such a transformation doesn't exist for finite-dimensional vector spaces. | 2021/01/27 | [
"https://math.stackexchange.com/questions/4001576",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/740090/"
] | Let $V$ be the space of all polynomial functions from $\Bbb R$ into $\Bbb R$ and let $A\bigl(p(x)\bigr)=p'(x)$. If $\deg p(x)=n$, then $A^{n+1}\bigl(p(x)\bigr)=0$, but $A$ is not nilpotent: for any $n\in\Bbb N$,$$A\left(x^{n+1}\right)=(n+1)!\ne0.$$ | The vector space is neceessarily infinite dimensional. Consider the space of all real sequences $(x\_n)$ such that $x\_n=0$ for $n$ sufficiently large. Define $A(x\_n)=(x\_2,x\_3,..)$. If $x\_n=0$ for $n>N$ then $A^{N}(x\_n)=0$. But, for any $N$, $Ae\_{N+1} \neq 0$ so $A$ is not nilpotent. [$e\_i$ is the sequence which has $1$ in the $i-$th coordinate and $0$ elsewhere]. |
648,066 | I'm designing an MCU-based electronic device and have a BOM of the major components (power regulators, MCU, serial communication ICs, etc.).
Is there any piece of software out there that can convert the suggested circuit designs found within an ICs datasheet to a schematic file? I realize it's the engineer's job to design the schematic, but 98% of the circuitry I'm putting on paper is literally the recommended design within the datasheet. Seems like a waste of time to copy over the manufacturer's circuit schematic from PDF to a KiCad schematic file; wire by wire, and components by component.
Ideally I'd want to select all the major components, then let a piece of software perform all the recommended connections (caps on power supplies, resistors on com lines, etc.). | 2022/12/29 | [
"https://electronics.stackexchange.com/questions/648066",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/235938/"
] | >
> Seems like a waste of time to copy over the manufacturer’s circuit schematic from PDF to a KiCad schematic file; wire by wire, and components by component.
>
>
>
You'll spend so much time doing everything else in the design process, that this time should be negligible. Invest time in learning KiCad well enough to be highly productive in it. "Copying" those schematics should take almost no time compared to the time needed to add the component symbols to your project library in KiCad. And even *that* should go very quickly once you've done it a couple dozen - hundred times.
If you're not productive enough in KiCad, then that's the problem to fix. The schematics would look like utter crap anyway if you just copied and "assembled them" from whatever package the evaluation kit designers had each standard application circuit designed in.
After the design work is done, then for most parts, the time will be spent not connecting them on the schematic, but doing all the bureaucracy: selecting footprints, manufacturer part numbers, hunting for 3D models especially for mechanical and connectors, and finally doing basic 3D modeling of parts no models can be found of. This is a big problem for legacy parts that have been around for a long time - often the manufacturer has no 3D CAD documentation for them, and thus can't easily generate a 3D model. There are 3D modelling services that will make a part model for a modest fee, but there's a wide variation in the quality of such models, and usually I find that it's faster to just do it myself - the model will capture what's important in my application. Now, **of course** it'll be excruciatingly slow when you do it the first time. Just keep at it and it'll soon enough become a botherless and quick process.
Board design isn't just electrical: you really want to generate a STEP file of the board assembly that the mechanical/thermal people can drop into their CAD to design enclosures, cooling, etc.
The way I've tackled this to have a "Catalog" schematic symbol library that has one part per each physical part that's orderable. Say, a particular capacitor part number has its symbol, and that symbol has data about the footprint, manufacturer part number, distributor part numbers, budgetary cost, etc. You only do it once per part, and then you can reuse the part in many designs. Often, for example, you'd hunt down a "good" 100nF 0603 decoupling capacitor - good meaning it's in huge quantities in stock at various distributors, and is priced well. There's no need to repeat that job. Just look for a C\_100nF\_0603\_X7R\_MMMMMMMMM in your library. If you've done the job right, the BOM will contain information that a board assembly house can use directly, the corresponding footprint will have a suitable 3D model of the part, etc. This speeds things up tremendously if you're doing many designs with similar parts. And even for larger, unique designs, it prevents many mistakes.
There's also the potential to integrate auxiliary data into the symbol library - data that transfers to the PCB layout, and can be used - via variable substitution - to provide annotations on the FAB drawings. These annotations would be part specific, and perhaps easy to forget otherwise. You can actually enter them in the schematic symbol's data field, refer to them in the footprint's FAB layer, and finally tweak the location of the annotation on the FAB layer in the PCB you're working on. Those can be e.g. assembly notes for parts that require additional information, etc.
Eventually, you'll probably want to figure out useful KiCad plugins/extensions that integrate/update data from distributors, such as cost, and further you'll try to adapt those for your own workflow. When using KiCad, learning a bit of Python and wxWidgets goes a long way to boosting your productivity. And those are transferable skills!
Some symbols have multiple variants so they can be properly represented on the schematic in a way that makes sense. E.g. a quad line driver may be best represented as a single symbol with 4 input and 4 output pins in some parts of the schematic, while in others it makes sense to have 4 sub-symbols in the part, one for each line driver channel, with 2 pins each.
For connectors: I usually make the connector pinout a part of the **symbol** - that way the schematic can be more readable, and the connector can be logically split into sub-symbols that capture signal groups that then lay out nicely on the schematic. There's also less potential for mistakes, since the same specific connector symbol can be aliased to mating connectors (e.g. male/female), ensuring the clerical mistakes in matching the pinouts are impossible due to the very process itself. And it's also impossible to mis-label the pin on the schematic: the signal name is the name of the pin in the connector symbol. It's much easier to verify that they match. Furthermore, it takes a very simple ERC script to enumerate all connector pins in the schematic, and ensure that the net names connected to them *match* the pin names. That way, if you connect, say net labeled CLK to a pin named BUSY, the script will pick it up. KiCad file formats are easy to work with for custom tooling, and there's plenty of Python glue out there to make it happen.
After decades of work, I find that I am much happier at the end of the day if the schematic is beautiful and not just a glorified netlist that has some symbols thrown in.
It's the kind of a setup that then makes the schematic and subsequent layout very fast: all the drudgery is done ahead of time, so if you put a part on the schematic, you know it'll appear on the PCB layout with the right footprint, on the 3D PCB view with the right model, on the BOM with the correct unambiguous part number, etc.
This also prevents mistakes in the often inevitable "race to FAB", where time pressure may induce unnecessary stress. If all the bureaucratic work is done ahead of time, then you can usually trust that a schematic that passes ERC, a layout that passes DRC, will give you a manufacturable and correct assembly back. Without, say, a couple of 10k resistors being populated with 1k resistors - easy mistake to make if your process is manual and there's time pressure! | The schematic itself is the least of your worries.
Even if it a tool existed to take a graphical schematic and translate it to a CAD one, the visual representation lacks other information essential to the design: complete part numbers, physical footprints, operating parameters (voltage, current, temperature, etc.)
Not only that, the reference designators need to merge with the rest of your design.
That said, manufacturers sometimes offer reference designs in CAD form. This makes the process much easier. |
24,576,009 | I m using listfragment in my app. When the data fails to load I call setEmptyText with the failure message. This works fine on 4 inch phones but on 7 and 10 inch phones the size of the empty textview is very small and hard to read.
4 inch empty text view

7 inch empty text view

How can I increase the size of empty text view? | 2014/07/04 | [
"https://Stackoverflow.com/questions/24576009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203565/"
] | Here is a drop in extension for ListFragment which changes the size (and color) of the empty view programmatically:
```
/**
* Abstract list fragment that does customizations of the list style.
*/
public abstract class LoggingListFragment extends ListFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
TextView emptyView = null;
View possibleEmptyView = view.findViewById(0x00ff0001);
if (possibleEmptyView instanceof TextView) {
emptyView = (TextView) possibleEmptyView;
}
if (emptyView == null) {
possibleEmptyView = getListView().getEmptyView();
if (possibleEmptyView instanceof TextView) {
emptyView = (TextView) possibleEmptyView;
}
}
if (emptyView != null) {
emptyView.setTextColor(getActivity().getResources().getColor(R.color.list_subtitle_normal));
emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
}
return view;
}
}
``` | 1. Create different folders like res/values-sw720dp,res/values-sw600dp,
res/values-v11.
2. Create dimen.xml with different font size of different screen size.
3. Use values/dimen.xml:
<resources>
<dimen name="normal\_font">16sp </dimen>
</resources>
4.Use in your widget in your xml.
android:textSize="@dimen/normal\_font |
41,410,490 | I have been trying to center the very bottom row of blue cards. As you can see it is not:
[](https://i.stack.imgur.com/van67.png)
So far I have tried `text-align`, `width: 100%;`, and `margin-left: auto; margin right: auto;`
But it will just not center! Is there something I am obviously executing poorly/wrong?
HTML:
```
<!------------------- SKILLS --------------------->
<section>
<div class="container-fluid skillset">
<div class="row">
<div class="col-xs-12">
<h3>Skills</h3>
</div>
</div>
<div class="row lang">
<div class="col-md-3">
<div class="card card-outline-primary text-xs-center">
<div class="card-block">
<blockquote class="card-blockquote">
<p><i class="fa fa-html5" aria-hidden="true"></i></p>
</blockquote>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card card-outline-primary text-xs-center">
<div class="card-block">
<blockquote class="card-blockquote">
<p><i class="fa fa-css3" aria-hidden="true"></i></p>
</blockquote>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card card-outline-primary text-xs-center">
<div class="card-block">
<blockquote class="card-blockquote">
<p><i class="fa fa-twitter" aria-hidden="true"></i></p>
</blockquote>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card card-outline-primary text-xs-center">
<div class="card-block">
<blockquote class="card-blockquote">
<p><i class="fa fa-database" aria-hidden="true"></i></p>
</blockquote>
</div>
</div>
</div>
</div>
</div>
</section>
```
CSS:
```
/* -------------------------------------
SKILLS
--------------------------------------*/
.card {
width: 100px;
height: auto;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
transition: 0.3s;
border-radius: 5px; /* 5px rounded corners */
/* margin-left: 30%; */
}
/* Add rounded corners to the top left and the top right corner of the image */
img {
border-radius: 5px 5px 0 0;
}
/* On mouse-over, add a deeper shadow */
.card:hover {
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.8);
}
.lang {
text-align: center;
}
``` | 2016/12/31 | [
"https://Stackoverflow.com/questions/41410490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7128870/"
] | Add `display: inline-block;` to `.col-md-3`.
<https://jsfiddle.net/q6hpqob1/>
```css
.card {
width: 100px;
height: auto;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
transition: 0.3s;
border-radius: 5px; /* 5px rounded corners */
/* margin-left: 30%; */
}
/* Add rounded corners to the top left and the top right corner of the image */
img {
border-radius: 5px 5px 0 0;
}
/* On mouse-over, add a deeper shadow */
.card:hover {
box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.8);
}
.lang {
text-align: center;
}
.col-md-3 {
height: 50px;
width: 50px;
border: 1px solid black;
display: inline-block; /*add this*/
}
```
```html
<section>
<div class="container-fluid skillset">
<div class="row">
<div class="col-xs-12">
<h3>Acomplishments</h3>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<h4>Internship</h4>
</div>
<div class="col-xs-10">
<p>Every day is taco ipsum tuesday. Tacos Al pastor/De Adobada are made of thin pork steaks seasoned with adobo seasoning, then skewered and overlapped on one another on a vertical rotisserie cooked and flame-broiled as it spins. 50 cent tacos! I’ll
take 30. Carne asada on corn tortillas. Let’s do a beef and a chicken, and one with both. I’ve been following that taco truck around all day. Josh’s taco shack is the best taco shack. Let’s do a beef and a chicken, and one with both. CARNE ASADA!!</p>
</div>
</div>
<div class="row">
<div class="col-md-2">
<h4>Live Project</h4>
</div>
<div class="col-md-10">
<p>Every day is taco ipsum tuesday. Tacos Al pastor/De Adobada are made of thin pork steaks seasoned with adobo seasoning, then skewered and overlapped on one another on a vertical rotisserie cooked and flame-broiled as it spins. 50 cent tacos! I’ll
take 30. Carne asada on corn tortillas. Let’s do a beef and a chicken, and one with both. I’ve been following that taco truck around all day. Josh’s taco shack is the best taco shack. Let’s do a beef and a chicken, and one with both. CARNE ASADA!!</p>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<h3>Skills</h3>
</div>
</div>
<div class="row lang">
<div class="col-md-3">
<div class="card card-outline-primary text-xs-center">
<div class="card-block">
<blockquote class="card-blockquote">
<p><i class="fa fa-html5" aria-hidden="true"></i></p>
</blockquote>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card card-outline-primary text-xs-center">
<div class="card-block">
<blockquote class="card-blockquote">
<p><i class="fa fa-css3" aria-hidden="true"></i></p>
</blockquote>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card card-outline-primary text-xs-center">
<div class="card-block">
<blockquote class="card-blockquote">
<p><i class="fa fa-twitter" aria-hidden="true"></i></p>
</blockquote>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card card-outline-primary text-xs-center">
<div class="card-block">
<blockquote class="card-blockquote">
<p><i class="fa fa-database" aria-hidden="true"></i></p>
</blockquote>
</div>
</div>
</div>
</div>
</div>
</section>
```
I've added height,width,and border, to them, because they are essentially empty.
But you can just remove that when you put the icons in it. | for bootstrap3 the class for center is text-center
```
<div class="col-md-3 text-center">
<div class="card card-outline-primary text-xs-center">
<div class="card-block">
<blockquote class="card-blockquote">
<p><i class="fa fa-html5" aria-hidden="true"></i></p>
</blockquote>
</div>
</div>
</div>
``` |
18,065,736 | I have this problem, I'm using StringReader to find specific words from a textbox, so far is working great, however I need to find a way how to check specific words in every line against a string array.
The following code works:
```
string txt = txtInput.Text;
string user1 = "adam";
int users = 0;
int systems = 0;
using (StringReader reader = new StringReader(txt))
{
while ((txt = reader.ReadLine()) != null)
{
if (txt.Contains(user1))
{
users++;
}
}
}
```
Now, I have created a String Array to store more than one string, but the method Contains seems to only accept a string.
```
string[] systemsarray = new string[] { "as400", "x500", "mainframe" };
if(txt.Contains(systemsarray))
{
systems++;
}
// error message: cannot convert from string[] to string
```
Does anyone have an idea how to do this, or a way to improve it?
Thanks in advance. | 2013/08/05 | [
"https://Stackoverflow.com/questions/18065736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2615155/"
] | Why not write yourself an extension method to do this?
```
public static class StringExtensionMethods
{
public static bool ContainsAny(this string self, params string[] toFind)
{
bool found = false;
foreach(var criteria in toFind)
{
if (self.Contains(criteria))
{
found = true;
break;
}
};
return found;
} // eo ContainsAny
}
```
Usage:
```
string[] systemsarray = new string[] { "as400", "x500", "mainframe" };
if(txt.ContainsAny(systemsarray))
{
systems++;
}
// error message: cannot convert from string[] to string
``` | If you want a case-insensitive search (`as400` will match `AS400`), you can do this
```
if (systemsarray.Any(x => x.Equals(txt, StringComparison.OrdinalIgnoreCase)))
{
//systemsarray contains txt or TXT or TxT etc...
}
```
You can remove [StringComparison.OrdinalIgnoreCase](http://msdn.microsoft.com/en-us/library/system.stringcomparison.aspx) if you want to take the case into account (or choose a different enum value). |
16,646,205 | As the question says how to install Github for Windows without an internet connection?
If it is not possible then is there some alternative client with the following features:
* Support for proxy
* Offline installer
I found smartgit which has an offline installer but it seems it doesn't have proxy support.
If there is no such client then what can be done to extend the functionality of github for windows or some other client? I mean is there a way to use some API to extend it? Any links for that would be helpful. | 2013/05/20 | [
"https://Stackoverflow.com/questions/16646205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2235567/"
] | This is the answer I received from the support today (2015-06-30):
>
> Unfortunately we do not have a standalone installer at this time.
> GitHub for Windows makes use of Microsoft's ClickOnce technology for
> installation and updates.
>
>
> We are currently working on an open source replacement for ClickOnce
> here:
>
>
> <https://github.com/squirrel/squirrel.windows>
>
>
> Once that technology is complete and ready for use, we hope to switch
> GitHub for Windows to use that. It would allow for a standalone
> installer.
>
>
> In the meantime, you can find a list of alternate GUIs available
> here:
>
>
> <http://git-scm.com/downloads/guis>
>
>
> | For the current version (as of June 2017) of GitHub Desktop (windows), you can go to <https://github-windows.s3.amazonaws.com/standalone/GitHubDesktop.exe> for the standalone, offline installer.
For GitHub Desktop (beta), the team is also working to make it an offline installer hopefully by version 1.0. Currently the installer has some [issues](https://github.com/desktop/desktop/issues/776) that prevent it from installing successfully. |
15,503,242 | I'm want to make an iphone app that has a loginViewController. is this code correct and secure?
```
-(IBAction)loginPressed:(id)sender{
NSString *usr = [[NSString alloc]init];
NSString *psw = [[NSString alloc]init];
usr = username.text;
psw = password.text;
NSLog(@"%@",usr);
NSLog(@"%@", psw);
NSString *URL = [NSString stringWithFormat:@"http://www.mywebsite.com/loginApp.php?user_name=%@&password=%@", usr, psw];
NSLog(@"%@", URL);
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:URL]];
NSString *Result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if ([Result isEqualToString:@"1"])
{
NSLog(@"logged in");
}else if ([Result isEqualToString:@"2"]){
UIAlertView *WrongCredential = [[UIAlertView alloc]initWithTitle:@"Loggin failed" message:@"sorry, check again your email and password" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles: nil];
[WrongCredential show];
}
}
```
loginApp.php
```
<?php
require_once 'functions/init.php';
if (isset($_GET['user_name'], $_GET['password'])){
$email = sanitize($_GET['user_name']);
$password = sanitize($_GET['password']);
$login = loginApp($email, $password);
if($login === true){
echo json_encode(1);
}
else if($login === false){
echo json_encode(2);
}
}
?>
```
How can I check if the user has already logged in? In php I would probably set a session/cookies(?), right? How can I do it with Objective C? | 2013/03/19 | [
"https://Stackoverflow.com/questions/15503242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/651871/"
] | ```
NSString *usr = [[NSString alloc]init];
NSString *psw = [[NSString alloc]init];
usr = username.text;
psw = password.text;
```
This piece of code create a memory leak. You don't have to alloc a string and retrieve it from label after, just replace it by :
```
NSString* usr = username.text;
NSString* psw = password.text;
```
Then, you pass the password in clear to your website. And you make this on a non-HTTPS protocole and on a GET method.
1. Encrypt the password before send to the web
2. Use a POST method to do a login
3. If possible, make your site using HTTPS protocol.
Then, in this piece of code:
```
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:URL]];
```
You make a call to the web in synchronous mode from the Main Thread. So your UI will be blocked upon the web service haven't respond. It's not a good practice. It will be better to do then in asynchronous mode.
If you're not familiar with NSURLConnection and it's asynchronous mode, I will recommend you [AFNetworking](http://www.afnetworking.com), the best REST library at this moment. | If you want to save user status between application launches you probably need to set value in `NSUserDefaults`.
```
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"UserLogged"];
```
Than you can check this flag
```
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"UserLogged"]) {}
```
Or you can save username and password.
Also you can take a look onto [parse.com](https://parse.com) for basic singup/login functionality. |
43,732,737 | I've been racking my brain trying to fix this. I'm at a loss. I've searched and tried most of the solutions I could find but with no luck.
I'm building a basic website as apart of a hobby project for myself. I'm trying to get the page content split in two; left and right. However, the left is is always sitting on top of the right content. It is as if its ignoring the `float:left;` and `float: right;` commands.
```css
body {
font-family: 'Noto Sans', sans-serif;
background-color: #DAA520;
}
#container {
width: 80%;
margin: 25px auto;
background: #fff !important;
border: 1px solid black;
border-radius: 10px;
overflow: auto;
}
.header img {
padding-left: 30%;
float: none;
}
.header {
border-bottom: 5px solid #ccc;
margin-bottom: 4px;
height: 300px;
}
.nav ul {
list-style: none;
width: 100%;
margin-top: 25px;
text-align: center;
}
.nav li {
float: left;
width: 24%;
box-sizing: border-box;
border: 1px solid black;
margin-left: 2px;
}
.nav li:hover {
background: gold;
}
.banner img {
display: block;
height: 400px;
width: 100%;
}
.sub1 h3,
p {
float: left;
margin-left: 10px;
width: 48%;
display: inline-block;
position: relative;
}
.sub2 {
float: right;
margin-right: 10px;
width: 48%;
display: flex;
display: inline-block;
position: relative;
}
```
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/day1.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans" rel="stylesheet">
<title>Bakem and Shakem</title>
</head>
<body>
<div id="container">
<div class="header">
<img src="http://kojaks.betterplacesonline.com/wp-content/uploads/2016/09/Kojaks-Houose-of-Ribs-BBQ-Tampa-Logo-w-slogan-one-line-001-retina.png" alt="Logo">
<div class="nav">
<ul>
<li>Home</li>
<li>Recipes</li>
<li>Contact</li>
<li>Bakem</li>
</ul>
</div>
<!-- navigation bar divider -->
</div>
<!-- header divider -->
<div class="banner">
<img src="http://www.brucelauderdale.com/wp-content/uploads/2011/08/ribs.png" alt="banner">
</div>
<div class="sub1">
<h3>We make em, you bake em!</h3>
<p>Boudin ham hock fatback, tongue beef ribs drumstick capicola picanha pork chop meatloaf. Strip steak meatball hamburger tri-tip flank. Biltong sirloin spare ribs tongue, shank cupim corned beef burgdoggen venison. Kevin shankle sirloin porchetta
frankfurter.
</p>
</div>
<!-- sub1 divider -->
<div class="sub2">
<form class="signup" action="index.html" method="post">
<h3>Sign up for our news letter</h3>
<p>Be apart of the bakem family</p>
<input type="text" name="name" value="name"><label for="email" required>Name</label>
<input type="email" name="email" value="email" required><label for="email">Email address</label>
</form>
</div>
<!-- sub2 divider -->
</div>
<!-- conatiner divider -->
</body>
</html>
```
The main issue can be found in the sub1 and sub2 classes. I'm starting to think it must be another class where I have made a rule that is clashing with this one, I'm not sure. | 2017/05/02 | [
"https://Stackoverflow.com/questions/43732737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7899214/"
] | You can check this method:
```
if (!isTaskRoot()) {
super.onBackPressed();//or finish()
} else {
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
finish();
}
``` | ```
// isTaskRoot() returns 'true' if this is the root activity, else 'false'.
/* If it returns 'true' this means the current activity is the root activity of your
application right now & no activity exist on the back stack, if you press back at
this moment your app will be closed. But now you can handle the back press by checking
is the current activity a root activity or not like below */
if(isTaskRoot()) {
// Start an activity or do whatever you want
} else {
super.onBackPressed();
}
``` |
24,096,406 | I am new to C#. I want to convert the two strings to single JSON array.
I tried the following:
```
var username = "username";
var password = "XXXXXXXX";
var json_data = "result":[{"username":username,"password":password}]'; //To convert the string to Json array i tried like this
MessageBox.Show(json_data);
```
It is not working, I'm getting a lot of errors.
I've went through the following links:
<http://json.codeplex.com/>
[Convert string to Json Array](https://stackoverflow.com/questions/14935677/convert-string-to-json-array)
<http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET>
[convert string to json](https://stackoverflow.com/questions/6884453/convert-string-to-json)
To learn how to convert my string to Json array. Well explained in the above url, but for my case I don't know how to convert this two string to single Json array.
I want the output to be like this format,
```
[{"result":{"username":"Tom","password":"XXXXXXX"}}]
```
Please help me in doing this. | 2014/06/07 | [
"https://Stackoverflow.com/questions/24096406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3100575/"
] | You can use a JSON serialiser API. A commonly used one is the one from Newtonsoft, called [Json.NET](http://james.newtonking.com/json).
Job of such an API is to convert C# objects to JSON (also known as serialisation) and convert JSON data into C# objects (deserialisation).
In your example, Newtonsoft JSON API can be used as follows.
```
public class UserData { public string username; public string password; }
var userData = new UserData() { username = "Tom", password = "XXXXXXXX" };
UserData[] arr = new UserData[] { userData };
string json_data = JsonConvert.SerializeObject(arr); // this is the Newtonsoft API method
// json_data will contain properly formatted Json. Something like [{"result":{"username":"Tom","password":"XXXXXXX"}}]
MessageBox.Show(json_data);
```
Excuse my typing as I'm doing it over phone. | In [Javascript Object Notation](http://json.org/json-de.html) the top level is always an object.
In JSON an array is not an object but it can be a value.
You can unfold the grammer into this:
```
{ string : [ { string : string , string : string },{ string : string , string : string } ] }
```
in your case this could be:
```
{ "allUsers": [ { "name": "Luis" , "password": "R0Cke+" }, { "name": "Janette" , "password": "BookTour2011" } ] }
``` |
23,639,113 | `ViewSets` have automatic methods to list, retrieve, create, update, delete, ...
I would like to disable some of those, and the solution I came up with is probably not a good one, since `OPTIONS` still states those as allowed.
Any idea on how to do this the right way?
```python
class SampleViewSet(viewsets.ModelViewSet):
queryset = api_models.Sample.objects.all()
serializer_class = api_serializers.SampleSerializer
def list(self, request):
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
def create(self, request):
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
``` | 2014/05/13 | [
"https://Stackoverflow.com/questions/23639113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2089556/"
] | If you are trying to disable the PUT method from a DRF viewset, you can create a custom router:
```
from rest_framework.routers import DefaultRouter
class NoPutRouter(DefaultRouter):
"""
Router class that disables the PUT method.
"""
def get_method_map(self, viewset, method_map):
bound_methods = super().get_method_map(viewset, method_map)
if 'put' in bound_methods.keys():
del bound_methods['put']
return bound_methods
```
By disabling the method at the router, your api schema documentation will be correct. | An alternative approach for Viewsets in django-rest-framework to enable/disable methods. Here is an example api/urls.py:
```
user_list = UserViewSet.as_view({
'get': 'list'
})
user_detail = UserViewSet.as_view({
'get': 'retrieve'
'put': 'update',
'post': 'create',
'patch': 'partial_update',
'delete': 'destroy'
})
urlpatterns = [
path('users/', user_list, name='user-list'),
path('users/<int:pk>/', user_detail, name='user-detail')
]
```
View user\_list has only one - get - method allowed, whereas user\_detail has all methods active.
Tested on Django 4.0
reference: [more details here](https://github.com/encode/django-rest-framework/blob/e7777cb1ee98c0215a5f1f082a88290eefa3e293/docs/tutorial/6-viewsets-and-routers.md) |
110,987 | When you track down and fix a regression—i.e. a bug that caused previously working code to stop working—version control makes it entirely possible to look up who committed the change that broke it.
Is it worth doing this? Is it constructive to point this out to the person that made the commit? Does the nature of the mistake (on the scale of simple inattentiveness to fundamental misunderstanding of the code they changed) change whether or not it's a good idea?
If it is a good idea to tell them, what are good ways to do it without causing offense or causing them to get defensive?
Assume, for the sake of argument, that the bug is sufficiently subtle that the CI server's automated tests can't pick it up. | 2011/09/27 | [
"https://softwareengineering.stackexchange.com/questions/110987",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/17701/"
] | If you just approach them to tell them about a mistake they made then unless you are the best diplomat in the world its going to be difficult for it not to just sound like "Ha! - look at this mistake you made!". We are all human and criticism is difficult to take.
On the other hand unless the change is completely trivial and **obviously** wrong I normally find it benificial to talk to the person who committed the original change as part of my investigation just to make sure that I fully understand whats going on, hence the way I usually end up handling these situation is by going over to said person and having a conversation that goes a little like this:
>
> **Me:** I'm working on this bug where *... summary of bug ...* and I think I've tracked down the problem to a change you made. Can you remember what this change was for? / have you got some time to explain this change?
>
>
>
Then either:
>
> **Them:** Sure, thats to handle *... situation I wasn't aware of ...*
>
>
>
Or something along the lines of:
>
> **Them:** Nope sorry I don't remember, looks wrong to me.
>
>
>
By going and investigating the change / bug together the original committer gets to learn from their mistakes without just feeling like they are being criticised\*, and there is also a pretty good chance that you will learn something too.
If the original committer isn't around or is busy then you can alwasy just slog through and figure it all out yourself, I just normally find that talking to the person who originally made the change is quicker.
\* *Of course this is only going to work if you are genuinely interested in the other persons help. If you are just using this as a thinly disguised method of telling someone about a mistake they made then this is probably* worse *than just being open about it.* | If someone gets offended when you said him he made a mistake, it means he thinks he is the wisest on the earth and makes no mistake, and when criticized, he gets the feeling, as we said in Poland, that 'crown is falling from his head'.
So you shouldn't hesitate to say that someone has made a mistake. It is normal. Everyone makes mistakes, even the best! Only those who make nothing make no mistakes ;) |
59,856,861 | I create a form where I check the length of a password. If length is <6 then an error message appears.
This message is created by javascript. And here is the problem, the message appears with a line break after every word. I also tried it with ' ' but that doesn't work:(
How do I create the message without the line breaks?
Thanks for your help!
```js
$("#registerPass").on("focusout", function() {
if ($("#registerPass").val().length < 6) {
$(this).removeClass("valid").addClass("invalid");
$('#registerPass + label').attr('data-error', 'Mindestens 6 Zeichen nötig!');
}
});
```
```html
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.8.11/css/mdb.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.8.11/js/mdb.min.js"></script>
<form style="color: #757575;" action="#!">
<div class="md-form mb-5">
<input type="password" id="registerPass" class="form-control" required>
<label data-error="" data-success="OK" for="registerPass">Passwort</label>
</div>
</form>
``` | 2020/01/22 | [
"https://Stackoverflow.com/questions/59856861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10474530/"
] | You can first split the string containing your datas (`queryResult.final_Matrix[index]`) to get each parts separatly, then, for each parts, split again using `":"` and apply some math (multiply by 100) to get the percentage :
```js
let input = "53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245";
let times = input.split(", ");
const result = [];
times.forEach((elem) =>
{
const tempArr = elem.split(":");
result.push(tempArr[0] + ":" + (Math.round((tempArr[1] * 100) * 100) / 100) + "%");
});
let finalResult = result.join(", ");
console.log(finalResult);
``` | You can loop, split according to the strings, reducing the array of tokens (those separated by comma `,`) and finally rebuild the tokens with the transformed percentage values.
```js
let arr = [ { "id": "12345", "header": "<a class=\"card-link\" href=\"http://www.google.com\" target=\"_blank\"> 12345</a>- solved-1", "title": "Training Summary Report", "description": "", "link": "", "labels": [ { "filter": "type", "value": "course 1" }, { "filter": "Subject", "value": "Sub. 1239" }, { "filter": "Idea", "value": "Idea . 53" } ] }, { "id": "12345", "header": "<a class=\"card-link\" href=\"http://www.google.com\" target=\"_blank\"> 12345</a>- solved-1", "title": "Training Summary Report", "description": "", "link": "", "labels": [ { "filter": "type", "value": "course 1" }, { "filter": "Subject", "value": "Sub. 1239" }, { "filter": "Idea", "value": "Idea . 53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245" } ] }];
arr.forEach(({labels}) => {
labels.forEach(label => {
let [_, value] = label.value.split("Idea . ");
if (value) {
label.value = "Idea . " + value.split(",").reduce((a, t) => {
let [str, perc] = t.split(":");
if (perc) str += ":" + (Number(perc.trim()) * 100).toFixed(2) + "%"
return a.concat(str);
}, []).join();
}
});
});
console.log(arr);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
``` |
32,471,985 | I am trying to build a section where we can add users with `Role_ID=2`
`Role_ID` is in some other table named as `User_Details`, and is linked with current `user` table `id` as foreign key.
**Here is code for my UserController.php**
```
function addUser(){
$this->set('setTab','addUser');
$this->set('parent_tab','Manage Users');
$this->set('tab','Add User');
// Super admin doesn't have an access of Manage user section
if($this->Session->read('User.access_rights') == 4){
$this->redirect('dashboard');
}
$this->layout = 'user';
$this->set('setTab','manageUsers');
$this->set('statusArray', $this->statusArray);
/*CREATE USER DROP DOWN ARRAY START*/
/*$userDrop['0']='Select Parent';
$getUsers = $this->User->generatetreelist('User.access_rights <> 4',null,'{n}.User.username','-');
if($getUsers) {
foreach ($getUsers as $key=>$value){
$userDrop[$key] = $value;
}
$this->set(compact('userDrop'));
}*/
/*CREATE USER DROP DOWN ARRAY END*/
if(!$this->Session->check('User')){
$this->redirect('login');
}
if($this->data){
$data = $this->data;
$this->User->set($data);
if ($this->User) {
// pr($this->data); die;
// because we like to send pretty mail
//Set view variables as normal
$this->set('userDetails', $data['User']);
//$this->User->recursive = 1;
if($this->User->saveAll($data)){
$this->Session->setFlash('User added successfully', 'default', array('class' => 'errMsgLogin'));
$this->redirect('manageUsers');
}
else {
echo "User not added";
}
}
else {
// do nothing
}
}
}//Ends here
```
Here is code for model **user.php**
```
<?php
class User extends AppModel{
var $name = "User";
var $validate = array(
'Username' => array(
'notempty' => array(
'rule' => array('notempty'),
'required' => false,
'message' => 'Username can not be empty!',
),
'maxLength'=> array(
'rule' => array('maxLength', 20),
'message' => 'Username can not be longer that 20 characters.'
)
),
'First_Name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'First name can not be empty!',
)
),
/*'phone' => array(
'numeric' => array(
'rule' => 'numeric',
'message' => 'Numbers only'
),
'rule' => array('minLength', 10),
'message' => 'Phone number should be of 10 digits'
),*/
'Last_Name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Last name can not be empty!',
)
),
'Email_Id' => array(
'notempty' => array(
'rule' => array('email'),
'allowEmpty' => false,
'message' => 'Please Enter a valid Email Address'
)
)
/*'status'=> array(
'notempty' => array(
'rule' => array('notEmpty'),
'allowEmpty' => false,
'message' => 'Please Enter a Status'
)
),*/
);
```
Here is view code **add\_user.ctp**
```
<h4 class="widgettitle">Add New User</h4>
<div class="widgetcontent">
<?php echo $this->Form->create('User',array('url'=>'addUser/', "enctype" => "multipart/form-data",'class'=>'stdform','id'=>'form1')); ?>
<div class="par control-group">
<label class="control-label" for="firstname">First Name*</label>
<div class="controls">
<?php echo $this->Form->input('First_Name',array('label'=>false, 'id'=>'firstname','class'=>'input-large')); ?>
</div>
</div>
<div class="control-group">
<label class="control-label" for="lastname">Last Name*</label>
<div class="controls">
<?php echo $this->Form->input('Last_Name',array('label'=>false,'id'=>'lastname','class'=>'input-large')); ?>
</div>
</div>
<div class="control-group">
<label class="control-label" for="username">Username*</label>
<div class="controls">
<?php echo $this->Form->input('Username',array('label'=>false,'id'=>'username','class'=>'input-large')); ?>
</div>
</div>
<div class="par control-group">
<label class="control-label" for="email">Email*</label>
<div class="controls">
<?php echo $this->Form->input('Email_Id',array('label'=>false,'id'=>'email','class'=>'input-xlarge')); ?>
</div>
</div>
<div class="par control-group">
<label class="control-label" for="location">Office Phone*</label>
<div class="controls">
<?php echo $this->Form->input('User_Phone1',array('label'=>false, 'maxlength'=>false,'id'=>'phone','class'=>'input-large')); ?>
</div>
</div>
<div class="par control-group">
<label class="control-label" for="location">Cell Phone*</label>
<div class="controls">
<?php echo $this->Form->input('User_Phone2',array('label'=>false, 'maxlength'=>false,'id'=>'phone','class'=>'input-large')); ?>
</div>
</div>
<div class="par control-group">
<label class="control-label" for="status">Status</label>
<div class="controls">
<?php echo $this->Form->input('Is_Active',array('type'=>'select', 'width' => 100, 'options'=>$statusArray, 'label' => false, 'class'=>'input-large')); ?>
</div>
</div>
<p class="stdformbutton">
<button class="btn btn-primary">Save</button>
</p>
<?php echo $this->Form->end(); ?>
</div><!--widgetcontent-->
```
**After adding:**
```
$this->User->bindModel(array('belongsTo'=>array('UserDetail'=>array('className' => 'UserDetail', 'foreignKey' => 'Role_ID', ))));
```
**Got Error in query:**
```
SQL Query: SELECT `User`.`User_ID`, `User`.`First_Name`, `User`.`Last_Name`, `User`.`Email_Id`, `User`.`Username`, `User`.`User_Password`, `User`.`User_Phone1`, `User`.`User_Phone2`, `User`.`Created_By`, `User`.`Created_Date`, `User`.`Is_Active`, `User`.`Is_Deleted`, `UserDetail`.`User_Detail_ID`, `UserDetail`.`User_ID`, `UserDetail`.`Role_ID`, `UserDetail`.`Unit_ID`, `UserDetail`.`Rank_ID`, `UserDetail`.`City_ID`, `UserDetail`.`State_ID`, `UserDetail`.`RSID`, `UserDetail`.`User_Address1`, `UserDetail`.`User_Address2`, `UserDetail`.`Zip_Code`, `UserDetail`.`User_Url`, `UserDetail`.`Created_By`, `UserDetail`.`Created_Date`, `UserDetail`.`Is_Active`, `UserDetail`.`Is_Deleted` FROM `national`.`users` AS `User` LEFT JOIN `national`.`user_details` AS `UserDetail` ON (`User`.`Role_ID` = `UserDetail`.`id`) WHERE 1 = 1 ORDER BY `User`.`User_ID` DESC
```
Any suggestions on how can I build this? | 2015/09/09 | [
"https://Stackoverflow.com/questions/32471985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3322344/"
] | Your code is fundamentally wrong (I think). According to what you say (the conditions in your problem statement), this should be the code:
```
public static boolean search(int[] keys, int value, int l, int r)
{
if(l < 0 || r >= keys.length || l>r) return false;
else
{
Random random = new Random();
int i = l + random.nextInt(r-l);
if(keys[i] == value) return true;
else if(keys[i] > value) return search(keys, value, l, i - 1);
else return search(keys, value, i + 1, r);
}
}
``` | See this part of your code,
```
else if(keys[i] > value)
return search(keys, value, i - 1); //Line1
else
return search(keys, value, i + 1); //Line2
```
You are searching in the same part of the array in both case.
`Line1` searches for the `value` in the array from `0` to `i - 1`.
`Line2` searches for the `value` in the array from `0` to `i + 1`.
What you should have done is,
`Line1` should search for the `value` in the array from `0` to `i - 1`.
`Line2` should search for the `value` in the array from `i + 1` to end of array. |
58,839,913 | I have two dataframes, `dfa` and `dfb`:
```
dfa <- data.frame(
gene_name = c("MUC16", "MUC2", "MET", "FAT1", "TERT"),
id = c(1:5)
)
dfb <- data.frame(
gene_name = c("MUC1", "MET; BLEP", "MUC21", "FAT", "TERT"),
id = c(6:10)
)
```
which look like this:
```
> dfa
gene_name id
1 MUC16 1
2 MUC2 2
3 MET 3
4 FAT1 4
5 TERT 5
> dfb
gene_name id
1 MUC1 6
2 MET; BLEP 7
3 MUC21 8
4 FAT 9
5 TERT 10
```
`dfa` is my genes of interest list: I want to keep the `dfb` rows where they appear, minding the digits (`MUC1` is **not** `MUC16`). My `new_df` should look like this:
```
> new_df
gene_name id
1 MET; BLEP 7
2 TERT 10
```
My problem is that the regular `dplyr::semi_join()` does exact matches, which doesn't take into account the fact that `dfb$gene_names` can contain genes separated with `"; "`. Meaning that with this example, `"MET"` is not retained.
I tried to look into `fuzzyjoin::regex_semi_join`, but I can't make it do what I want...
A tidyverse solution would be welcome. (Maybe with `stringr`?!)
**EDIT:** Follow-up question...
How would I go about to do the reciprocal `anti_join`? Simply changing `semi_join` to `anti_join` in this method doesn't work because the row `MET; BLEP` is present when it shouldn't be...
Adding a `filter(gene_name == new_col)` after the `anti_join` works with the provided simple dataset, but if I twist it a little like this:
```
dfa <- data.frame(
gene_name = c("MUC16", "MUC2", "MET", "FAT1", "TERT"),
id = c(1:5)
)
dfb <- data.frame(
gene_name = c("MUC1", "MET; BLEP", "MUC21; BLOUB", "FAT", "TERT"),
id = c(6:10)
)
```
...then it doesn't anymore. Here and in my real-life dataset, `dfa` doesn't contain semicolons, it's only one column of individual gene names. But `dfb` contains a lot of information, and multiple combinations of semicolons... | 2019/11/13 | [
"https://Stackoverflow.com/questions/58839913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8876619/"
] | You can use `seperate_rows()` to split the dataframe before joining. Note that if `BLEP` existed in dfa, it would result in a duplicate, which is why distinct is used
```
dfa <- data.frame(
gene_name = c("MUC16", "MUC2", "MET", "FAT1", "TERT"),
id = c(1:5),
stringsAsFactors = FALSE
)
dfb <- data.frame(
gene_name = c("MUC1", "MET; BLEP", "MUC21", "FAT", "TERT"),
id = c(6:10),
stringsAsFactors = FALSE
)
library(tidyverse)
dfb%>%
mutate(new_col = gene_name)%>%
separate_rows(new_col,sep = "; ")%>%
semi_join(dfa,by = c("new_col" = "gene_name"))%>%
select(gene_name,id)%>%
distinct()
``` | Here's a solution using `stringr` and `purrr`.
```
library(tidyverse)
dfb %>%
mutate(gene_name_list = str_split(gene_name, "; ")) %>%
mutate(gene_of_interest = map_lgl(gene_name_list, some, ~ . %in% dfa$gene_name)) %>%
filter(gene_of_interest == TRUE) %>%
select(gene_name, id)
``` |
35,301,178 | Long-running, high-end Excel-based applications that I developed years ago and that run beautifully in Excel 2007 and 2010 look like Amateur Hour in Excel 2013 and 2016 because `Application.ScreenUpdating = False` no longer works reliably.
The screen unfreezes apparently when VBA code copies a preformatted worksheet from the macro workbook into a new workbook, although other circumstances must trigger it as well.
I’ve seen the threads on this subject that recommend “fiddling with the code” or “calling the code in a subroutine”. Unfortunately, I have to maintain hundreds of Excel applications each with thousands of lines of code and hundreds of users who are about to migrate to Office 2016, so rewriting is not an option. How can I recover Excel’s former elegance? | 2016/02/09 | [
"https://Stackoverflow.com/questions/35301178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5410232/"
] | We have been dealing with this problem now for a long time as my tools do show live animated charts which all of the sudden were completely static - we would have died for having at least a flickering animation.
Initially we tried to force the animation with a forced screenupdate but that did not work. Just by pure coincidence (copy pasted too many times) we stumbled into a solution which is equally unbelievable as it does seem to work. After each `Application.ScreenUpdating = True` we have added x3 times DoEvents. On some systems x2 times DoEvents works but x3 times does seem to be more reliable on the various office releases out there. Voila our animation came back :-)
```
Application.ScreenUpdating = True
DoEvents
DoEvents
DoEvents
```
We have not used it for the `Application.ScreenUpdating = False` statement but it might do some magic there. Anyway we hope that this road can help some of you finding creative functional solutions! | For me, only "Application.ScreenUpdating = False" did not completely cure the flickering.
Calculation caused also the flickering.
Adding "Application.Calculation = xlCalculationManual" solved the flickering issue.
So, the code should be like:
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
... inportant code here....
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Nico Mijnster. |
793,926 | The following `DataTemplate.DataTrigger` makes the age display red if it is **equal to** 30.
How do I make the age display red if it is **greater than** 30?
```
<DataTemplate DataType="{x:Type local:Customer}">
<Grid x:Name="MainGrid" Style="{StaticResource customerGridMainStyle}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Text="First Name" Margin="5"/>
<TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding FirstName}" Margin="5"/>
<TextBlock Grid.Column="0" Grid.Row="1" Text="Last Name" Margin="5"/>
<TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding LastName}" Margin="5"/>
<TextBlock Grid.Column="0" Grid.Row="2" Text="Age" Margin="5"/>
<TextBlock x:Name="Age" Grid.Column="1" Grid.Row="2" Text="{Binding Age}" Margin="5"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=Age}">
<DataTrigger.Value>30</DataTrigger.Value>
<Setter TargetName="Age" Property="Foreground" Value="Red"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
``` | 2009/04/27 | [
"https://Stackoverflow.com/questions/793926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | I'd recommend using an `IValueConverter` to bind to the `Foreground` element of the Age `TextBlock` and isolating the coloring logic there.
```
<TextBlock x:Name="Age"
Text="{Binding Age}"
Foreground="{Binding Path=Age, Converter={StaticResource AgeToColorConverter}}" />
```
Then in the Code:
```
[ValueConversion(typeof(int), typeof(Brush))]
public class AgeToColorConverter : IValueConverter
{
public object Convert(object value, Type target)
{
int age;
Int32.TryParse(value.ToString(), age);
return (age >= 30 ? Brushes.Red : Brushes.Black);
}
}
``` | I believe there is a simpler way of acheiving the goal by using the powers of MVVM and `INotifyPropertyChanged`.
---
With the `Age` property create another property which will be a boolean called `IsAgeValid`. The `IsAgeValid` will simply be an *on demand* check which does not *technically* need an the `OnNotify` call. How?
To get changes pushed to the Xaml, place the `OnNotifyPropertyChanged` event to be fired for `IsAgeValid` **within** the `Age` setter instead.
Any binding to `IsAgeValid` will *also* have a notify message sent on any `Age` change subscriptions; which is what really is being looked at...
---
Once setup, of course bind the style trigger for false and true accordingly to the `IsAgeValid` result.
```
public bool IsAgeValid{ get { return Age > 30; } }
public int Age
{
get { return _Age; }
set
{
_Age=value;
OnPropertyChanged("Age");
OnPropertyChanged("IsAgeValid"); // When age changes, so does the
// question *is age valid* changes. So
// update the controls dependent on it.
}
}
``` |
31,704,822 | Question with left join. I am trying to LEFT JOIN a table that requires other tables to be joined on the initial left joined table. So..
```
SELECT * FROM tableA
LEFT JOIN tableB
ON tableB.id=tableA.id
JOIN tableC
ON tableC.id=tableB.id
```
The problem is if I don't left join table C I get no results, and if do left join I get too many results.
What kind of joins should I be using where if tableB join is null, tableC joins will also be null? | 2015/07/29 | [
"https://Stackoverflow.com/questions/31704822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456850/"
] | >
> I don't left join table C I get no results, and if do left join I get
> too many results
>
>
>
You need to determine what is your driving table and data. In this case, it seems like table A is the driving table and the join from B to C also could be a left join, meaning data from C could be returned even if no matching exists in B.
```
SELECT * FROM tableA
LEFT JOIN tableB
ON tableB.id=tableA.id
LEFT JOIN tableC
ON tableC.id=tableB.id
```
>
> if do left join I get too many results
>
>
>
Can you post some sample data to show what you mean by this? | I think you might want this logic:
```
SELECT *
FROM tableA LEFT JOIN
(tableB JOIN
tableC
ON tableC.id = tableB.id
)
ON tableB.id = tableA.id ;
```
Normally, with `LEFT JOIN` you want to chain them, but there are some exceptions. |
52,425,988 | I would like to download this file <https://www.omniva.ee/locations.xml> with VBA or VB6.
I can do it with C# using webClient but i don't know how do it in VBA or VB6.
Is it possible without IE API? Because it doesn't work for me:
[](https://i.stack.imgur.com/XsXdC.png)
Internet explorer can't show this page :-(.
Can you help me please? | 2018/09/20 | [
"https://Stackoverflow.com/questions/52425988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10391525/"
] | you could try that but make a copy of the otherlist to not lose the info:
```
[row+[myotherlist.pop(0)] if row[0]=='Download' else row for row in listScheduel]
```
for example:
```
list = [['Download',1,2,3],[0,1,2,3],['Download',1,2,3],['Download',1,2,3]]
otherlist = [0,1,2,3,4]
l = [ row+[otherlist.pop(0)] if row[0]=='Download' else row for row in list]
```
Output:
```
[['Download', 1, 2, 3, 0],
[0, 1, 2, 3],
['Download', 1, 2, 3, 1],
['Download', 1, 2, 3, 2]]
``` | We can use a queue and pop its values one by one when we meet the condition. To avoid copying of data let's implement the queue as a view over `myOtherList` using an iterator (thanks to [ShadowRanger](https://stackoverflow.com/users/364696/shadowranger)).
```
queue = iter(myOtherList)
for row in listSchedule:
if row[0] == "Download":
row.append(next(iter))
``` |
70,203,149 | I want to handle foreground firebase messages.
But messaging().onMessage is not triggered very first time app launched in iOS. This is working fine in Android.
Exact scenario is:
* First time launch app : messaging().onMessage not triggered in iOS
* Close and reopen app : messaging().onMessage will trigger
```
import { Alert } from 'react-native';
import messaging from '@react-native-firebase/messaging';
function FCMReadInForeGround() {
useEffect(() => {
const unsubscribe = messaging().onMessage(async remoteMessage => {
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
});
return unsubscribe;
}, []);
}
export default FCMReadInForeGround;```
``` | 2021/12/02 | [
"https://Stackoverflow.com/questions/70203149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8112970/"
] | The writerows() method expects a list of lists. A row is a list and the rows are a list of those.
Two solutions, depending on what you want:
```
even_numbers = [[2, 4, 6, 8]]
```
or
```
even_numbers = [[2], [4], [6], [8]]
```
To do that latter transformation automatically, use:
```
rows = [[data] for data in even_numbers]
writer.writerows(rows)
``` | According to [the documentation](https://docs.python.org/3/library/csv.html#csv.csvwriter.writerows), the `writeRows` method expects a list of row objects as a parameter.
You can also see the definition [of a row object here](https://docs.python.org/3/library/csv.html#writer-objects).
That is:
>
> A row must be an iterable of strings or numbers for Writer objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str() first) for DictWriter objects.
>
>
>
The reason you are getting this message is that it is trying to convert each int in that list as a row itself. The reason it works for strings is that a string itself is iterable. However I suspect you would get unexpected behavior if you tried out a multiple digit number in your list of strings like this:
```
even_numbers = ['24','45','66','82'] # list of strings
```
It will likely split out each of the digits as columns in the row, because it is reading the string in as a row object. |
51,712,220 | Lets say my use-case is to print a list of posts. I have the following react component.
```
class App extends Component {
constructor(props) {
super(props);
this.state = {
loaded: !!(props.posts && props.posts.length)
};
}
componentDidMount() {
this.state.loaded ? null : this.props.fetchPosts();
}
render() {
return (
<ul>
{this.state.loaded
? this.props.posts.length
? this.props.posts.map((post, index) => {
return <li key={index}>{post.title}</li>;
})
: 'No posts'
: 'Loading'}
</ul>
);
}
}
```
`fetchPosts` is an action which makes an API call to fetch posts from DB and then updates the redux store with data. Now, my questions are
1. When should I update my local React state as per the props?
Initially, `this.props.posts` would either be `undefined` or `[]` so `this.state.loaded` would be `false` and we will make an API call to fetch. Once, the data is fetched then should I update it as
```
componentWillReceiveProps(nextProps) {
this.setState({
loaded: nextProps.posts && nextProps.posts.length
});
}
```
This sets the local state and initially `spinner/loader` will be shown and then `posts` or `no posts`. However, as far as I understand, React documentation discourages to `setState` in `componentWillReceiveProps` as that `lifecycle` hook will be called many times in React 16 and is also deprecated.
**So, in which lifecycle hook should I update local state?**
2. Would it be better to maintain the loading mechanism in Redux only?
```
class App extends Component {
constructor(props) {
super(props);
}
compomentDidMount() {
this.props.loaded ? null : this.props.fetchPosts();
}
render() {
return (
<ul>
{this.props.loaded
? this.props.posts.length
? this.props.posts.map((post, index) => {
return <li key={index}>{post.title}</li>;
})
: 'No posts'
: 'Loading'}
</ul>
);
}
}
```
Here everything is maintained in Redux store only. If any other approach would be better then I would love to know. Thanks! | 2018/08/06 | [
"https://Stackoverflow.com/questions/51712220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4191127/"
] | The recommended solution would be to move that to `mapStateToProps`. Most of the time when you need data from your store (here it's `posts`) or data that is derived from store (here `loading`) then `mapStateToProps` is the correct place to inject that. It is usually a good idea to keep the component as dumb as possible that takes data from the store. Also it it kind of violating the single source of truth principle to keep state in a component that is derived from the store because it can get out of sync if you do not pay attention:
```
class App extends Component {
render() {
const {loading, posts} = this.props;
if (loading) return 'Loading';
if (!posts.length) return 'No Posts';
return (
<ul>
{posts.map((post, index) => (
<li key={index}>{post.title}</li>;
))}
</ul>
);
}
}
const mapStateToProps = ({posts}) => ({
posts
loading: !posts,
});
export default connect(mapStateToProps, /* mapDispatchToProps */)(App);
``` | 2 is correct. It is better to maintain the state in Redux only. Otherwise, you have two separate states for this component! |
4,368,308 | I'm using SOAPUI tool to access JAX-WS web services deployed in Weblogic 10.3.2
Request:
```xml
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.pc3.polk.com/">
<soapenv:Header>
<wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsu:Timestamp wsu:Id="Timestamp-1" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsu:Created>2010-12-03T21:10:43Z</wsu:Created>
<wsu:Expires>2010-12-03T21:44:03Z</wsu:Expires>
</wsu:Timestamp>
<wsu:Timestamp wsu:Id="Timestamp-60" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsu:Created>2010-12-03T20:10:39Z</wsu:Created>
<wsu:Expires>2010-12-03T20:43:59Z</wsu:Expires>
</wsu:Timestamp>
<wsse:UsernameToken wsu:Id="UsernameToken-59" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:Username>rwerqre</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">ewrqwrwerqer</wsse:Password>
<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">Nmw0ksmiOX+hkiSoWb2Rjg==</wsse:Nonce>
<wsu:Created>2010-12-03T20:10:39.649Z</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<ws:getMetadata/>
</soapenv:Body>
</soapenv:Envelope>
```
Response:
```xml
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<SOAP-ENV:Fault xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<faultcode>SOAP-ENV:MustUnderstand</faultcode>
<faultstring>MustUnderstand headers:[{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}Security] are not understood</faultstring>
</SOAP-ENV:Fault>
</S:Body>
</S:Envelope>
``` | 2010/12/06 | [
"https://Stackoverflow.com/questions/4368308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117802/"
] | Issue is with the Handlers. You need to add following in handler implementation
```
public Set<QName> getHeaders() {
final QName securityHeader = new QName(
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
"Security",
"wsse");
final HashSet headers = new HashSet();
headers.add(securityHeader);
return headers;
}
``` | In SOAP UI Navigator,
right-click your project->Show Project View->WS-Security Configurations->Outgoing WS-Security Configurations
**Uncheck** Must Understand, and then send request. |
21,140,349 | This has been awnsered many times here and at other sites and its working, but I would like ideas to other ways to:
get the ReadyState = Complete after using a navigate or post, without using DoEvents because of all of its cons.
I would also note that using the DocumentComplete event woud not help here as I wont be navigating on only one page, but one after another like this.
```
wb.navigate("www.microsoft.com")
//dont use DoEvents loop here
wb.Document.Body.SetAttribute(textbox1, "login")
//dont use DoEvents loop here
if (wb.documenttext.contais("text"))
//do something
```
The way it is today its working by using DoEvents. I would like to know if anyone have a proper way to wait the async call of the browser methods to only then proceed with the rest of the logic. Just for the sake of it.
Thanks in advance. | 2014/01/15 | [
"https://Stackoverflow.com/questions/21140349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3198440/"
] | **The solution is simple:**
```
// MAKE SURE ReadyState = Complete
while (WebBrowser1.ReadyState.ToString() != "Complete") {
Application.DoEvents();
}
```
// Move on to your sub-sequence code...
---
Dirty and quick.. I am a VBA guys, this logic has been working forever, just took me days and found none for C# but I just figured this out myself.
Following is my complete function, the objective is to obtain a segment of info from a webpage:
```
private int maxReloadAttempt = 3;
private int currentAttempt = 1;
private string GetCarrier(string webAddress)
{
WebBrowser WebBrowser_4MobileCarrier = new WebBrowser();
string innerHtml;
string strStartSearchFor = "subtitle block pull-left\">";
string strEndSearchFor = "<";
try
{
WebBrowser_4MobileCarrier.ScriptErrorsSuppressed = true;
WebBrowser_4MobileCarrier.Navigate(webAddress);
// MAKE SURE ReadyState = Complete
while (WebBrowser_4MobileCarrier.ReadyState.ToString() != "Complete") {
Application.DoEvents();
}
// LOAD HTML
innerHtml = WebBrowser_4MobileCarrier.Document.Body.InnerHtml;
// ATTEMPT (x3) TO EXTRACT CARRIER STRING
while (currentAttempt <= maxReloadAttempt) {
if (innerHtml.IndexOf(strStartSearchFor) >= 0)
{
currentAttempt = 1; // Reset attempt counter
return Sub_String(innerHtml, strStartSearchFor, strEndSearchFor, "0"); // Method: "Sub_String" is my custom function
}
else
{
currentAttempt += 1; // Increment attempt counter
GetCarrier(webAddress); // Recursive method call
} // End if
} // End while
} // End Try
catch //(Exception ex)
{
}
return "Unavailable";
}
``` | Here is a "quick & dirty" solution. It's not 100% foolproof but it doesn't block UI thread and it should be satisfactory to prototype WebBrowser control Automation procedures:
```
private async void testButton_Click(object sender, EventArgs e)
{
await Task.Factory.StartNew(
() =>
{
stepTheWeb(() => wb.Navigate("www.yahoo.com"));
stepTheWeb(() => wb.Navigate("www.microsoft.com"));
stepTheWeb(() => wb.Navigate("asp.net"));
stepTheWeb(() => wb.Document.InvokeScript("eval", new[] { "$('p').css('background-color','yellow')" }));
bool testFlag = false;
stepTheWeb(() => testFlag = wb.DocumentText.Contains("Get Started"));
if (testFlag) { /* TODO */ }
// ...
}
);
}
private void stepTheWeb(Action task)
{
this.Invoke(new Action(task));
WebBrowserReadyState rs = WebBrowserReadyState.Interactive;
while (rs != WebBrowserReadyState.Complete)
{
this.Invoke(new Action(() => rs = wb.ReadyState));
System.Threading.Thread.Sleep(300);
}
}
```
Here is a bit more generic version of `testButton_Click` method:
```
private async void testButton_Click(object sender, EventArgs e)
{
var actions = new List<Action>()
{
() => wb.Navigate("www.yahoo.com"),
() => wb.Navigate("www.microsoft.com"),
() => wb.Navigate("asp.net"),
() => wb.Document.InvokeScript("eval", new[] { "$('p').css('background-color','yellow')" }),
() => {
bool testFlag = false;
testFlag = wb.DocumentText.Contains("Get Started");
if (testFlag) { /* TODO */ }
}
//...
};
await Task.Factory.StartNew(() => actions.ForEach((x)=> stepTheWeb (x)));
}
```
**[Update]**
I have adapted my "quick & dirty" sample by borrowing and sligthly refactoring [@Noseratio's `NavigateAsync` method from this topic](https://stackoverflow.com/questions/21140349/get-readystate-from-webbrowser-control-without-doevents/21152965#21152965).
New code version would automate/execute asynchronously in UI thread context not only navigation operations but also Javascript/AJAX calls - any "lamdas"/one automation step task implementation methods.
All and every code reviews/comments are very welcome. Especially, from `@Noseratio`. Together, we will make this world better ;)
```
public enum ActionTypeEnumeration
{
Navigation = 1,
Javascript = 2,
UIThreadDependent = 3,
UNDEFINED = 99
}
public class ActionDescriptor
{
public Action Action { get; set; }
public ActionTypeEnumeration ActionType { get; set; }
}
/// <summary>
/// Executes a set of WebBrowser control's Automation actions
/// </summary>
/// <remarks>
/// Test form shoudl ahve the following controls:
/// webBrowser1 - WebBrowser,
/// testbutton - Button,
/// testCheckBox - CheckBox,
/// totalHtmlLengthTextBox - TextBox
/// </remarks>
private async void testButton_Click(object sender, EventArgs e)
{
try
{
var cts = new CancellationTokenSource(60000);
var actions = new List<ActionDescriptor>()
{
new ActionDescriptor() { Action = ()=> wb.Navigate("www.yahoo.com"), ActionType = ActionTypeEnumeration.Navigation} ,
new ActionDescriptor() { Action = () => wb.Navigate("www.microsoft.com"), ActionType = ActionTypeEnumeration.Navigation} ,
new ActionDescriptor() { Action = () => wb.Navigate("asp.net"), ActionType = ActionTypeEnumeration.Navigation} ,
new ActionDescriptor() { Action = () => wb.Document.InvokeScript("eval", new[] { "$('p').css('background-color','yellow')" }), ActionType = ActionTypeEnumeration.Javascript},
new ActionDescriptor() { Action =
() => {
testCheckBox.Checked = wb.DocumentText.Contains("Get Started");
},
ActionType = ActionTypeEnumeration.UIThreadDependent}
//...
};
foreach (var action in actions)
{
string html = await ExecuteWebBrowserAutomationAction(cts.Token, action.Action, action.ActionType);
// count HTML web page stats - just for fun
int totalLength = 0;
Int32.TryParse(totalHtmlLengthTextBox.Text, out totalLength);
totalLength += !string.IsNullOrWhiteSpace(html) ? html.Length : 0;
totalHtmlLengthTextBox.Text = totalLength.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
// asynchronous WebBroswer control Automation
async Task<string> ExecuteWebBrowserAutomationAction(
CancellationToken ct,
Action runWebBrowserAutomationAction,
ActionTypeEnumeration actionType = ActionTypeEnumeration.UNDEFINED)
{
var onloadTcs = new TaskCompletionSource<bool>();
EventHandler onloadEventHandler = null;
WebBrowserDocumentCompletedEventHandler documentCompletedHandler = delegate
{
// DocumentCompleted may be called several times for the same page,
// if the page has frames
if (onloadEventHandler != null)
return;
// so, observe DOM onload event to make sure the document is fully loaded
onloadEventHandler = (s, e) =>
onloadTcs.TrySetResult(true);
this.wb.Document.Window.AttachEventHandler("onload", onloadEventHandler);
};
this.wb.DocumentCompleted += documentCompletedHandler;
try
{
using (ct.Register(() => onloadTcs.TrySetCanceled(), useSynchronizationContext: true))
{
runWebBrowserAutomationAction();
if (actionType == ActionTypeEnumeration.Navigation)
{
// wait for DOM onload event, throw if cancelled
await onloadTcs.Task;
}
}
}
finally
{
this.wb.DocumentCompleted -= documentCompletedHandler;
if (onloadEventHandler != null)
this.wb.Document.Window.DetachEventHandler("onload", onloadEventHandler);
}
// the page has fully loaded by now
// optional: let the page run its dynamic AJAX code,
// we might add another timeout for this loop
do { await Task.Delay(500, ct); }
while (this.wb.IsBusy);
// return the page's HTML content
return this.wb.Document.GetElementsByTagName("html")[0].OuterHtml;
}
``` |
16,506,865 | Hi I am trying to setup a project using [composer](http://getcomposer.org/).
I am able to install [CakePHP](http://cakephp.org/) but I am getting a hard time installing [cakephp/debug\_kit](http://plugins.cakephp.org/p/52-debug_kit) on a custom direcoty. I am trying to install it on "vendor/cakephp/cakephp/app/Plugin/DebugKit/" because [CakePHP](http://cakephp.org/) require its plugins to be installed on the Plugin directory of its "app" folder.
I already setup my composer.json according [this](http://getcomposer.org/doc/faqs/how-do-i-install-a-package-to-a-custom-path-for-my-framework.md) site but still the plugin get installed on "vendor/cakephp/debug\_kit"
Here is my composer.json maybe there is something wrong with my code.
I am just a newbie in using composer.json.
```
{
"name" : "notmii/pse",
"repositories" :
[{
"type": "package",
"package":
{
"name" : "cakephp/cakephp",
"version" : "2.3.5",
"source" :
{
"type" : "git",
"url" : "git://github.com/cakephp/cakephp.git",
"reference" : "2.3.5"
},
"bin" : ["lib/Cake/Console/cake"]
}
},
{
"type": "package",
"package":
{
"name" : "cakephp/debug_kit",
"version" : "2.2.0",
"source" :
{
"type" : "git",
"url" : "https://github.com/cakephp/debug_kit.git",
"reference" : "2.2.0"
}
}
}],
"extra":
{
"installer-paths":
{
"vendor/cakephp/cakephp/app/Plugin/DebugKit/": ["cakephp/debug_kit"]
}
},
"require" :
{
"php": ">=5.3",
"cakephp/cakephp" : ">=2.3.5",
"cakephp/debug_kit": "2.2.*"
}
}
``` | 2013/05/12 | [
"https://Stackoverflow.com/questions/16506865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1260962/"
] | If you want to add all plugins to `app/Plugin` instead of defining custom path for each plugin, update your `extra` block like this:
```
"extra": {
"installer-paths": {
"app/Plugin/{$name}/": ["type:cakephp-plugin"]
}
}
``` | [Composer Packages Custom Installer plugin](https://github.com/farhanwazir/cpcinstaller), you don't need to develop custom installer. Just FORK it and add your instructions in config directory under src/Installer [CPCInstaller](https://github.com/farhanwazir/cpcinstaller) will do everything for you. |
304,317 | Does MySQL index foreign key columns automatically? | 2008/11/20 | [
"https://Stackoverflow.com/questions/304317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] | Apparently an index is created automatically as specified in [the link robert has posted](http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html).
>
> InnoDB requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. **Such an index is created on the referencing table automatically if it does not exist.** (This is in contrast to some older versions, in which indexes had to be created explicitly or the creation of foreign key constraints would fail.) index\_name, if given, is used as described previously.
>
>
>
[InnoDB and FOREIGN KEY Constraints](http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html) | Yes, `Innodb` provide this. You can put a foreign key name after `FOREIGN KEY` clause or leave it to let MySQL to create a name for you. MySQL automatically creates an index with the `foreign_key_name` name.
```
CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action
``` |
5,072,415 | I have 2 different radio button fields sets `name=top` and `name=bottom`.
```
<div class="branch">
<div class="element">
<label for="top">top color:</label>
<input type="radio" value="1" name="top" checked="checked">black
<input type="radio" value="0" name="top">white
<input type="radio" value="null" name="top">transparent
</div>
<div class="element">
<label for="bottom">bottom color:</label>
<input type="radio" value="1" name="bottom">black
<input type="radio" value="0" name="bottom" checked="checked">white
<input type="radio" value="null" name="bottom">transparent
</div>
</div>
```
I know how to detect the value of a radio button at the time it's selected and I reference `$(this)` to get the value that's just been selected. What I'm trying to do is trigger the reading when an unrelated button is clicked. I click another element (not the radio button itself) and at this point I want to read which value (black, white, transparent) is checked for `name=top` and `name=bottom`. How do I do this with jquery? I don't have reference to `$(this)` anymore. Do I need to loop through each input type radio option and check if it's checked? I hope someone can suggest a better way. In the example above, I want to read that the checked value for top color = 1 and the checked value for bottom color is 0 | 2011/02/21 | [
"https://Stackoverflow.com/questions/5072415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605098/"
] | Ummm, you have a `cout << '\n';` inside that loop... so it'll print a `newline` for each time it goes through the loop. | Because of the:
```
for(;;)
```
Which stands for 'do this forever' combined with the fact that the rows and columns may never be both set to zero with cin.
Try typing in zeroes for the cin input and it might end.
Also write:
```
cout << endl;
```
That is just what I do because I like flushing buffers. |
70,737,474 | I made a simple `sqrt` struct using TMP. It goes like :
```
template <int N, int i>
struct sqrt {
static const int val = (i*i <= N && (i + 1)*(i + 1) > N) ? i : sqrt<N, i - 1 >::val;
};
```
but is causes error since it does not have the exit condition, so I added this :
```
template <int N>
struct sqrtM<N, 0> {
static const int val = 0;
};
```
So as I understand it, in case we use TMP, the compiler goes into recursion loop until they meet the exit condition (in terms of `sqrt`, usally when i = 0 or i = 1)
But if we make a recursive `sqrt` function, compiler doesn't have to dive until it meets `i = 0`, because at some point, recursive function ends at exact location where condition `(i*i <= N && (i + 1)*(i + 1) > N)` is met.
So let's assume we put very large value into our `sqrt`, then our TMP should do extra computation of `sqrt<N, sqrt<N-1>::val>` compared to the recursive version of `sqrt` function, and it seems waste to me.
Am I getting it wrong? Or TMP is really worth it even in this kind of cases? | 2022/01/17 | [
"https://Stackoverflow.com/questions/70737474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6543053/"
] | The thing is that in TMP you can't go very deep by default. The depth is limited but the limit can be changed (see [this](https://www.ibm.com/docs/en/xl-c-and-cpp-linux/13.1.1?topic=descriptions-ftemplate-depth-qtemplatedepth-only)). The other thing is that you write your TMP code with recursion but it can be compiled into a non-recursive code so it doesn't have the extra cost of saving the state and doing a function call as it goes deeper. So it is a tradeoff between compile time, executable size and runtime performance. If your N is not known at compile time, then you can't use TMP. | There is a difference between evaluation and instantiation.
in
```
template <int N, int i>
struct sqrt {
static const int val = (i*i <= N && (i + 1)*(i + 1) > N) ? i : sqrt<N, i - 1 >::val;
};
```
it should instantiate `sqrt<N, i - 1 >` to retrieve associated `val`, even if that value won't be taken at the end.
You can write code differently to delay instantiation of `sqrt<N, i - 1 >`
```
template <int N> struct val_identity { static const int val = N; };
template <int N, int i>
struct sqrt {
static const int val =
std::conditional_t<i * i <= N && N < (i + 1) * (i + 1),
val_identity<i>,
sqrt<N, i - 1 >
>::val;
};
```
[Demo](https://godbolt.org/z/b64d6f1jK) |
258,396 | I'm setting up a secure server for my use only to store encrypted files, but it will need to be accessed from the internet. The server itself is in a secure location with no physical access which is fine, but I'm more worried about the internet side. I'm thinking of using Ubuntu with no other software apart from open ssh.
How do I set up iptables to block all connections apart from ssh? And how do I set up open ssh to lock out any more than 2 failed attempts? | 2011/04/11 | [
"https://serverfault.com/questions/258396",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | ```
iptables -A INPUT -p tcp -m state --state NEW --dport 22 -m recent --name sshattack --set
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --name sshattack --rcheck --seconds 60 --hitcount 4 -j LOG --log-prefix 'SSH REJECT: '
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --name sshattack --rcheck --seconds 60 --hitcount 4 -j REJECT --reject-with tcp-reset
```
See, eg, [my writeup on the subject](http://www.teaparty.net/technotes/ssh-rate-limiting.html) for more details (including where in your firewall rules to put these, which **does** matter).
The other respondents' recommendations to allow only key-based ssh I **thoroughly** endorse, because it renders brute-force password guessing useless; but you could go even further and allow only two-factor authentication, see [my writeup on the yubikey](http://www.teaparty.net/technotes/yubikey.html) for more details on that. | Here's a basic guide to [securing Linux ssh](http://www.farinspace.com/secure-login-linux-server/). This covers setting up (and only using) Public Key Authentication, disabling root login (and seting up sudo), and using non-standard ports.
Here's an [iptables guide](http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO_:_Ch14_:_Linux_Firewalls_Using_iptables). |
22,120,859 | ```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct fileData
{
char fileName[100];
int size;
char type;
long timestamp;
};
void print(struct fileData *myFile);
int main(void)
{
struct fileData *toUse = malloc(sizeof(toUse));
char temp[100] = {0};
printf("Enter the type:");
getchar();
scanf("%c", toUse->type);
getchar();
printf("Enter the filename:");
fgets(temp, 100, stdin);
strcpy(toUse->fileName, temp);
printf("Enter the access time:");
scanf("%lf", toUse->timestamp);
printf("Enter the size:");
scanf("%d", toUse->size);
print(toUse);
free(toUse);
}
void print(struct fileData *myFile)
{
printf("Filename: %s - Size: %d - Type: [%c] - Accessed @ %ld\n", myFile->fileName, myFile->size, myFile->type, myFile->timestamp);
}
```
Ok so here is what the program is supposed to do:
1. Make a structure for data of a file (must use a pointer in main)
2. malloc memory for the structure, and prompt/read in data about your structure
3. Write 1 function that will print out that data
So... above is my code and i have a few questions:
1. You may notice i have some getchar()'s in there, reason for that is because for whatever reason when i run ./a.out it always skips over the first scanf which i was guessing because when i press enter it gets stuck in stdin and resolves that to scanf, so putting the getchar()'s work.. but is there anyway to avoid this from happening all together? This never happened in any other of my programs...
2. As you can see i am using fgets to get the string as the file name may contain spaces, which scanf doesn't work with. But my question is, do i have to store it in temp and then copy it over or could i just do:
fgets(toUse->fileName, 100, stdin);
I am assuming not, for the same reason i can't use this:
toUse->fileName = "Test";
So is this correct the way i am currently doing it, or is there a better way?
3. Now for the actual question that is making my program fail, the next reading in "Enter access time:", it will let me enter a number but as soon as i press enter i get a Seg Fault.. So why? Is it because i am using %lf? Is it something completely different? Should i just be using %l in the scanf? [When i do this, it will skip right over the question.. I am assuming for the same reason it skips over the other ones.. Something to deal with the enter]. So could this be it, the enter after i type the long "1234567890" is causing it to seg fault or am i doing something wrong?
Any questions answered would be helpful, thanks! | 2014/03/01 | [
"https://Stackoverflow.com/questions/22120859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494817/"
] | 1. Try scanf("%c\n", ...) so that scanf waits for a return character
2. fgets(toUse->fileName, 100, stdin); can work, toUse->fileName = "Test"; don't because "Test" is a pointer to the "Test" string, but toUse->fileName is a buffer, you can fgets in it directly
3. %lf is a long float format. Try %ld in your scanf. Then you need to give scanf an address to write to, use scanf("%ld", &toUse->timestamp);
Same for size: scanf("%d", toUse->size); should be scanf("%d", &toUse->size); | Because you didn't allocate enough space.
`SizeOf(toUse)` = size of an address, on a 32 bit machine = 4 bytes, but clearly the size of your structure is more than 100 Bytes.
So, you need to allocate the sizeof the `structure fileDate`.
Change:
```
struct fileData *toUse = malloc(sizeof(toUse));
```
to:
```
struct fileData *toUse = malloc(sizeof(struct fileData));
```
and to avoid compiler warning for incompatible pointer types:
```
struct fileData *toUse = (struct fileData *) malloc(sizeof(struct fileData));
``` |
4,798 | How should I prepare my army when attacking someone who has 12+ battlecruisers?
(Protoss/Zerg/Terran answers are more than appreciated) | 2010/08/08 | [
"https://gaming.stackexchange.com/questions/4798",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/2473/"
] | You shouldn't be giving him the time to get those 12+ Battlecruisers.
So you should press him earlier so he doesn't get that far up the tech tree AND has the time to built that many Battlecruisers | First of all, I do not understand why people are telling you, "You should not give him that much time to build 12 Battlecruisers in the first place". That is clearly not a solution to fighting Battlecruisers.
For Protoss players up against Battlecruisers, Phoenixes **CANNOT** take on Battlecruisers. Go try it, they will get *demolished*. **You HAVE TO get Voidrays** against Battlecruisers. Voidrays were made for this reason. The charge is the only thing that can drop their HP and storm does not work effectively on mech units. Also, a side note, you can charge your Voidrays before you enter a battle by attacking a rock or even your own structures (if you are desperate).
You can also get Mothership with Carriers and Voidrays as well. If you do, do not worry about letting your mothership die. While it is tanking, you can destroy half of your opponents fleet by then.
Basically, nothing other than Protoss air (Voidrays, Carriers, Mothership) can take on Battlecruisers. I should say, not as well. If you find yourself stuck in a Gateway build, then you should try out tzene's strategy. Otherwise, you should go air against Battlecruisers.
However, if you run into a situation where he has the superior army then you can always aim for a base race; Avoid his army and wait until he attacks, so you can attack his base without him defending. |
1,775,302 | Some time ago i Wrote a service with a timer that make an action every n minutes. All was right. But now, I want to write a service that waits for a signal, message or something from a gui application for doing his job.
I want me process to sleep pacefull (not in a infinite loop sniffing something) until my winforms application tell him "Hey, do things and give me a ring when the work is done"
could someone give me staring point?
Thanks. | 2009/11/21 | [
"https://Stackoverflow.com/questions/1775302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81076/"
] | You can use [Windows Communication Foundation](http://msdn.microsoft.com/en-us/netframework/aa663324.aspx) to allow your client to communicate with your service, send it requests, and register to receive progress events from existing running jobs. | You need to use interprocess communication (IPC). For C#, this usually means either .NET remoting -- on older versions of .NET -- or Windows Communication Foundation (WCF) -- on newer versions of .NET.
Essentially, the client application connects to an interface implemented by the service, and can then call methods on it, as if it was in the same process.
If this is too complicated, you could use a named event object, which the service waits on, and the client sets. |
79,870 | I'm trying to implement ssh server under a custom Debian-based installation, which has no GUI, and yet no ssh access. How can I know whether SSH is installed, and how can I know whether the firewall actually allows it or not ? | 2009/12/07 | [
"https://superuser.com/questions/79870",
"https://superuser.com",
"https://superuser.com/users/7768/"
] | To check whether the firewall allows it (assuming you're using iptables) write `iptables -l` (with root, otherwise put `sudo` in front).
As to whether the ssh-server is installed or not (assuming you're using packages) do `aptitude search openssh-server` and check the status marker next to the name.
If you're outside the server, simply try to connect to the IP on port 22 to verify/check that it is open :) | 1. If you have console access, `dpkg -l openssh-server` will tell you whether or not the SSH server package is installed.
2. Running `pgrep sshd` will return the process ID of the SSH daemon if it is running. |
16,627 | I'm having a very frustrating problem with my Joomla 1.6 site. I cannot add any new extensions through the admin interface. I have tried to upload the extension, or to use the search folder option or even the direct link. Neither of these options work, and all that happens is that the page tries to load forever until it finally timesout with a blank white page (no further error messages).
I have tried this with multiple browsers (Chrome,FF,IE) and I have tried it with different extensions (modules, components, templates - all the same result). So I don't think it has anything to do with what I am uploading, but more likely the problem is something with the post action. I have also seen the exact same error occur when I try to update menu items or even create new menu items.
I am not getting this error with a duplicate of the site in the dev environment, but only get this on my shared web hosting live server. This is on a Windows IIS / PHP / mySQL environment. | 2011/07/08 | [
"https://webmasters.stackexchange.com/questions/16627",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/8885/"
] | There's a lot more to SEO than a Google Places listing or number of pages in a website. There are at least 200 ranking factors and they vary in importance.
The site that is outranking you *probably* has better quality links then you do. Quantity of backlinks is irrelevant. Quality is what matters. Not to mention you don't know how many backlinks they really have since Google doesn't report all of them on purpose.
Their URL structure may be more search engine friendly. This includes having keywords in the domain. Having "sprinklers" in their domain name definitely is helping them out.
If you want to make sure your pages are optimized you should start with [this question](https://webmasters.stackexchange.com/questions/2/what-are-the-best-ways-to-increase-your-sites-position-in-google) and then continue to do more research on SEO. Especially in this site since there are a lot of SEO questions with good answers. | **How Google determines local ranking**
1. Local results are based primarily on [relevance, distance, and prominence](https://support.google.com/business/answer/7091?hl=en#factors).
2. Use Google Ads for local places. It's works. |
52,610,246 | I have Chat service in .NET Core Web API, handling chat messages through Signal R when clients are online.
Also, i have mobile clients (android/apple) and i need to handle messages sent when client is in offline mode. I am aware if clients are offline/online. So, when the client is offline, i want to send message to apple/android push notification server so it can notify the device about new message(s).
Which options do i have to connect net core Web API to android/apple push notification servers? Any experiences with sending client push notifications to mobile clients from .net service? | 2018/10/02 | [
"https://Stackoverflow.com/questions/52610246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7450326/"
] | You need To make a POST request to <https://fcm.googleapis.com/fcm/send> with the following parameters
**Header**
* *Authorization:* `key=YOUR_SERVER_KEY`
* *Content-Type:* `Application/JSON`
**Body:**
```
{
"to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
"collapse_key" : "type_a",
"notification" : {
"body" : "First Notification",
"title": "Collapsing A"
},
"data" : {
"body" : "First Notification",
"title": "Collapsing A",
"key_1" : "Data for key one",
"key_2" : "Hellowww"
}
```
You can get your server Token from `Firebase Console`. Also you need to [set up APN](https://firebase.google.com/docs/cloud-messaging/ios/certs) in order for this to work on iOS.
You can find More info [here](https://firebase.google.com/docs/cloud-messaging/) | You can use any cloud solutions for this case, like Azure Notification Hub.
You can check the [documentation](https://learn.microsoft.com/en-us/azure/notification-hubs/) and configure your app with Notification Hub. With default configuration you will be able to broadcast your notification to all registered devices.
But in your case you need to send a notification to a specific device. In this case you need to use tags. When you register the device with Notification Hub register it with an unique id. So when you send a notification send it with same unique id as tag and it will received by that device only. |
3,514,321 | For example, $X\_1, X\_2 \sim U[0,t]$. Does it imply that $2X\_1+X\_2 \sim U[0,3t]$? | 2020/01/19 | [
"https://math.stackexchange.com/questions/3514321",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/732644/"
] | A linear combination of uniform random variables is in general not uniformly distributed. In this case we have $Y=2X\_1+X\_2$, where $2X\_1\sim\mathrm{Unif}(0,2t)$ and $X\_2\sim\mathrm{Unif}(0,t)$. The density of $2X\_1$ is $f\_{2X\_1}(x) =\frac1{2t}\mathsf 1\_{(0,2t)}(x)$, and the density of $X\_2$ is $f\_{X\_2}(x) = \frac 1t\mathsf 1\_{(0,t)}(x)$. Therefore the density of the sum is given by convolution:
$$
f\_Y(y) = f\_{2X\_1}\star f\_{X\_2}(y) = \int\_{\mathbb R} f\_{2X\_1}(x)f\_{X\_2}(y-x)\ \mathsf dx = \int\_{\mathbb R}\frac1{2t}\mathsf 1\_{(0,2t)}(x)\cdot\frac 1t\mathsf 1\_{(0,t)}(y-x)\ \mathsf dx.
$$
Now, $\mathsf 1\_{(0,2t)}(x)\mathsf 1\_{(0,t)}(y-x)$ is equal to one when $0<x<2t$ and $0<y-x<t$ and zero otherwise. There are three cases to consider:
If $0<y<t$ then the convolution integral is
$$
\int\_0^y \frac1{2t^2}\ \mathsf dx = \frac y{2t^2}.
$$
If $t<y<2t$ then the convolution integral is
$$
\int\_{y-t}^y \frac1{2t^2}\ \mathsf dx = \frac1{2t}.
$$
If $2t<y<3t$ then the convolution integral is
$$
\int\_{y-t}^{2t} \frac1{2t^2}\ \mathsf dx = \frac{3 t-y}{2 t^2}.
$$
Hence the density of $Y$ is given by
$$
\frac y{2t^2}\mathsf 1\_{(0,t)}(y) + \frac1{2t}\mathsf 1\_{(t,2t)}(y) + \frac{3 t-y}{2 t^2}\mathsf 1\_{(2t,3t)}(y).
$$ | **If** $X\_2$ is always equal to $X\_1,$ and $X\_1\sim\operatorname{Uniform}[0,t],$ then $2X\_1+X\_2\sim\operatorname{Uniform}[0,3t].$ At the opposite extreme, if $X\_1,X\_2\sim\operatorname{Uniform}[0,t]$ and $X\_1,X\_2$ are independent, then $2X\_1+X\_2$ is **not** uniformly distributed. You haven't told use the **joint** distribution of $X\_1,X\_2,$ but only how each one **separately** is distributed. |
31,757,852 | I've looked around a lot, and I understand that there's a lot of ways to detect internet explorer.
My problem is this: I have an area on my HTML document, that when clicked, calls a JavaScript function that is incompatible with internet explorer of any kind.
I want to detect if IE is being used, and if so, set the variable to true.
The problem is, I am writing my code out of Notepad++, and when I run the HTML code in browser, none of the methods for detecting IE work. I think the problem is that I am running it out of Notepad++. I need to be able to detect IE, so that based on the variable, I can disable that area of the site. I have tried this:
```
var isIE10 = false;
if (navigator.userAgent.indexOf("MSIE 10") > -1) {
// this is internet explorer 10
isIE10 = true;
window.alert(isIE10);
}
var isIE = (navigator.userAgent.indexOf("MSIE") != -1);
if(isIE){
if(!isIE10){
window.location = 'pages/core/ie.htm';
}
}
```
but it doesn't work. How can I detect IE out of Notepad++? That's what I'm testing the HTML out of, but I need a method that'll work with that.
edit
====
I noticed someone has marked this as a duplicate, and that is understandable. I suppose I was not clear. I cannot use a JQuery answer, so this is not a duplicate as I am asking for a vanilla JS answer.
Edit #2
=======
Is there also a way to detect the Microsoft Edge browser? | 2015/08/01 | [
"https://Stackoverflow.com/questions/31757852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm using UAParser
<https://github.com/faisalman/ua-parser-js>
```
var a = new UAParser();
var name = a.getResult().browser.name;
var version = a.getResult().browser.version;
``` | If we need to check Edge please go head with this
if(navigator.userAgent.indexOf("Edge") > 1 ){
```
//do something
```
} |
1,168,668 | So, I have an iterative function that looks something like this.
$$f(x\_n) = (x\_n + 0.08) \cdot 0.98$$
e.g. So if $n = 2$ and $x$ started at $0$, then the equation would be equal to $(((0 + 0.8) \cdot 0.98) + 0.08) \cdot 0.98$, which is $0.155232$.
Is it possible to create a formula that can find the value of any iteration of the function?
e.g being able to rewrite the answer as a polynomial (where $x$ is an integer). If it is, how is it done? | 2015/02/28 | [
"https://math.stackexchange.com/questions/1168668",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/219887/"
] | We have $$x\_n = 0.98 \cdot x\_{n-1} + 0.08 \cdot 0.98$$
$$x\_{n+1} = 0.98 \cdot x\_n + 0.08 \cdot 0.98$$
Subtract to get
$$x\_{n+1}=1.98 \cdot x\_n-0.98 \cdot x\_{n-1}$$
You get the following characteristic polynomial
$$p(x)=x^2-1.98x+0.98$$
Whose roots are $x\_1=1, \space x\_2=0.98$
So the general formula is $x\_n=c\_1+c\_2\cdot 0.98^n$
Using $x\_1,x\_2$ you can find $c\_1=3.92, c\_2=-3.92$ so your final equation is:
$$x\_n=3.92-3.92\cdot 0.98^n$$ | If the starting value is $t$ and the numbers $0.08,\ 0.98$ are called $a,b$ then your iteration takes $t$ into $(t+a)b.$ Working out the first few iterates we have
$$t,\\ bt+ab,\\ b^2t+ab(b+1),\\ b^3t+ab(b^2+b+1).$$
If we apply the sum of a geometric series to the lengthening sequence of powers of $b$ occurring on the right sides, we get for the $n$th iterate the formula
$$ b^n t +ab\cdot \frac{b^n-1}{b-1}.$$
One can check that this matches the first few terms above, and it's likely not hard to show it keeps working using induction. |
72,104,323 | I am trying to sum up values inside an object, but i am adding a Nullish coalescing operator if undefined or null then it should have zero value. But here instead of getting 10 i am getting 4 only.
```js
let data = {
a: 4,
b: 6,
c: null
}
console.log(data?.a ?? 0 + data?.b ?? 0 + data?.c ?? 0)
```
Any help is appreciated | 2022/05/03 | [
"https://Stackoverflow.com/questions/72104323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10829671/"
] | Just add small brackets this will do. The reason for above not running is because the `??` operator is conditional and will evaluate the first statement since there is value for `data?.a` it will not run the right part of it which is `0 + data?.b ?? 0 + data?.c ?? 0`
```js
let data = {
a: 4,
b: 6,
c: null
}
console.log((data?.a ?? 0) + (data?.b ?? 0) + (data?.c ?? 0))
``` | Ideal case for [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).
* First: make an array of values with `Object.value`
* Next: reduce (awesome method to master)
* Optional: Use `+` operator for elegant type conversion (might not work in every case)
```
console.log(Object.values(data).reduce(function (sum, value) { return sum + +value }, 0))
```
Good practice is to learn from utility / helper libraries like [lodash](https://lodash.com/) or [ramda](https://ramdajs.com/). [Lodash](https://github.com/lodash/lodash/blob/master/.internal/baseSum.js) provides nice solution as well |
34,791,244 | I am using Retrofit 2 (2.0.0-beta3) with OkHttp client in Android application and so far everything going great. But currently I am facing issue with OkHttp Interceptor. The server I am communicating with is taking access token in body of request, so when I intercept the request to add auth token or in authenticate method of Authenticator when I need to add updated auth token, I need to modify body of request for this purpose. But it looks like I can only add data in headers but not in the body of ongoing request. The code I have written so far is as follows:
```
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (UserPreferences.ACCESS_TOKEN != null) {
// need to add this access token in request body as encoded form field instead of header
request = request.newBuilder()
.header("access_token", UserPreferences.ACCESS_TOKEN))
.method(request.method(), request.body())
.build();
}
Response response = chain.proceed(request);
return response;
}
});
```
Can anyone point me to the right direction as how to modify request body to add my access token (first time or updated after token refresh)? Any pointer to right direction would be appreciated. | 2016/01/14 | [
"https://Stackoverflow.com/questions/34791244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114956/"
] | Since this cannot be written in the comments of the previous answer by @Fabian, I am posting this one as separate answer. This answer deals with both "application/json" as well as form data.
```
import android.content.Context;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
/**
* Created by debanjan on 16/4/17.
*/
public class TokenInterceptor implements Interceptor {
private Context context; //This is here because I needed it for some other cause
//private static final String TOKEN_IDENTIFIER = "token_id";
public TokenInterceptor(Context context) {
this.context = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RequestBody requestBody = request.body();
String token = "toku";//whatever or however you get it.
String subtype = requestBody.contentType().subtype();
if(subtype.contains("json")){
requestBody = processApplicationJsonRequestBody(requestBody, token);
}
else if(subtype.contains("form")){
requestBody = processFormDataRequestBody(requestBody, token);
}
if(requestBody != null) {
Request.Builder requestBuilder = request.newBuilder();
request = requestBuilder
.post(requestBody)
.build();
}
return chain.proceed(request);
}
private String bodyToString(final RequestBody request){
try {
final RequestBody copy = request;
final Buffer buffer = new Buffer();
if(copy != null)
copy.writeTo(buffer);
else
return "";
return buffer.readUtf8();
}
catch (final IOException e) {
return "did not work";
}
}
private RequestBody processApplicationJsonRequestBody(RequestBody requestBody,String token){
String customReq = bodyToString(requestBody);
try {
JSONObject obj = new JSONObject(customReq);
obj.put("token", token);
return RequestBody.create(requestBody.contentType(), obj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private RequestBody processFormDataRequestBody(RequestBody requestBody, String token){
RequestBody formBody = new FormBody.Builder()
.add("token", token)
.build();
String postBodyString = bodyToString(requestBody);
postBodyString += ((postBodyString.length() > 0) ? "&" : "") + bodyToString(formBody);
return RequestBody.create(requestBody.contentType(), postBodyString);
}
}
``` | I'm using this way to verify my token
```
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS) //retrofit default 10 seconds
.writeTimeout(30, TimeUnit.SECONDS) //retrofit default 10 seconds
.readTimeout(30, TimeUnit.SECONDS) //retrofit default 10 seconds
.addInterceptor(logging.setLevel(HttpLoggingInterceptor.Level.BODY))
.addInterceptor(new BasicAuthInterceptor())
.build();
```
Here i'm sending token through BasicAuthInterceptor
```
public class MyServiceInterceptor implements Interceptor {
private String HEADER_NAME="Authorization";
private String OBJECT_NAME="Bearer";
private String SPACE=" ";
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder requestBuilder = request.newBuilder();
String token= PreferenceManager.getInstance().getString(PreferenceManager.TOKEN);
if (token != null) { {
requestBuilder.addHeader(HEADER_NAME, OBJECT_NAME+SPACE+ token);
}
}
return chain.proceed(requestBuilder.build());
```
}
} |
3,146,013 | I've not been able to find any documentation stating the existence of an API that can be used to automate things inside of a qemu guest.
For example, I would like to launch a process inside of the guest machine from the host machine. Libvirt does not appear to contain such functionality. | 2010/06/30 | [
"https://Stackoverflow.com/questions/3146013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29049/"
] | [Note: Automation without using any virtualization API. From my [blog post](http://db42.wordpress.com/2011/10/14/guest-automation-with-qemukvm/).]
**Step 1:**
By default, QEMU uses SDL to display the VGA output. So, the first step is make this interaction with QEMU through standard I/O. QEMU provides an option for this.
From QEMU docs:
>
> **-nographic** Normally, QEMU uses SDL to display the VGA output. With this option, you can totally disable graphical output so that QEMU is
> a simple command line application. The emulated serial port is
> redirected on the console. Therefore, you can still use QEMU to debug
> a Linux kernel with a serial console.
>
>
>
So, all you have to do is invoke QEMU with `-nographic`.
```
qemu -nographic -hda guest.disk
```
**Step 2:**
Now that you can interact with your guest (or QEMU process) through command line, you have to automate this interaction. The obvious way to do this in python is start the QEMU process (with `-nographic`) with [subprocess module](http://jimmyg.org/blog/2009/working-with-python-subprocess.html) and then communicate with that process. But to my surprise, this just didn’t work out for me. So, I looked for some other way.
Later, I found out that the most awesome tool for this kind of jobs is [Expect](http://en.wikipedia.org/wiki/Expect). It is an automation tool for interactive applications written in TCL.
[This guide](http://www.linuxjournal.com/article/3065) should help you in getting started with Expect. Here is the script to run a guest with QEMU using Expect.
```sh
#!/usr/bin/expect -f
#starts guest vm, run benchmarks, poweroff
set timeout -1
#Assign a variable to the log file
set log [lindex $argv 0]
#Start the guest VM
spawn qemu -nographic -hda guest.disk
#Login process
expect "login: "
#Enter username
send "user\r"
#Enter Password
expect "Password: "
send "user\r"
#Do whatever you want to do with in the guest VM. ( Run a process and write result to log )
#poweroff the Guest VM
expect "# "
send "shutdown -h now\r"
``` | The [QEMU Monitor](http://en.wikibooks.org/wiki/QEMU/Monitor) can interact with guest systems to a limited extent using it's own console. This includes reading registers, controlling the mouse/keyboard, and getting screen dumps.
There is a [QEMU Monitor Protocol (QMP)](http://wiki.qemu.org/QMP) that let's you pass JSON commands to and read values from the guest system. |
16,060,696 | I'm working with `Visual Studio`, `ASP.net`, `HTML`, `CSS`, `C#` (for the code behind), `ADO.net` and `Javascript/Jquery`.
I'm trying to make a web page with some `div` block and I want that the block never exceed the browser. Do you know : how to add a height size for `div` even if I change the resolution of my window?
PS: I'm French so, please, don't be matter about my mistake. | 2013/04/17 | [
"https://Stackoverflow.com/questions/16060696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2265252/"
] | Without further clarification of your senario, one method is to do the following:
**HTML**
```
<div id="test">
My div
</div>
```
**CSS**
```
html, body {height:100%;margin:0;padding:0}
#test {width:100%; height: 100%;position:absolute;}
``` | I've encountered screen resolution problem before and this solved my problem.
* If you want your website to dynamically changing whenever your screen resolution change you can use % in your css to all your page, containers, wrappers etc. so that it will adjust on any screen resolution. (*problem: This destroys your web design whenever the screen resolution is big*)
* The best solution I find so far and I think other professional websites also is doing is to make your width static or fixed and just let your page get on the center. This will preserve the design you made on your page and everything will stay and looks as it is.
In your CSS just add this line on your page ,containers, wrappers etc.
**margin:0 auto;**
and your site will be centered to any screen resolution. For more examples and to read more about it check this reference [How to Center a Website With CSS](http://buildinternet.com/2008/11/how-to-center-a-website-with-css/). If you want to test different screen resolutions without changing your actual screen resolution you could try it [here](http://quirktools.com/screenfly/).
Hope this helps :) |
19,620 | I'm coming from this question: <https://superuser.com/questions/359799/how-to-make-freebsd-box-accessible-from-internet>
I want to understand this whole process of `port forwarding`.
I read so many things, but am failing to understand the very basic concept of port forwarding itself.
What I have:
>
> a freebsd server sitting at my home.
>
> netgear router
>
>
>
This is what I am trying to achieve:
>
> to be able to access freebsd server from a windows machine over internet to be able to open a webbrowser and access internet.
>
>
>
> I also want to access this freebsd box from a ubuntu machine that I have.
>
>
>
It will be great if someone can please help me.
Here is the netgear router setup that I did for port forwarding.
 | 2011/08/28 | [
"https://unix.stackexchange.com/questions/19620",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/1358/"
] | ### I'll start with the raw facts :
1. You have: `A` - your FreeBSD box, `B` - your router and `C` - some machine with Internet access. This is how it looks like:
```
.-----. .-----. .-----.
| A | == | B | - - ( Internet ) - - | C |
'-----' '-----' '-----'
\_________ ________/
v
`- this is your LAN
```
Notice how your router *normally* works: it allows connections *from* machines on your LAN *to* the Internet (simply speaking). So if the `A` (or any other machine on LAN) wants to access the Internet, it will be allowed (again, just talking about basic understanding and configuration) :
```
.-----. .-----. .-----.
| A | == | B | - - ( Internet ) - - | C |
'-----' '-----' '-----'
`-->----' `--->--->---^
```
And the following is **not** allowed by default:
```
.-----. .-----. .-----.
| A | == | B | - - ( Internet ) - - | C |
'-----' '-----' '-----'
`--<----' `---<--- - - - - --<---<-----'
```
(That is, the router *protects* the machines on your LAN from being accessed from the Internet.) Notice that the router is the only part of your LAN that is seen *from* the Internet1).
2. Port forwarding is what allows the third schema to take place. This consists in telling the router *what* connection from `C`2) should go to *which* machine on the LAN. This is done based on *port numbers* - that is why it is called ***port forwarding***. You configure that by instructing the router that all the connections coming on a given port from the Internet should go to a certain machine on LAN. Here's an example for port 22 forwarded to machine `A`:
```
.------. .-------. .-----.
| A | == | B | - - ( Internet ) - - | C |
| | | | '-----'
'-|22|-' ',--|22|' |
`--<-22---' `---<---- - - - - - --<-22---'
```
3. Such connections through the Internet occur based on IP addresses. So a bit more precise representation of the above example would be:
```
.------. .-------. .-----.
| A | == | B | - - - - - ( Internet ) - - - - | C |
| | | | '-----'
'-|22|-' ',--|22|' |
`--<-A:22--' `--<-YourIP:22 - - - - --<-YourIP:22--'
```
If you do not have an Internet connection with a *static* IP, then you'd have to somehow learn what IP is currently assigned to your router by the ISP. Otherwise, `C` will not know what IP it has to connect to in order to get to your router (and further, to `A`). To solve this in an easy way, you can use a service called ***dynamic DNS***. This would make your router periodically send information to a special *DNS server* that will keep track of your IP and provide you with a *domain name*. There are quite a few free dynamic DNS providers. Many routers come with configuration options to easily contact with those.
1) This is, again, a simplification - the actual device that is seen to the Internet is the modem - which can often be integrated with the router, but might also be a separate box.
2) or any other machine with Internet connection.
---
### Now for what you want:
1. Simply allowing ssh access to your machine from the Internet is a bad idea. There are thousands of bots set up by *crackers* that search the Internet for machines with open SSH port. They typically "knock" on the default SSH port of as many IPs as they can and once they find an SSH daemon running somewhere, the try to gain *bruteforce* access to the machine. This is not only a risk of potential break-in, but also of network slow-downs while the machine is being bruteforced.
2. If you really need such access, you should at least
* assure that you have *strong* passwords for all the user accounts,
* disallow root access over SSH (you can always log in as normal user and `su` or `sudo` then),
* change the default port on which your SSH server would run,
* introduce a mechanism of disallowing numerous SSH login attempts (with icreasing time-to-wait for subsequent attempts - I don't remember how exactly this is called - I had it enabled some time ago on FreeBSD and I recall it was quite easy - try searching some FreeBSD forums etc. about securing SSH an you'll find it.)
* If possible, try to run ssh daemon only when you know you will be accessing the machine in near future an turn it off afterwards
3. Get used to going through your system logs. If you begin noticing anything suspicious, introduce additional security mechanisms like *IP tables* or *port knocking*. | This can be done by your router. On some router this feature is called `Virtual Server`
See in below part of image there are two examples of port forwarding. One is of Web and another one is of SSH. In first case any request on your WAN IP i.e. the IP of your router with port `80` will be forwarded to a LAN IP ( `192.168.2.4` in this case)
With this feature you can get services running on your PC/server running in LAN from anywhere in the world i.e. those services are not limited to LAN
[](https://i.stack.imgur.com/aJxoq.png) |
51,943,106 | It is perfectly valid to import from a URL inside an ES6 module and as such I've been using this technique to reuse modules between microservices that sit on different hosts/ports:
```
import { authInstance } from "http://auth-microservice/js/authInstance.js"
```
I'm approaching a release cycle and have started down my usual path of bundling to IIFEs using rollup. Rollup doesn't appear to support es6 module imports from URLs, I think it should as this is allowed in the spec :(
>
> **module-name**
> The module to import from. This is often a relative or absolute path name to the .js file containing the module. Certain bundlers may permit or require the use of the extension; check your environment. Only single quotes and double quotes Strings are allowed. (<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import>)
>
>
>
I've dug through the interwebs for an hour now and have come up with nothing. Has anybody seen a resolver similar to rollup-plugin-node-resolve for resolving modules from URLs? | 2018/08/21 | [
"https://Stackoverflow.com/questions/51943106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3236706/"
] | I had to move on from this quickly so ended up just writing a skeleton of a rollup plugin. I still feel that resolving absolute paths should be a core feature of rollup.
**Updated snippet**
We have been using this to transpile production code for several of our apps for a considerable amount of time now.
```js
const fs = require('fs'),
path = require('path'),
axios = require("axios")
const createDir = path => !fs.existsSync(path) && fs.mkdirSync(path)
const mirrorDirectoryPaths = async ({ cacheLocation, url }) => {
createDir(cacheLocation)
const dirs = [], scriptPath = url.replace(/:\/\/|:/g, "-")
let currentDir = path.dirname(scriptPath)
while (currentDir !== '.') {
dirs.unshift(currentDir)
currentDir = path.dirname(currentDir)
}
dirs.forEach(d => createDir(`${cacheLocation}${d}`))
return `${cacheLocation}${scriptPath}`
}
const cacheIndex = {}
const writeToDiskCache = async ({ cacheLocation, url }) => {
//Write a file to the local disk cache for rollup to pick up.
//If the file is already existing use it instead of writing a new one.
const cached = cacheIndex[url]
if (cached) return cached
const cacheFile = await mirrorDirectoryPaths({ cacheLocation, url }),
data = (await axiosInstance.get(url).catch((e) => { console.log(url, e) })).data
fs.writeFileSync(cacheFile, data)
cacheIndex[url] = cacheFile
return cacheFile
}
const urlPlugin = (options = { cacheLocation }) => {
return {
async resolveId(importee, importer) {
//We importing from a URL
if (/^https?:\/\//.test(importee)) {
return await writeToDiskCache({ cacheLocation: options.cacheLocation, url: importee })
}
//We are importing from a file within the cacheLocation (originally from a URL) and need to continue the cache import chain.
if (importer && importer.startsWith(options.cacheLocation) && /^..?\//.test(importee)) {
const importerUrl = Object.keys(cacheIndex).find(key => cacheIndex[key] === importer),
importerPath = path.dirname(importerUrl),
importeeUrl = path.normalize(`${importerPath}/${importee}`).replace(":\\", "://").replace(/\\/g, "/")
return await writeToDiskCache({ cacheLocation: options.cacheLocation, url: importeeUrl })
}
}
}
}
``` | This plugin together with the following config works for me:
<https://github.com/mjackson/rollup-plugin-url-resolve>
```js
import typescript from "@rollup/plugin-typescript";
import urlResolve from "rollup-plugin-url-resolve";
export default {
output: {
format: "esm",
},
plugins: [
typescript({ lib: ["es5", "es6", "dom"], target: "es5" }),
urlResolve(),
],
};
```
You can remove the TypeScript plugin obviously. |
34,726,547 | i'm working on ACTIVITI and need to hide this button:
[](https://i.stack.imgur.com/3oKrk.png)
if no process are instantiate, i.e. if server return this (show button):
[](https://i.stack.imgur.com/FI66R.png)
instead of this (in this case button hide):
[](https://i.stack.imgur.com/OUhOs.png)
This is the code for button i used in HTML:
```
<div ng-controller=getDeploy>
<h3>Deployments Info</h3>
<br>
<table class="table" table-bordered table-hover>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Deployment</th>
<th>Category</th>
<th class="text-center">Url</th>
</tr>
</thead>
<tbody>
<tr class="info" ng-repeat="x in names">
<td class="danger">{{ x.id }}</td>
<td>{{ x.name }}</td>
<td class="warning">{{ x.deploymentTime }}</td>
<td>{{ x.category }}</td>
<td>{{ x.url }}</td>
</tr>
</tbody>
</table>
</div>
<div style="width:200px; float:left;" ng-controller="InstanziateProcess">
<button ng-click="processdef()">
Instanzia il Processo
</button>
</div>
```
and for JS:
```
function InstanziateProcess($scope, $http, Base64) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + Base64.encode('kermit' + ':' + 'kermit');
$http.get("http://localhost:8080/activiti-rest/service/repository/process-definitions")
.then(function (response, data, status, headers, config) {
var key = response.data.data[0].key;
var req = {
method: 'POST',
url: "http://localhost:8080/activiti-rest/service/runtime/process-instances",
data: {
processDefinitionKey: key
},
headers: {
'Authorization': 'Basic ' + Base64.encode('kermit' + ':' + 'kermit'),
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
$scope.processdef = function () {
$http(req).then(function (response, data, status, headers, config) {
console.log(response);
});
};
});};
``` | 2016/01/11 | [
"https://Stackoverflow.com/questions/34726547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5740267/"
] | After some experiments, I have figured it out. Here is my solution in case someone reaches a dead end.
```
$request = new Request(
'POST',
$uri,
['Content-Type' => 'text/xml; charset=UTF8'],
$xml
);
``` | You can do that in a below way
```
$xml_body = 'Your xml body';
$request_uri = 'your uri'
$client = new Client();
$response = $client->request('POST', $request_uri, [
'headers' => [
'Content-Type' => 'text/xml'
],
'body' => $xml_body
]);
``` |
16,082,054 | We have an eShop build on prestashop and we are developing new features every week. I'm writing here because I don't find the correct way to update our production environment with the changes, without having to upload all the code again or having to upload the modified files manually.
Now we work like this:
* Our developers work with local copies connected to a GIT repo.
* Once we have some new features and we want to create a new release I download the latest version from the repo and test it locally on another computer.
=> HERE comes the part that I don't like... :)
* Once all the tests have been passed in my local copy we take all the files that have been modified (looking at the commits) and we upload them manually to the development environment.
* We test it again and if it works we upload the same files to the production environment.
We have been thinking in linking both environments source files with the repo as well, but I don't link it because I don't want to have the .git folder published messing my production code.
I didn't find the way of having a tested copy of our code pushed at our GIT REPOSITORY and update the servers automatically, without having to upload the files manually or having to upload entire folders (themes, classes, etc...) via FTP.
Is there anybody working with prestashop and GIT and having a nice automated system to do all this? :)
Many thanks in advance!
Regards,
Jordi | 2013/04/18 | [
"https://Stackoverflow.com/questions/16082054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/600377/"
] | Here is the workflow we use, it's (I guess) pretty standard:
* one git repo
* preprod domain
* prod domain
All the development is done on branches, when it's ready to ship we merge on the master.
So on the preprod we pull the branch we are working on, and on the production we only pull the master. The preprod and prod domain are on the same server, it's just a sub-domain with a htaccess to protect it.
We use this not only for Prestashop but for every thing, it works well.
For the part where you want to automatically pull the code, it must be possible (à la Heroku). But for me the most important is: you should git everywhere and forget about FTP. It's really easier and you're sure everything you need is updated. | I think you answer is not correct as well :)
Check this code if you use apache on you web server
This need to be present in your .htaccess file
```
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule . - [E=HTTP_AUTHORIZATION:%1]
```
And of course you need to have .htpasswd file.
Its mean any file or foldier which name start form "." dot, you need to autorize before you have an access to it.
See more about Mod Rewrite here: <http://httpd.apache.org/docs/2.2/rewrite/access.html>
I thik it will be useful for you Jordi. (Saludos de Bcn) |
52,857,484 | Keep getting a sync error on this line of code.
**implementation 'com.android.support:support.media.compat:28.0.0'**
No idea what it means, and I have tried multiple times to change the library with no luck
```
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-core:16.0.0:15.0.0'
```
}
Any help is appreciated!! | 2018/10/17 | [
"https://Stackoverflow.com/questions/52857484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10433454/"
] | If you want only to wrap the icons without media queries you can try this
```css
*{
font-family: verdana;
margin: 0;
}
body{
background: #eee;
}
.wrapper{
width: 100%;
max-width: 960px;
margin: 0 auto;
}
.flex-wrapper{
display:flex;
flex-wrap:wrap;
flex-grow: 1 ;
}
.profile-box-wrapper{
max-width:500px;
height:150px;
background:rgb(253, 253, 253);
border-radius:4px;
margin: 10px 10px;
display:flex;
flex-direction: column;
}
.profile-box-header img{
width:70px;
height:70px;
margin:5px 0 0 10px;
}
.profile-box-header{
display:flex;
}
.profile-name{
margin-left:10px;
flex-grow:1;
}
.profile-name h3{
}
.profile-right {
margin:0;
text-align:right;
margin-right:5px;
}
.profile-box-content{
margin:15px 0 0 10px;
}
.profile-right img{
width:25px;
height:25px;
}
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Net Ninja - CSS Flexbox</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="referrer" content="origin" />
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0">
</head>
<body>
<div class="profile-box-wrapper">
<div class="profile-box-header">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAABSlBMVEUuWHH////7YCDxyaXktpKRXyzrwJwmWHOHXjWUXyglU23oupYeT2oLSGWYZzb7VQCMWSP2zqrh5ukERmQhUGv7UAD6z6j7WxSWXyaLWCHL09n7VwDCy9KKUg9EaH7n3dVogpOcrLd3jp319/hWa3k6YXiRo6+wvMWmtL6GmqfY3uJBZn1mW1IRV3RScYZPWmCre1D+49qjckVGWWXElW79y7x/XT3+2s/9q5KyhVvDo4tGWWSjmY6MhYD59fL87ulyXUj6ZShdW1f6vqz449H8lXTvcEHqx6x1aG3HalDZa0fyaTb8hmGob2Pu1MDhb0nBdWL9pYn9tqL4dET4h2GAXV7mo5CmYFL8f1P4ajL60MTXYju1YEtrZW78nH9wXWOSZ2PfvqDBrJhzeHuzmofUpX+VkImPlZhsXE3RqoujfFjXx7m0lnvIsqAn7OWlAAAQm0lEQVR4nNWd+1sTxxrHd5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qAxG2+T5oegYAiRs75ZixpSMNREA41ZWnuf2j0dQREiHZyFvVUw1IQCDfLOs3iTrUwBEqIGdXAWsKTgEPE4gLd2dpA4u5MESog0fff+vLHmUpr8b/D1aMy1xvn7d6B4Mjwh1tHj746Rw5rBbaZUvSvhbmepdHz2GCB0RpQFIdbRwZu3a42GSDi832isvX1zkAUdVlaElo7eHfAnjaYH77KCs5QpoaWe3Jva/yFZX8F/6KH/W/9l/vP/D/FK8XoQWqtiAAAAAElFTkSuQmCC"
alt="profile pic Nuri" />
<div class="flex-wrapper">
<div class="profile-name">
<h2>John Doe</h2>
<h3>j.doe@test.nl</h3>
<p>Software-engineer</p>
</div>
<div class="profile-right">
<img src="http://www.iconarchive.com/download/i86026/graphicloads/100-flat-2/arrow-up.ico" /> +1
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQBfqvaL0rrs6wxMD_mzGnLyC5eg_Hd6UmzbMtZ9bJY0C1dKRc9" />-1
</div>
</div>
</div>
<div class="profile-box-content">
<div class="content">
<p>This is a lorum ipsum text</p>
</div>
</div>
</div>
</div>
</body>
</html>
```
changed `width` to `max-width` in `.profile-box-wrapper` so the `profile-box-wrapper` can become smaller than `500px`.
added `.flex-wrapper` around `profile-name` and `profile-right` so the icons will be under `profile-name` when they wrap.
`.flex-wrapper` is a flexbox, added `flex-wrap:wrap;` so the icons can wrap.
`flex-grow: 1;` is used so `.flex-wrapper` takes the remaining width.
check out this guide for css flex [A Complete Guide to Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) | Here's a version that scales.
```css
body {
margin: 0;
background: #eee;
font-family: verdana;
}
img {
max-width: 100%;
display: inline-block;
}
.users {
position: relative;
box-sizing: border-box;
min-height: 1px;
vertical-align: top;
width: 100%;
max-width: 960px;
margin: 0 auto;
display: flex;
justify-content: space-evenly;
}
.users-list-wrapper {
display: flex;
flex-direction: row;
flex-wrap: wrap;
margin: 0;
position: relative;
float: none;
}
.users-list-card {
background: #fff;
width: calc(33.3% - 60px);
text-align: left;
position: relative;
padding: 10px;
margin: 20px;
}
@media (min-width: 768px) and (max-width: 960px) {
.users-list-card {
width: calc(50% - 60px);
}
}
@media (max-width: 767px) {
.users-list-card {
width: 100%;
display: block;
}
}
.users-list-card-header {
display: flex;
}
.users-list-card-header h2 {
margin: 0;
}
.users-list-card-header img {
width: 50px;
height: 50px;
margin-right: 20px;
}
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Net Ninja - CSS Flexbox</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="referrer" content="origin" />
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0">
</head>
<body>
<div class="user-list">
<div class="users-list-wrapper">
<div class="users-list-card">
<div class="users-list-card-header">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAABSlBMVEUuWHH////7YCDxyaXktpKRXyzrwJwmWHOHXjWUXyglU23oupYeT2oLSGWYZzb7VQCMWSP2zqrh5ukERmQhUGv7UAD6z6j7WxSWXyaLWCHL09n7VwDCy9KKUg9EaH7n3dVogpOcrLd3jp319/hWa3k6YXiRo6+wvMWmtL6GmqfY3uJBZn1mW1IRV3RScYZPWmCre1D+49qjckVGWWXElW79y7x/XT3+2s/9q5KyhVvDo4tGWWSjmY6MhYD59fL87ulyXUj6ZShdW1f6vqz449H8lXTvcEHqx6x1aG3HalDZa0fyaTb8hmGob2Pu1MDhb0nBdWL9pYn9tqL4dET4h2GAXV7mo5CmYFL8f1P4ajL60MTXYju1YEtrZW78nH9wXWOSZ2PfvqDBrJhzeHuzmofUpX+VkImPlZhsXE3RqoujfFjXx7m0lnvIsqAn7OWlAAAQm0lEQVR4nNWd+1sTxxrHd5eEhc1u7nGTgBESkoCYiBistDWIWot4qVZ6Wuw5HqulrT31///1zOwte5nb7r4Lyffp00cxDPPhfed95z6SnLl61fb6cHOnuzHu7PYlServdsYb3Z3N4Xq72sv+x0tZFt5rD3fGfd0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h1tHj746Rw5rBbaZUvSvhbmepdHz2GCB0RpQFIdbRwZu3a42GSDi832isvX1zkAUdVlaElo7eHfAnjaYH77KCs5QpoaWe3Jva/yFZX8F/6KH/W/9l/vP/D/FK8XoQWqtiAAAAAElFTkSuQmCC"
alt="profile pic Nuri" />
<div>
<h2>John Doe</h2>
<h3>j.doe@test.nl</h3>
<p>Software-engineer</p>
</div>
</div>
</div>
<div class="users-list-card">
<div class="users-list-card-header">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAABSlBMVEUuWHH////7YCDxyaXktpKRXyzrwJwmWHOHXjWUXyglU23oupYeT2oLSGWYZzb7VQCMWSP2zqrh5ukERmQhUGv7UAD6z6j7WxSWXyaLWCHL09n7VwDCy9KKUg9EaH7n3dVogpOcrLd3jp319/hWa3k6YXiRo6+wvMWmtL6GmqfY3uJBZn1mW1IRV3RScYZPWmCre1D+49qjckVGWWXElW79y7x/XT3+2s/9q5KyhVvDo4tGWWSjmY6MhYD59fL87ulyXUj6ZShdW1f6vqz449H8lXTvcEHqx6x1aG3HalDZa0fyaTb8hmGob2Pu1MDhb0nBdWL9pYn9tqL4dET4h2GAXV7mo5CmYFL8f1P4ajL60MTXYju1YEtrZW78nH9wXWOSZ2PfvqDBrJhzeHuzmofUpX+VkImPlZhsXE3RqoujfFjXx7m0lnvIsqAn7OWlAAAQm0lEQVR4nNWd+1sTxxrHd5eEhc1u7nGTgBESkoCYiBistDWIWot4qVZ6Wuw5HqulrT31///1zOwte5nb7r4Lyffp00cxDPPhfed95z6SnLl61fb6cHOnuzHu7PYlServdsYb3Z3N4Xq72sv+x0tZFt5rD3fGfd0wdL2uaZo0E/pbXcf/0B/vDNuZcmZF2FsfjDFB3c9FEiJFHxsP1rPCzIKwN+z2BdjCnP3uMAtKaMJee9Cp6XHgfJh6rTMAd1lQwt56Vzdi2S5qS0PvwjosICHGS0PnUWJIuGpBEVYHGgieC6kNqkA1gyEcjo06GJ6t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2>John Doe</h2>
<h3>j.doe@test.nl</h3>
<p>Software-engineer</p>
</div>
</div>
</div>
<div class="users-list-card">
<div class="users-list-card-header">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAABSlBMVEUuWHH////7YCDxyaXktpKRXyzrwJwmWHOHXjWUXyglU23oupYeT2oLSGWYZzb7VQCMWSP2zqrh5ukERmQhUGv7UAD6z6j7WxSWXyaLWCHL09n7VwDCy9KKUg9EaH7n3dVogpOcrLd3jp319/hWa3k6YXiRo6+wvMWmtL6GmqfY3uJBZn1mW1IRV3RScYZPWmCre1D+49qjckVGWWXElW79y7x/XT3+2s/9q5KyhVvDo4tGWWSjmY6MhYD59fL87ulyXUj6ZShdW1f6vqz449H8lXTvcEHqx6x1aG3HalDZa0fyaTb8hmGob2Pu1MDhb0nBdWL9pYn9tqL4dET4h2GAXV7mo5CmYFL8f1P4ajL60MTXYju1YEtrZW78nH9wXWOSZ2PfvqDBrJhzeHuzmofUpX+VkImPlZhsXE3RqoujfFjXx7m0lnvIsqAn7OWlAAAQm0lEQVR4nNWd+1sTxxrHd5eEhc1u7nGTgBESkoCYiBistDWIWot4qVZ6Wuw5HqulrT31///1zOwte5nb7r4Lyffp00cxDPPhfed95z6SnLl61fb6cHOnuzHu7PYlServdsYb3Z3N4Xq72sv+x0tZFt5rD3fGfd0wdL2uaZo0E/pbXcf/0B/vDNuZcmZF2FsfjDFB3c9FEiJFHxsP1rPCzIKwN+z2BdjCnP3uMAtKaMJee9Cp6XHgfJh6rTMAd1lQwt56Vzdi2S5qS0PvwjosICHGS0PnUWJIuGpBEVYHGgieC6kNqkA1gyEcjo06GJ6tujEegtQNgLC3qScMLWxpur4J0CJTE1a7up4Bni1d76Z21pSE1Y1aFuabSattpGRMRVjdAIwuVEYjHWMKwszt5zGmsmNiwt7gEuznMRqDxDEnKeFQyy6+kKRrSXNHMsKbu8al8mEZuzcvj3DnEh10Js3YuSTCtnS5DjqTLrUvg7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OCQkjpzB52VAhjoFZ+oVPaIYAdWaij0koV4P3F3M6pZbipQuukyLCn/wNUdNYXbX4hHKv4x9M8ZshCqZxAKfssZNN6G+I9Q6js52IEI0XfYlxxJhy8AjjpAuBZBFoiAZ9PJic0JcYOWNDW7HSBT9ZYM1izKZ40TEI5ba7L0T9IEC4Fmf8dF+gHXoZUauLxZj4hKgx2jGVPUXj1udNjJJ5Iwu7xJ8tQl24CcYnlOWB5amjpyL1iTO6YM75eLLmowzyxC9VMQnlm/gKIH6+xzoWL3Uq4qSoxBH66cSpe4biEspyt8bvdluKEUzvCCQLBY8Ra6TVJbbiE8ptfrfbUoxgKhZKlbWf4oQYRwkIZflfDRHEGMGUM0ljy2zEnRmxlIhQvnMu8EuPMVVDX5WZqXQedwrWVjJCWX5s8oc7b4VLE+h2m3GnJ10lJZSnb0rcIaJoWdwpDLP0Ju4qgafEhKheZ5zmWBINpuwZfdQAz+JNiQSUghA1xxdMRuFhPnOAbzZeJGuAjlIRchiFh/nUBW7M90sqvtSEiPGM2h7NF4JlUMdiZuksJR8AIWqP90s0SLECKMNfs1S6n6L9uQIgRHr8luisgv02YqAxG2+T5oegYAiRs75ZixpSMNREA41ZWnuf2j0dQREiHZyFvVUw1IQCDfLOs3iTrUwBEqIGdXAWsKTgEPE4gLd2dpA4u5MESog0fff+vLHmUpr8b/D1aMy1xvn7d6B4Mjwh1tHj746Rw5rBbaZUvSvhbmepdHz2GCB0RpQFIdbRwZu3a42GSDi832isvX1zkAUdVlaElo7eHfAnjaYH77KCs5QpoaWe3Jva/yFZX8F/6KH/W/9l/vP/D/FK8XoQWqtiAAAAAElFTkSuQmCC"
alt="profile pic Nuri" />
<div>
<h2>John Doe</h2>
<h3>j.doe@test.nl</h3>
<p>Software-engineer</p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
``` |
50,025,908 | How can I convert an image to array of bytes using ImageSharp library?
Can ImageSharp library also suggest/provide RotateMode and FlipMode based on EXIF Orientation? | 2018/04/25 | [
"https://Stackoverflow.com/questions/50025908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3648560/"
] | If you are looking to convert the raw pixels into a `byte[]` you do the following.
```cs
var bytes = image.SavePixelData()
```
If you are looking to convert the encoded stream as a `byte[]` (which I suspect is what you are looking for). You do this.
```cs
using (var ms = new MemoryStream())
{
image.Save(ms, imageFormat);
return ms.ToArray();
}
``` | For those who look after 2020:
SixLabors seems to like change in naming and adding abstraction layers, so...
Now to get a raw byte data you do the following steps.
1. Get `MemoryGroup` of an image using `GetPixelMemoryGroup()` method.
2. Converting it into array (because `GetPixelMemoryGroup()` returns a interface) and taking first element (if somebody tells me why they did that, i'll appreciate).
3. From `System.Memory<TPixel>` get a `Span` and then do stuff in old way.
(i prefer solution from @Majid comment)
So the code looks something line this:
```cs
var _IMemoryGroup = image.GetPixelMemoryGroup();
var _MemoryGroup = _IMemoryGroup.ToArray()[0];
var PixelData = MemoryMarshal.AsBytes(_MemoryGroup.Span).ToArray();
```
*ofc you don't have to split this into variables and you can do this in one line of code. I did it just for clarification purposes. This solution only viable as for 06 Sep 2020* |
11,812,142 | OK, I want to get all the data from the first column of a JTable. I though the best way would be pulling it in to a `ArrayList`, so I made one. I also made an instance of a `TableModel`:
```
static DefaultTableModel model = new javax.swing.table.DefaultTableModel();
f.data.setModel(model); //f.data is the JTable
public static final void CalculateTotal(){
ArrayList<String> numdata = new ArrayList<String>();
for(int count = 1; count <= model.getRowCount(); count++){
numdata.add(model.getValueAt(count, 1).toString());
}
System.out.println(numdata);
}
```
This gives me a NullPointerException (cue screams). What am i doing wrong? | 2012/08/04 | [
"https://Stackoverflow.com/questions/11812142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1332495/"
] | It is best if you could post [SSCCE](http://sscce.org/) that shows model initialization and its population with data. Also include details of the exception as there could be multiple sources for the problem.
Here is a demo based on @CedricReichenbach correction:
```
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;
public class TestModel {
public static void main(String s[]) {
DefaultTableModel model = new javax.swing.table.DefaultTableModel();
model.addColumn("Col1");
model.addColumn("Col2");
model.addRow(new Object[]{"1", "v2"});
model.addRow(new Object[]{"2", "v2"});
List<String> numdata = new ArrayList<String>();
for (int count = 0; count < model.getRowCount(); count++){
numdata.add(model.getValueAt(count, 0).toString());
}
System.out.println(numdata);
}
}
```
The result is:
```
[1, 2]
``` | I know this answer is a bit late, but it is actually a very easy problem to solve. Your code gives an error when reading the entry because there is no entry in the table itself for the code to read. Populate the table and run your code again. The problem could have been solved earlier but from the code you posted it was not obvious what was inside your table. |
67,052 | I would like to design a dungeon-like location, a city surrounding a keep built on a limestone hill littered with caves. Tunnels and caverns would connect certain city locations to keep dungeons but also to some natural formations, which are used as building parts, free storage space, or in some deeper cases unused, abandoned or unexplored.
The whole structure has at least five levels, but unlike in premeditated multi-storey design, natural and organic cave formation does not follow a set of distinct, parallel "floors". And most importantly, I have to explain that network to players.
I'm looking for a good methodology of wholesome design and representation of a three-dimensional dungeon. It has to be representable on paper as a map (innovation welcome - folding paper structures?). It has to include non-sequential "levels" (e.g. ramps going through a level without accessing it or "half levels"). Is there any such methodology available to players, short of making a 3D model with Blender or something similar?
---
The map is supposed to help players realise which bits of the city are connected and what is required to travel underground. E.g. in Game of Thrones, you could travel by horse underground from the Red Keep dungeons to city docks. I want that fact to be immediately recognisable. | 2015/08/13 | [
"https://rpg.stackexchange.com/questions/67052",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/14670/"
] | Forget about floors and levels, and think in sections.
------------------------------------------------------
Split the map into manageable sections. Each section could be a large room with several entries, a corridor with some rooms and two exits, etc. Give each section a name and each exit/entrance a number. While the players explore the complex, you just handle them the relevant map section, and make handwritten notes on which section/door connects to which section/door as the player discovers them. Or let the player make those notes themselves.
Additionally, in our group the DM usually keeps for himself a very simple flowchart detailing the sections and the connections between them, both for reference and as a place for writing quick notes about specific sections and rooms for whatever thing you see fit.
You really should not concern yourself with making perfectly realistic simulation of an underground complex, and your players probably do not need it neither. | What you're describing -- a sprawling, unorganized network with no set floor structure -- doesn't really require a detailed representation of three dimensional spatial positioning, or at least not throughout the entirety of it. Think about it like this -- if you're travelling through a subway station to a different exit, is it really necessary for you to think about how the subway is underneath specific buildings in the city for you to get where you're going? The answer is (for most) no, you just follow a path through a stairwell or two and understand your heading that way, as a set path. Really, you just need to tell your players that "there's a tunnel connecting Building A to Building B underground, but Ruins C lies in the middle."
I personally prepare by deciding how much detail I need on a room-by-room basis. I would imagine that not every room in your dungeon is going to feature zero-G combat or something equally exotic -- surely there's going to be rooms in-between those scenes. Most of the time, combat is the only part of the game where exact spatial awareness becomes important. When you create a room (and by "room" I mean any meaningful space that the players travel through, separated by portals of some kind) you should decide at the time of its creation whether the players will be involved in any activity that would require awareness of all three dimensions. There's always going to be exceptions and emergent events that happen during play where the bard decides to swing on the chandelier or something, but you can deal with those and come up with distances and dimensions when it happens. |
61,218,789 | Get averages from a python dictionary for example if i have the next dictionary:
```
students={'Dan':(5,8,8), 'Tim':(7), 'Richard':(9,9)}
```
And i would like to print de dictionary in the next form:
```
results={'Dan':(7), 'Tim':(7), 'Richard':(9)}
```
is there any function that i can use? Im new coding in python so dictionaries are a bit confusing for me. | 2020/04/14 | [
"https://Stackoverflow.com/questions/61218789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11048727/"
] | I'd do:
```
result = {}
for k, v in students.items():
if type(v) in [float, int]:
result[k] = v
else:
result[k] = sum(v) / len(v)
``` | A pythonic solution would be to use dictionary comprehension to create the results dictionary.
```
def avg(l):
return sum([l]) / len(l)
results = {key: (avg(val)) for (key, val) in students.items()}
```
You need brackets around the l in sum so the tuple is treated as a list. I would further change the data structure to a list instead of tuple. |
36,716,818 | What is the *idiomatic* way to do the following string concatenation in R?
Given two vectors of strings, such as the following,
```
titles <- c("A", "B")
sub.titles <- c("x", "y", "z")
```
I want to produce the vector
```
full.titles <- c("A_x", "A_y", "A_z", "B_x", "B_y", "B_z")
```
Obviously, this could be done with two for-loops. However, I would like to know what an “idiomatic” (i.e., elegant and natural) solution would be in R.
In Python, an idiomatic solution might look like this:
```
titles = ['A', 'B']
subtitles = ['x', 'y', 'z']
full_titles = ['_'.join([title, subtitle])
for title in titles for subtitle in subtitles]
```
Does R allow for a similar degree of expressiveness?
**Remark**
The consensus among the solutions proposed thus far is that the idiomatic way to do this in R is, basically,
```
full.titles <- c(t(outer(titles, sub.titles, paste, sep = "_")))
```
Interestingly, this has an (almost) literal translation in Python:
```
full_titles = map('_'.join, product(titles, subtitles))
```
where `product` is the cartesian-product function from the itertools module. However, in Python, such a use of `map` is considered more convoluted—that is, *less* expressive—than the equivalent use of list comprehension, as above. | 2016/04/19 | [
"https://Stackoverflow.com/questions/36716818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5768077/"
] | ```
apply(expand.grid(titles, sub.titles), 1, paste, collapse = "_")
```
`expand.grid` creates a matrix of combinations between `titles` and `sub.titles`.
`apply` goes down the matrix of combinations and pastes them together. | ```
full.titles <- paste0(expand.grid(titles,sub.titles)$Var1,'_',
expand.grid(titles,sub.titles)$Var2)
>full.titles
[1] "A_x" "B_x" "A_y" "B_y" "A_z" "B_z"
``` |
12,603,837 | So I made a game loop that uses `SDL_Delay` function to cap the `frames per second`, it look like this:
```
//While the user hasn't qui
while( stateID != STATE_EXIT )
{
//Start the frame timer
fps.start();
//Do state event handling
currentState->handle_events();
//Do state logic
currentState->logic();
//Change state if needed
change_state();
//Do state rendering
currentState->render();
//Update the screen
if( SDL_Flip( screen ) == -1 )
{
return 1;
}
//Cap the frame rate
if( fps.get_ticks() < 1000 / FRAMES_PER_SECOND )
{
SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - fps.get_ticks() );
}
}
```
So when I run my games on `60 frames per second` (which is the "eye cap" I assume) I can still see laggy type of motion, meaning i see the frames appearing independently causing unsmooth motion.
This is because apparently `SDL_Delay` function is not too accurate, causing `+,- 15 milliseconds` or something difference between frames greater than whatever I want it to be.
(all these are just my assumptions)
so I am just searching fo a good and accurate timer that will help me with this problem.
any suggestions? | 2012/09/26 | [
"https://Stackoverflow.com/questions/12603837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1680034/"
] | Use the QueryPerformanceCounter / Frequency for that.
```
LARGE_INTEGER start, end, tps; //tps = ticks per second
QueryPerformanceFrequency( &tps );
QueryPerformanceCounter( &start );
QueryPerformanceCounter( &end );
int usPassed = (end.QuadPart - start.QuadPart) * 1000000 / tps.QuadPart;
``` | 60 fame per second is just the frequency of power in US (50 in Europe, Africa and Asia are somehow mixed) and is the frequency of video refreshing for hardware comfortable reasons (It can be an integer multiple on more sophisticated monitors). It was a mandatory constrains for CRT dispaly, and it is still a comfortable reference for LCD (that's how frequently the frame buffer is uploaded to the display)
The eye-cap is no more than 20-25 fps - not to be confused with retina persistency, that's about one-half - and that's why TV interlace two squares upon every refresh.
independently on the timing accuracy, whatever hardware device cannot be updated during its buffer-scan (otherwise the image changes while it is shown, resulting in half-drawn broken frames), hence, if you go faster than one half of the device refresh you are queued behind it and forced to wait for it.
60 fps in a game loop serves only to help CPU manufacturers to sell new faster CPUs. Slow down under 25 and everything will look more fluid. |
1,491,566 | In my solution [here](https://math.stackexchange.com/a/1484125/168053), it was shown that
$$\omega+\omega^2+\omega^4=-\frac 12\pm\frac{\sqrt7}2\qquad\qquad (\omega=e^{i2\pi/7})$$
from which we know that
$$\sin \frac{2\pi}7+\sin \frac{4\pi}7-\sin \frac{6\pi}7=\Im (\omega+\omega^2+\omega^4)=\frac{\sqrt7}2$$
This can also be verified easily by computation.
By the same token it would appear that
$$\cos \frac{2\pi}7+\cos \frac{4\pi}7-\cos \frac{6\pi}7=\Re (\omega+\omega^2+\omega^4)=\frac 12$$
However a quick computational check shows that the result is $1.3019...$ and not $\frac 12$.
Why is this so? | 2015/10/21 | [
"https://math.stackexchange.com/questions/1491566",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/168053/"
] | In that answer there is the following equality
$$\begin{align}
\sin\frac{2\pi}7+\sin\frac{4\pi}7-\sin\frac{6\pi}7
&=\Im(\omega^1+\omega^2-\omega^3)\\
&=\Im(\omega^1+\omega^2+\omega^4)\\
&=\Im(S)\\
&=\dfrac{\sqrt{7}}{2}\\
\end{align}.$$
For the real part you have
$$\begin{align}
-\dfrac{1}{2}&=
\Re(S)\\
&=\Re(\omega^1+\omega^2+\omega^4)\\
&=\Re(\omega^1+\omega^2+\omega^3)\\
&=\cos\frac{2\pi}7+\cos\frac{4\pi}7+\cos\frac{6\pi}7
\end{align}$$ | You're starting from the wrong assumption that $-\omega^3=\omega^4$, which is obviously wrong, because it would imply $\omega=-1$.
The true fact is that
$$
-\sin\frac{6\pi}{7}=\sin\frac{8\pi}{7}
$$
but
$$
\cos\frac{6\pi}{7}=\cos\frac{8\pi}{7}
$$
because
$$
\frac{6\pi}{7}+\frac{8\pi}{7}=2\pi
$$
and
$$
\sin(2\pi-\alpha)=-\sin\alpha,\qquad
\cos(2\pi-\alpha)=\cos\alpha
$$ |
390,131 | >
> What are some examples of naturally occurring badly behaved (possibly higher) categories?
>
>
>
When working with a specific category like ${\bf Set}$ or ${\bf Cat}$, we usually understand/explain them by lauding structural properties they posess -- ${\bf Set}$ is an autological topos, ${\bf Cat}$ is Cartesian closed, etc.
What structures can be arranged naturally/canonically into (possibly higher) categories, despite the resulting categories having few/none of the structural properties we would usually like to have in order to carry out category-theoretic-type proofs?
A natural example is ${\bf Field}$, the category of fields and field homomorphisms, since it has no terminal object, no initial object, no finite products, is not algebraic and is not presentable. (It is, however, accessible with a multi-initial object given by the set of prime fields).
I suspect that it gets worse than this, but I can't think of anything further off the top of my head. Any examples are appreciated. | 2021/04/14 | [
"https://mathoverflow.net/questions/390131",
"https://mathoverflow.net",
"https://mathoverflow.net/users/92164/"
] | The category $Rel$ of sets and relations between them [fails to have finite (co)limits](https://math.stackexchange.com/questions/354779/the-category-set-seems-more-prominent-important-than-the-category-rel-why-is-th/870483#870483).
So does the $(2,1)$-category $Span$ of sets and spans between them (the pushout of the forward map $2 \to 1$ against itself fails to exist).
These are examples illustrating the point that *self-dual* categories often fail to have nice categorical properties (Hilbert Spaces, as mentioned by Andre, would be another). | The category $\mathbf{Met}$ of metric spaces and [metric maps](https://en.wikipedia.org/wiki/Metric_map) is another example. There are finite limits, but no infinite products. Countable products exist at least when we use continuous maps as the morphisms instead. $\mathbf{Met}$ has no binary coproducts, and this can be seen as the starting point of the [Gromov-Hausdorff distance](https://en.wikipedia.org/wiki/Gromov%E2%80%93Hausdorff_convergence), where we consider all possible metrics on a disjoint union. Coequalizers do not exist either. It is worth pointing out that the [injective objects of $\mathbf{Met}$](https://en.wikipedia.org/wiki/Injective_metric_space) have gathered some interest. |
3,458,023 | I'm trying to write a GUI program grabbing specific contents from a webpage. The idea is when I hit the start button, the program should start extracting information from that page. And I want to add some code to check if connected to the Internet. If not, continue trying until connected.
So I just added the following code in the event, but found it didn't work. Also the whole program has to be closed in a forced way. Here's my code:
```
import urllib2
import time
InternetNotOn = True
while InternetNotOn:
try:
urllib2.urlopen("http://google.com")
InternetNotOn = False
print "Everyting is fine!"
except urllib2.URLError, e:
print "Error!"
time.sleep(10)
```
What could the problem be? | 2010/08/11 | [
"https://Stackoverflow.com/questions/3458023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402197/"
] | When you have an event based program, the overall flow of the program is this:
```
while the-program-is-running:
wait-for-an-event
service-the-event
exit
```
Now, lets see what happens when service-the-event calls something with a (potentially) infinite loop:
```
while the-program-is-running:
wait-for-an-event
while the-internet-is-on:
do-something
exit
```
Do you see the problem? In the worse case your program may never call wait-for-an-event again because your loop is running.
Remember: the event loop is already an infinite loop, you don't need to add another infinite loop inside of it. Instead, take advantage of the existing loop. You can use [wx.CallAfter](http://www.wxpython.org/docs/api/wx-module.html#CallAfter) or [wx.CallLater](http://www.wxpython.org/docs/api/wx.CallLater-class.html) to call a method which will cause your function to be called at the next iteration of the event loop.
Then, within your function you call [wx.CallAfter](http://www.wxpython.org/docs/api/wx-module.html#CallAfter) or [wx.CallLater](http://www.wxpython.org/docs/api/wx.CallLater-class.html) again to cause it to again be called on the next iteration of the event loop. | Instead of `time.sleep(10)` you can call [wxApp::Yield](http://docs.wxwidgets.org/stable/wx_wxapp.html#wxappyield) and `time.sleep(1)` ten times.
Beware of reentrancy problems (e.g. pressing the start button again.). The start button could be dimmed while in the event handler.
But [Bryan Oakley's solution](https://stackoverflow.com/questions/3458023/when-while-loop-placed-in-wxpython-events/3458633#3458633) is probably the better way. |
91,320 | What other ways are there to save a human for a very long time. I know only about cryostasis. Let's say we have a spaceship traveling several hundred light years to a distant galaxy. | 2017/09/08 | [
"https://worldbuilding.stackexchange.com/questions/91320",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/32349/"
] | If you really want to go to a *distant* galaxy you should first realize the *nearest* (Andromeda) is about 2.5 *million* light years.
If You really want to travel that far (and get there before your ship falls apart) I think the best is "just" to exploit Lorentz time contraction.
Have your spaceship to travel very near to light speed (say 0.99c) so that the crew would travel ~7.3 light-years in a single (subjective) year.
Going even closer to light speed effect would be more relevant (at 0.999c in a single year spaceship would travel more than 22.6 light-years).
At that speed you really need to start paying attention to the road ahead, so having an active crew (not in hibernation) may be actually useful. | Cryostatis Pro: we (of september 14 of 2017) are doing this every single day, at least in first world countries. So the techonolgy already exists.
Con: the frozen water expands bursting cells open thus killing the thing you want to perserve.
May i introduce you to the Medical Nanobots. **tiny little robots,** nanobots (in fiction at least) serve many different roles. This specific role is to make sure the chemical-horomal balance of humans in statis allows them to "Crash Wake" (aka OMG THE SHIP IS FALLING APART BECAUSE REASONS! WAKE UP NOOOWWW!) in emergences.
The nanobots will of course make sure your passengers get enough stuff to survive the journey and may double as DNA Repair Systems for radiation treatment. (Example: <https://m.youtube.com/watch?v=7401A3k7OYc>)
Sure the end product may not be Genetically human. But it got them there didn't it? Also this allows for a sub plot on what it means to be human. |
18,372,027 | I have two stored procedures which gives Daily swipe data and another gives Temporary Swipe details.
I got an requirement to populate gridview, Based on the date the temporary card details must get displayed in between Daily swipe data.
Please anyone give me idea how to populate two result sets into gridview
Iam using Sql server 2008 R2 and Visualstudio 2010 | 2013/08/22 | [
"https://Stackoverflow.com/questions/18372027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2595238/"
] | Lets assume we consume this ResultSet which has two DataTables "Agent" and "RealEstateProperty". The task is to display, what properties belongs to which agent, in a GridView.

There are different ways to accomplish this task-
**Method 1: Bind DataTables to a single GridView**
To bind these multiple DataTables to a single GridView control, we can quickly create a new temporary DataTable, with the required fields and populate the Rows and then bind the new DataTable Rows to the GridView.

The above code is self explanatory, where I have created a temporary DataTable, populated its rows by iterating through the original DataTables and then binded the Grid to the new DataTable.Rows. The interesting piece of code to note here is the row.GetChildRows(), which respects the relationship and automatically returns the related child rows. The aspx part looks like the following, where we have a GridView with three columns.

and the RowDataBound code is

**Method 2: Bind DataTables to a nested GridView**
If we want to avoid creating temporary dummy DataTable as described in method 1, we can use the technique of nested list control. Now we can do this by using
two GridView, or
two DataList, or
two Repeaters or
a combination of Repeater and GridView, or
a combination of Repeater and DataList, or
a combination of GridView and DataList.
We are going to look at a combination of 2 GridViews here, where one GridView is nested inside another, you can do any of the above combinations. For this case the the aspx code is-

Notice the parent and nested GridViews has different onrowdatabound methods. In this technique the parent grid is binded to the the Agent DataTable Rows and the nested GridView is binded to the child RealEstateProperty DataTable Rows. Here is the code.

**Method 3: Convert the DataSet to Objects and then bind to GridView**
We can generate csharp class from the dataset schema using Xsd.exe and then bind the GridViews to the objects. I have discussed similar technique in one of my previous blog post, where you will find how we can use the Xsd.exe that ships with the .NET Framework.
Example
C:\temp>xsd propertyDataSet.xsd /l:cs /c
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\temp\propertydatasetclass.cs'.
I also demonstrated a handy DataTableToT() method to assist in converting DataTable to strongly typed object. And when we have the DataTable converted to a stronglytyped object/list/collection it is very easy to bind to the bind to the GridView. | ```
1.Call your Second stored procedure within first stored procedure.
2.Pass your outcome to dataset.
3.From dataset u can fetch it using ds.table[0],ds.table[1],etc..
``` |
36,933,755 | * A Activity is SingleTask
* B Activity and C Activity is Standard,
A -> B -> C, Then press Home, re-press the application icon, Why B,C destroy? Why B destroyed firstly, C destroyed later?
```
<activity
android:name=".Main1Activity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.dell.taskdemo.Main2Activity" />
<activity android:name="com.example.dell.taskdemo.Main3Activity" />
```
```
public class Main1Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("---1: onCreate " + getTaskId());
}
public void enter(View view) {
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
}
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
System.out.println("---2: onCreate " + getTaskId());
}
public void enter(View view) {
startActivity(new Intent(this, Main3Activity.class));
}
}
public class Main3Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
System.out.println("---3: onCreate " + getTaskId());
}
}
``` | 2016/04/29 | [
"https://Stackoverflow.com/questions/36933755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6270615/"
] | in short "singleTask" activity allows other activities to be a part of its task...so when ever you re-open the app again, the Activity a is shown because as of now activity b,c are part of its task...
the activity b is deleted first because, it started before the Activity c. | Check your manifest file and ensure that Activity B and C are not set to "noHistory=true." If they are, remove that line and it should fix your issue.
Activity B and C should not be destroyed simply because Activity A is SingleTask. Having a SingleTask activity simply means it has to be at the bottom of the activity stack - so it exists once and only once. If B and C are finishing each time you close the app, it's because B and C are not set properly. So the issue is with B and C, not with A. |
4,054,254 | I have written a program which sends more than 15 queries to Google in each iteration, total iterations is about 50. For testing I have to run this program several times. However, by doing that, after several times, Google blocks me. is there any ways so I can fool google maybe by adding delays between each iteration? Also I have heard that google can actually learn the timesteps. so I need these delays to be random so google cannot find a patter from it to learn my behavior. also it should be short so the whole process doesn't take so much.
Does anyone knows something, or can provide me a piece of code in python?
Thanks | 2010/10/29 | [
"https://Stackoverflow.com/questions/4054254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/313245/"
] | Best to use:
```
from numpy import random
from time import sleep
sleeptime = random.uniform(2, 4)
print("sleeping for:", sleeptime, "seconds")
sleep(sleeptime)
print("sleeping is over")
```
as a start and slowly decreasy range to see what works best (fastest). | Also you can try to use few proxy servers for prevent ban by IP adress. urllib support proxies by special constructor parameter, httplib can use proxy too |
20,778,991 | I am having a `table view` with custom cells. Each custom cell is having `scroll view` in which images are added in series. Images are of quite large size. Other than images, some other datas are also present in each cell. I am saving the images to `db` before reloading table view.The issue is as the tableview `reloaddata` is calling continuously and my scroll view inside the cell is not working properly. What is the efficient method for reloading table view without affecting the scroll inside.Images should also load in a proper manner.
this is how i m calling those methods:
```
-(void)viewWillAppear:(BOOL)animated{
[self performSelectorInBackground:@selector(getPacksdetails) withObject:nil];}
-(void) getPacksdetails
{
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
ForcePackRequest *request = [[ForcePackRequest alloc] init];
User *userObj = (User *)[request getActiveUser];
NSString *emailString =[NSString stringWithFormat:@"%@", userObj.Email ];
BOOL isPackList= [request getPurchasedPacksOfUser:emailString toArray:packsListArray excerciseArray:excercisesArray recommendedGearsArray:recommendedGears];
// NSMutableArray *namesArray=[[NSMutableArray alloc]init];
for(int packscounter=0;packscounter<[packsListArray count];packscounter++){
if([[[packsListArray objectAtIndex:packscounter]objectForKey:@"name"] isEqualToString: passedPackName]){
//nslog(@"passedPackName%@",passedPackName);
////nslog(@"%@",data.exName);
reservedIndexPath=nil;
reservedIndexPath= [NSIndexPath indexPathForRow:0 inSection:packscounter];
//nslog(@"%@",reservedIndexPath);;
break;
}
// reservedIndexPath=[NSIndexPath indexPathWithIndex:i];
}
if(isPackList)
[self performSelectorInBackground:@selector(loadExerthumbThread:) withObject:nil];
}
- (void) loadExerthumbThread:(id)sender{
//if (FP_DEBUG) //nslog(@"%@",excercisesArray);
for(int i=0;i<[excercisesArray count];i++){
NSMutableArray *exforAsection=[[NSMutableArray alloc]init];
// exerciseArrayForeachSection=[excercisesArray objectAtIndex:i];
exforAsection=[excercisesArray objectAtIndex:i];
for (int intConter = 0; intConter <[exforAsection count]; intConter++)
{
Exercise *data = [exforAsection objectAtIndex:intConter];
// NSString *imageName = [[data.exImage ] intValue];
int intExerId = [data.exImage intValue];
NSString *imagestr = [NSString stringWithFormat:@"hires_%d",intExerId];
FileManager *objFileManager = [[FileManager alloc] init];
NSData *imageData = nil;
if ([objFileManager isFileExistsInDocDir:imagestr])
{
imageData = [objFileManager getFileFormDocDirWithName:imagestr];
}
else
{
NSString *imageUrlString = [NSString stringWithFormat:@"http://www.forcetherex.com/force_uploads/exercise/exercise_hires/%@.png",data.exId];
NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageUrlString]];
if (data != nil)
{
if ([data length] > 100)
imageData = [data copy];
}
if (imageData != nil){
[objFileManager writeFileToAppDirectoryWithFileName:imagestr andFileData:imageData];
//Mark as dont back up
NSURL *fileUrl = [NSURL fileURLWithPath:imagestr];
[self addSkipBackupAttributeToItemAtURL:fileUrl];
fileUrl=nil;
data = nil;
}
}
if (imageData != nil)
data.exThumbImage = imageData;
objFileManager = nil;
}
[self reloadTableView];
}
```
and my cellforrow atindexpath code is:
```
{
NSString *CellIdentifier = [NSString stringWithFormat:@"%d_%d",indexPath.section,indexPath.row];
//static NSString *CellIdentifier = @"CustomCellFor_Dashboard";
_customCell = (CustomCellFor_Dashboard *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (_customCell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCellFor_Dashboard" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
_customCell = (CustomCellFor_Dashboard *) currentObject;
_customCell.delegate=self;
break;
}
}
}
_customCell.exNameDictArray=[[packsListArray objectAtIndex:indexPath.section]objectForKey:@"exerciseList"];
_customCell.indexPath=indexPath;
NSLog(@"%d",sng.showingPath.section);
if(indexPath.section ==sng.showingPath.section)
_customCell.exnameTable.hidden=FALSE;
sectionInt=indexPath.section;
exerciseArrayForeachSection=[[NSMutableArray alloc]init];
//[exerciseArrayForeachSection removeAllObjects];
exerciseArrayForeachSection=[excercisesArray objectAtIndex:indexPath.section];
//next btn
UIButton *accessoryView = [[UIButton alloc] initWithFrame: _customCell.nextBtn.frame];
accessoryView.tag = indexPath.section;
[accessoryView setImage:[imageasArr objectAtIndex:0]forState:UIControlStateNormal];
[accessoryView addTarget:self action:@selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[_customCell addSubview:accessoryView];
//_customCell.accessoryView = accessoryView;
//prev btn
UIButton *prevBtn = [[UIButton alloc] initWithFrame: _customCell.prevBtn.frame];
prevBtn.tag = indexPath.section;
[prevBtn setImage:[imageasArr objectAtIndex:2]forState:UIControlStateNormal];
[prevBtn addTarget:self action:@selector(previousButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[_customCell addSubview:prevBtn];
_customCell.selectionStyle = UITableViewCellSelectionStyleNone;
[_customCell addSubview:_customCell.buttonView];
_customCell.nameLabel.text=[[packsListArray objectAtIndex:indexPath.section]objectForKey:@"name"];
_customCell.exCountLbl.text=[NSString stringWithFormat:@"%@", [[packsListArray objectAtIndex:indexPath.section]objectForKey:@"exercises"]];
_customCell.scroll.delegate = self;
// [_customCell.scroll setBackgroundColor:[UIColor blackColor]];
[_customCell.scroll setCanCancelContentTouches:NO];
_customCell.scroll.indicatorStyle = UIScrollViewIndicatorStyleWhite;
_customCell.scroll.clipsToBounds = YES;
[_customCell.scroll setContentOffset:CGPointMake(0, 20)];
if([exerciseArrayForeachSection count]>0){
_customCell. scroll.frame = CGRectMake(0,40, 320, _customCell.scroll.frame.size.height-10);
_customCell. scroll.contentSize = CGSizeMake(320*[exerciseArrayForeachSection count],_customCell .scroll.frame.size.height);
int cx = 30;
for(int i=0;i<[exerciseArrayForeachSection count];i++){
Exercise *data = [exerciseArrayForeachSection objectAtIndex:i];
UIView *detailView=[[UIView alloc]initWithFrame:_customCell.excerciseDetailsView.frame];
UILabel *titleLbl=[[UILabel alloc]initWithFrame:_customCell.exTitleLabel.frame];
titleLbl.font=[UIFont systemFontOfSize:12];
UIImageView *exerciseImg=[[UIImageView alloc]initWithFrame: _customCell.exThumbImageView.frame];
UIButton *playBtn=[[UIButton alloc]initWithFrame:_customCell.exThumbButton.frame];
playBtn.showsTouchWhenHighlighted=YES;
[playBtn setImage:[imageasArr objectAtIndex:1]forState:UIControlStateNormal];
// playBtn.frame =_customCell.exThumbButton.frame;
playBtn.tag=i;
[playBtn addTarget:self action:@selector(videoPlayActn:) forControlEvents:UIControlEventTouchUpInside];
[titleLbl setText:data.exName];
if ([data.exThumbImage length] > 0)
[exerciseImg setImage:[UIImage imageWithData:data.exThumbImage]];
[detailView addSubview:titleLbl];
[exerciseImg addSubview: playBtn];
[detailView addSubview:exerciseImg];
// _customCell.exThumbButton= playBtn;
[exerciseImg bringSubviewToFront:playBtn];
exerciseImg.userInteractionEnabled=TRUE;
[detailView bringSubviewToFront:playBtn];
//if (FP_DEBUG) //nslog(@"%f",_customCell.scroll.frame.origin.x);
detailView.frame=CGRectMake(cx, 30, 320, _customCell.scroll.contentSize.height);
//_customCell.exThumbImageView=exerciseImg;
[_customCell.scroll addSubview:detailView];
detailView=nil;
exerciseImg=nil;
titleLbl=nil;
_customCell.scroll.contentSize = CGSizeMake( cx,_customCell.scroll.contentSize.height);
cx = cx+_customCell.scroll.frame.size.width;
//if (FP_DEBUG) //nslog(@"%i",cx);
}
}
// [_customCell.scroll setContentOffset:CGPointMake(0, 20)];
//if (FP_DEBUG) //nslog(@"%f",_customCell.scroll.contentOffset.x);
[_customCell.howyoulfeelBtn addTarget:self action:@selector(buttonclicked:) forControlEvents:UIControlEventTouchUpInside];
[_customCell.expertAdviceBtn addTarget:self action:@selector(expertbuttonclicked:) forControlEvents:UIControlEventTouchUpInside];
[_customCell.recoverTrackerBtn addTarget:self action:@selector(recoverytrackerBtnclicked:) forControlEvents:UIControlEventTouchUpInside];
[_customCell.recommendedGearsBtn addTarget:self action:@selector(recommendedGearsBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
////nslog(@"ewfewr************ewr");
if(indexPath.section== expandViewclickedSection&&_isexpanded==TRUE){
_customCell.scroll.frame = CGRectMake(-160, 22, self.view.frame.size.width, self.view.frame.size.height);
_customCell.shareView.hidden=FALSE;
// _customCell.nextBtn.hidden=TRUE;
accessoryView.hidden=TRUE;
//_isexpanded=TRUE;
}
else if(indexPath.section== expandViewCollapsedSection&&_isexpanded==FALSE) {
_customCell.scroll.frame = CGRectMake(-0, 22, self.view.frame.size.width, self.view.frame.size.height);
_customCell.shareView.hidden=TRUE;
// _isexpanded=FALSE;
}
if(_isExListingTablePresented==TRUE&&indexPath.section==exlistTableAddedSection){
_customCell.exListingTable.hidden=FALSE;
}
else if(_isExListingTablePresented==FALSE&&indexPath.section==_exlistTableremovedSection){
_customCell.exListingTable.hidden=TRUE;
}
return _customCell;
}
``` | 2013/12/26 | [
"https://Stackoverflow.com/questions/20778991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1093483/"
] | How about using [`re.split`](http://docs.python.org/2/library/re.html#re.split)?
```
'London, ENG, United Kingdom or Melbourne, VIC, Australia or Palo Alto, CA USA'
>>> list(map(str.strip, re.split(',|or', x)))
['London', 'ENG', 'United Kingdom', 'Melbourne', 'VIC', 'Australia', 'Palo Alto', 'CA USA']
>>> list(map(str.strip, re.split('or', x)))
['London, ENG, United Kingdom', 'Melbourne, VIC, Australia', 'Palo Alto, CA USA']
```
---
If you want location to be splitted with `or`, you don't need to use regular expression. Just use `str.split`:
```
>>> list(map(str.strip, x.split('or')))
['London, ENG, United Kingdom', 'Melbourne, VIC, Australia', 'Palo Alto, CA USA']
```
* `list` is not needed if you use Python 2.x.
---
**UPDATE**
```
>>> x = 'London, ENG, United Kingdom / Melbourne, VIC, Australia / Palo Alto, CA USA'
>>> re.findall(r'(?:\w+(?:\s+\w+)*,\s)+(?:\w+(?:\s\w+)*)', x)
['London, ENG, United Kingdom', 'Melbourne, VIC, Australia', 'Palo Alto, CA USA']
``` | Okay, i found my answer myself, its fairly simple:
```
r'\w+, \w+, \w+'
```
But to respect @falsetru's efforts i'll accept his answer.. Thankyou @falsetru |
36,686,392 | I have a game that when I land on a place, which is a coordinate,it checks it and replaces that coordinate with an object sort out thing. I'm struggling to do it please can any of you help me.
Please can any of you help me.THANKS :) t | 2016/04/18 | [
"https://Stackoverflow.com/questions/36686392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6187907/"
] | To solve this issue:
I searched for libmysqlclient.so.20 (the version number at the end may differ)
```
find /. -name "libmysqlclient.so.20"
```
My ouput was
```
/./usr/lib/x86_64-linux-gnu/libmysqlclient.so.20
```
I then copied that file into the root directory of my package
```
cp /usr/lib/x86_64-linux-gnu/libmysqlclient.so.20 <your package path>
``` | How did you install MySQLdb? <http://mysql-python.sourceforge.net/FAQ.html> says:
>
> ImportError: No module named \_mysql
> If you see this, it's likely you did some wrong when installing MySQLdb; re-read (or read) README. \_mysql is the low-level C module that interfaces with the MySQL client library.
>
>
>
Install MySQLdb with pip if you didn't already. |
2,971 | When going to Latvia, I like to eat some small snacks in the bakeries called [Martina Bekereja](http://www.bekereja.lv/). I think there are several of them in Latvia, or even in the whole Baltic. Because I really like them, I would like to have a map with all of them. I tried to find them on the homepage, but unfortunately I don't understand Latvian, so I'm not sure if this information is available on there homepage.
Is there any other way to find all these bakeries? | 2011/10/23 | [
"https://travel.stackexchange.com/questions/2971",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/693/"
] | I tried translating the site with Bing Translate, but because it's Flash it won't translate. However I did the menu words one at a time, and Vietas means Site - locations, I think. That page just has a number of words with a number after each. If you click on a word, you get a phone number and what are obviously opening hours.
The next step would be to determine whether those words are streetnames within a single city (my guess, with the number then being a street number since one is 76a), or city names. Recognize any? | I don't speak Latvian, but my girlfriend is Latvian. I'll make her an account later, but for now, here's what she says:
If you go to the "Vietas" tab it gives you a list of street names and numbers of their sites. All the sites are located in Rīga. So, for example, Marijas 19 means : Marijas Street 19, Rīga. Copy-paste the addresses in google maps and you're done.
p.s. their stuff is awesome! |
114,231 | Ever since I updated to iOS 7 in June, I have been having issues using the camera on my phone in apps other than the default Camera app. Regardless of settings, using my camera in any non-Apple app (such as Instagram or Tumblr) will result in that particular app crashing immediately. I have tried everything to remedy the issue short of a full restore on my phone. I'm convinced it's some sort of low memory or high CPU utilization issue, since iOS 7 seems to be much more taxing on my phone's resources than iOS 6 was. Is there some way to fix this issue without simply buying a newer, faster iPhone? | 2013/12/17 | [
"https://apple.stackexchange.com/questions/114231",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/27349/"
] | * With the system I've updated, will the buyer be asked for his apple ID and will that replace mine?
When they first use the system and create a User ID etc, they will be asked for an Apple ID (which is not entirely mandatory) and it will have no knowledge of you as the previous owner, nor will it care what ID is used.
* If that's not the case, will he be able to do updates without having the password to my account?
Updates will be possible without having any knowledge of the ID that originally purchased it
* Can I change the Apple ID that owns mavericks to him, even if I have to gift him Mavericks?
No, purchases via the Mac App Store are tied to your ID, and cannot be transferred. Also, you cannot gift a free app.
* Is there a better way to do all this?
Not really, you should just advise the purchaser to "buy" (It's free, so no cost) a copy of Mavericks against his own ID, such that it can be used for restores etc in future and to ensure that he owns a copy legitimately. He should be able to purchase it on a machine that is already running it, simply by logging into the App store with an ID that has not already purchased it. It may kick off a pointless download which can be cancelled, but it will get him square from a licensing terms perspective, and from a safety/recoverability perspective. | I would say first restore it and then sell it. You dont need to give you apple id. Also for updates, you don't need Apple id. If nobody buy it, I know a website that buy these MacBooks. I sold mine with damaged logic board for $220. You could try it. Here is the site address
<http://www.computerstar.ca/sell-macbook-macbookpro-toronto-mississauga.html>
I hope this helps. Thank you and good luck. |
486,178 | I already knew the basic meaning of pipeline indicating a series of tubes for transporting gas, oil, or water. But I found the word 'pipeline' written with a different nuance especially when aritcles describe tech companies' strategy. Here are the examples.
>
> 1. Blizzard: we have the strongest multi-year **pipeline** ever.
> ([Source](https://www.tweaktown.com/news/63775/blizzard-strongest-multi-year-pipeline/index.html))
> 2. Zynga’s live service portfolio while also expanding its new game **pipeline**. ([Source](https://www.businesswire.com/news/home/20181220005883/en/Zynga-Enters-Agreement-Acquire-Small-Giant-Games))
> 3. JD has a number of interesting growth drivers and initiatives in the **pipeline**. ([Source](https://www.thestreet.com/investing/stocks/three-fierce-chinese-stocks-to-track-right-now-14611205))
> 4. we still view as likely conservative given a robust **pipeline**.
>
>
>
Could you give more specific meaning? | 2019/02/19 | [
"https://english.stackexchange.com/questions/486178",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/291380/"
] | One suggestion that means a person who "*adapts easily*" is one who is "**flexible**".
<https://www.thefreedictionary.com/flexible> | Without knowing more about your mom and her situation, it's only a guess as to what will fit here:
***Easygoing*** - A person who is usually relaxed and in good humor - even when those around them may not be. Someone who "rolls with the punches".
<https://en.oxforddictionaries.com/definition/easy-going>
***Resourceful*** - The ability to obtain what you need and want on your own - not necessarily having to depend on others.
<https://www.merriam-webster.com/dictionary/resourceful>
***Two-faced*** - Able to control one's personality in order to be perceived favorably by conflicting or opposing persons - as well as allies.
<https://www.urbandictionary.com/define.php?term=two%20faced> |
44,964,363 | i am reading excel file using apache poi 3.16 here is my code
```
try
{
String excelPath = "C:\\Users\\wecme\\Desktop\\AccountStatement.xls";
FileInputStream fileInputStream = new FileInputStream(new File(excelPath));
// Create Workbook instance holding .xls file
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
// Get the first worksheet
XSSFSheet sheet = workbook.getSheetAt(0);
// Iterate through each rows
java.util.Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
// Get Each Row
Row row = rowIterator.next();
// Iterating through Each column of Each Row
java.util.Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
// Checking the cell format
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
}
}
System.out.println("");
}
} catch (IOException ie)
{
ie.printStackTrace();
}
```
my excel data looks like this:
```
Datetime Description TransactionId Credit Amount Debit Amount Remaining OdAmount EnteredBy Remarks
1/6/2017 8:14 IDEA (9542010237) COMMISSION GLGHQN 0.31 0 2721.92 0 iNHYD0390437LO IDEA COMMISSION
```
when i read other file which is not having time with date its reading properly ,but when i try to read this file this exception coming
```
Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:286)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:758)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:327)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:291)
at excelRead.ReadExcel.main(ReadExcel.java:27)
```
please help me , thank you. | 2017/07/07 | [
"https://Stackoverflow.com/questions/44964363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7791891/"
] | You're creating a `XSSFWorkbook` which is only suitable for working on xlsx files, i.e. the new xml based office format. Your file extension (xls) however suggests that this is the older Microsoft Office (2003 I guess) format. In order to fix the error you need to convert the file to xlsx format or you need to work with a [HSSFWorkbook](https://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html)
You can find some samples concerning HSSF here: <https://poi.apache.org/spreadsheet/examples.html#hssf-only>
Some examples concerning XDDF can be found here: <https://poi.apache.org/spreadsheet/examples.html#xssf-only> | According to the code where the Exception is thrown (see: <https://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackage.java?view=markup#l286>)
And also the name of the package (openxml4j) it is required that the files are in an openxml compatible format. (i.e. xlsx)
In your case the library cannot open the file because it is not in a .zip format that it can open.
This question has also been asked two months ago, maybe this is also helpful:
[How to fix NotOfficeXmlFileException in java Apache POI?](https://stackoverflow.com/questions/43641081/how-to-fix-notofficexmlfileexception-in-java-apache-poi) |
10,355,767 | SQLalchemy gives me the following warning when I use a Numeric column with an SQLite database engine.
>
> SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively
>
>
>
I'm trying to figure out the best way to have `pkgPrice = Column(Numeric(12,2))` in SQLalchemy while still using SQLite.
This question [1] [How to convert Python decimal to SQLite numeric?](https://stackoverflow.com/questions/6319409/how-to-convert-python-decimal-to-sqlite-numeric) shows a way to use `sqlite3.register_adapter(D, adapt_decimal)` to have SQLite receive and return Decimal, but store Strings, but I don't know how to dig into the SQLAlchemy core to do this yet. Type Decorators look like the right approach but I don't grok them yet.
Does anyone have a SQLAlchemy Type Decorator Recipe that will have Numeric or Decimal numbers in the SQLAlchemy model, but store them as strings in SQLite? | 2012/04/27 | [
"https://Stackoverflow.com/questions/10355767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098059/"
] | Since it looks like you're using decimals for currency values, I'd suggest that you do the safe thing and store the value of currency in its lowest denomination, e.g. 1610 cents instead of 16.10 dollars. Then you can just use an Integer column type.
It might not be the answer you were expecting, but it solves your problem and is generally considered sane design. | Here is a solution inspired by both @van and @JosefAssad.
```
class SqliteDecimal(TypeDecorator):
# This TypeDecorator use Sqlalchemy Integer as impl. It converts Decimals
# from Python to Integers which is later stored in Sqlite database.
impl = Integer
def __init__(self, scale):
# It takes a 'scale' parameter, which specifies the number of digits
# to the right of the decimal point of the number in the column.
TypeDecorator.__init__(self)
self.scale = scale
self.multiplier_int = 10 ** self.scale
def process_bind_param(self, value, dialect):
# e.g. value = Column(SqliteDecimal(2)) means a value such as
# Decimal('12.34') will be converted to 1234 in Sqlite
if value is not None:
value = int(Decimal(value) * self.multiplier_int)
return value
def process_result_value(self, value, dialect):
# e.g. Integer 1234 in Sqlite will be converted to Decimal('12.34'),
# when query takes place.
if value is not None:
value = Decimal(value) / self.multiplier_int
return value
```
Like @Jinghui Niu mentioned, when decimal is stored as strings in sqlite, some query won't always function as expected, such as session.query(T).filter(T.value > 100), or things like sqlalchemy.sql.expression.func.min, or even order\_by, because SQL compares strings (e.g. "9.2" > "19.2" in strings) instead of numerical values as we expected in these cases. |
88,093 | I'm leaving my current position as a Software Developer in two months, to get started with my bachelors degree, but my Team Leader is not giving me any work to do. I also had a talk with him, about a week ago, where he gave me some tasks, but I already finished those (and told him that). He also said he would figure some more things out, but since then, there was no reply.
I want to do something for the company for as long as I'm here. And it's not like I'm doing nothing, but mostly it's just learning stuff, with little context to my actual work (as in learning another programming language, which is not used at my company). And it is making feel a little bad and as if I had to hide something from everyone else.
The other thing is I basically have nothing to lose, because I already got a reference letter for the work I have done. The only thing is I would loose is the salary for the next two months, which I need.
How should I deal with this Situation?
Should I ask for more work?
Even if my team leader can't give me anything, without making an effort to teach me something, which obviously wouldn't pay off.
Should I just keep on going like this? | 2017/03/29 | [
"https://workplace.stackexchange.com/questions/88093",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/61565/"
] | **Your team lead may be making the sensible call in giving you nothing to do.**
I have been in your team lead's position, and sometimes your doing nothing may be the most productive thing for the team. Starting to work in an area you are not familiar with is likely to need some input from other team members in terms of teaching or mentoring, or runs the risk of you checking in code with mistakes. This is likely true even if you are a good self-learner. With two months to go it may not be worth other people taking the time getting you up to speed.
First (which I think you have already done) make sure your team lead is aware that you are available to do more work and would like more work. If she doesn't give you any, ask if she is OK with you doing some general learning until a task becomes available. Then treat the time like a free gift of learning time. Learning about something that is somewhat related to your job would be good, but since you are about to go to school, reading up on subject you know you will be studying there would also be good. If your company has access to a new technology you would like to learn about, do that.
Check in fairly frequently with your team lead to make sure there are no tasks he wants you to work on, but other than that, enjoy the free learning time. Remember when you come to apply for jobs after graduation, that this was a company that valued learning and didn't waste your time, and consider applying to them again. | >
> I did ask for work, but like I said, there is nothing to do for me, which wouldn't need schooling.
>
>
>
This point is realy bothering me , have you thought about the fact your lead knows his job , and asked you to "school" some stuff because you don't yet have the required level to help on the next tasks ?
I know it can be hard to acknowledge but maybe you don't have what it takes yet to work alongside the team on bigger tasks.
But if it's not the case then you should totaly do what François Gautier told you. Come up with tasks you can do , or see with the team members if they'd be ok to share some work with you. |
27,771,324 | I am using googles official oauth2client.client to access the google
plus api. I have a refresh token (that does not expire) stored in a database, and need
to recreate the temporary "Credentials" (access token) from that.
But I could not find a way to do this with to official library supplied by google.
So I hacked around it: used urllib to access the API that gives me a new
access\_token from the refresh\_token. Using the access\_token I can then use the library.
I must be missing somthing!
```
from apiclient import discovery
from oauth2client.client import AccessTokenCredentials
from urllib import urlencode
from urllib2 import Request , urlopen, HTTPError
import json
# ==========================================
def access_token_from_refresh_token(client_id, client_secret, refresh_token):
request = Request('https://accounts.google.com/o/oauth2/token',
data=urlencode({
'grant_type': 'refresh_token',
'client_id': client_id,
'client_secret': client_secret,
'refresh_token': refresh_token
}),
headers={
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
)
response = json.load(urlopen(request))
return response['access_token']
# ==========================================
access_token = access_token_from_refresh_token(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN)
# now I can use the library properly
credentials = AccessTokenCredentials(access_token, "MyAgent/1.0", None)
http = credentials.authorize(httplib2.Http())
service = discovery.build('plus', 'v1', http=http)
google_request = service.people().get(userId='me')
result = google_request.execute(http=http)
``` | 2015/01/04 | [
"https://Stackoverflow.com/questions/27771324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/153574/"
] | I use: [oauth2client.client.GoogleCredentials](http://oauth2client.readthedocs.io/en/latest/source/oauth2client.client.html#oauth2client.client.GoogleCredentials)
```
cred = oauth2client.client.GoogleCredentials(access_token,client_id,client_secret,
refresh_token,expires_at,"https://accounts.google.com/o/oauth2/token",some_user_agent)
http = cred.authorize(httplib2.Http())
cred.refresh(http)
self.gmail_service = discovery.build('gmail', 'v1', credentials=cred)
``` | I recommend this method.
```
from oauth2client import client, GOOGLE_TOKEN_URI
CLIENT_ID = "client_id"
CLIENT_SECRET = "client_secret"
REFRESH_TOKEN = "refresh_token"
credentials = client.OAuth2Credentials(
access_token = None,
client_id = CLIENT_ID,
client_secret = CLIENT_SECRET,
refresh_token = REFRESH_TOKEN,
token_expiry = None,
token_uri = GOOGLE_TOKEN_URI,
token_ id = None,
revoke_uri= None)
http = credentials.authorize(httplib2.Http())
```
Even if the access token has expired, the credential is still authorize because of the refresh token. |
66,167,878 | After updating my flutter project when I was going to run the application in the android studio, I got the following error.
```
e: C:\Users\user\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\fluttertoast-7.1.5\android\src\main\kotlin\io\github\ponnamkarthik\toast\fluttertoast\MethodCallHandlerImpl.kt: (16, 16): Redeclaration: MethodCallHandlerImpl
e: C:\Users\user\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\fluttertoast-7.1.6\android\src\main\kotlin\io\github\ponnamkarthik\toast\fluttertoast\MethodCallHandlerImpl.kt: (17, 16): Redeclaration: MethodCallHandlerImpl
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':fluttertoast:compileDebugKotlin'.
> Compilation error. See log for more details
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 52s
Exception: Gradle task assembleDebug failed with exit code 1
```
I tried following steps but I was not able to fix this.
* pub get, pub upgrade
* And here's my flutter doctor result
"C:\Program Files\flutter\bin\flutter.bat" doctor --verbose
[√] Flutter (Channel stable, 1.22.4, on Microsoft Windows [Version 10.0.19042.804], locale en-US)
• Flutter version 1.22.4 at C:\Program Files\flutter
• Framework revision 1aafb3a8b9 (3 months ago), 2020-11-13 09:59:28 -0800
• Engine revision 2c956a31c0
• Dart version 2.10.4
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
• Android SDK at C:/Users/user/AppData/Local/Android/Sdk
• Platform android-30, build-tools 30.0.2
• ANDROID\_HOME = C:/Users/user/AppData/Local/Android/Sdk
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0\_242-release-1644-b01)
X Android license status unknown.
Run `flutter doctor --android-licenses` to accept the SDK licenses.
See <https://flutter.dev/docs/get-started/install/windows#android-setup> for more details.
[!] Android Studio (version 4.1.0)
• Android Studio at C:\Program Files\Android\Android Studio
X Flutter plugin not installed; this adds Flutter specific functionality.
X Dart plugin not installed; this adds Dart specific functionality.
• Java version OpenJDK Runtime Environment (build 1.8.0\_242-release-1644-b01)
[!] VS Code (version 1.53.0)
• VS Code at C:\Users\user\AppData\Local\Programs\Microsoft VS Code
X Flutter extension not installed; install from
<https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter>
[√] Connected device (1 available)
• sdk gphone x86 arm (mobile) • emulator-5554 • android-x86 • Android 11 (API 30) (emulator)
! Doctor found issues in 3 categories.
Process finished with exit code 0
How can I fix this issue? | 2021/02/12 | [
"https://Stackoverflow.com/questions/66167878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10595169/"
] | This was happened due to a pub cache conflict. The problem was fixed after executing the following command in the terminal.
1. dart pub cache repair
2. dart pub get
3. dart pub upgrade | I got the same error. Tried updating `compileSdkVersion`. Didn't work for me. This solved my problem.
1. pubspec.yaml -->> pub upgrade
2. Change `fluttertoast` version to latest
3. Pub get
4. Run... |
25,443,258 | I want to calculate the difference between a start time and an end time. In `HH:mm` format.
I receive a negative value when, for example, the start time is `22.00` and the end time is `1.00` the next day.
How do I let the program know the end time is on the next day?
My script:
```
public void setBeginTijd()
{
String dateStart = "22:00";
String dateEnd = "1:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date d1 = null;
Date d2 = null;
try
{
d1 = format.parse(dateStart);
d2 = format.parse(dateEnd);
long diff = d2.getTime() - d1.getTime();
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
System.out.println(diffMinutes);
System.out.println(diffHours);
}
catch (Exception e)
{
e.printStackTrace();
}
}
``` | 2014/08/22 | [
"https://Stackoverflow.com/questions/25443258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3374335/"
] | As already mentioned by some people, it is important to also know day, month and year of each event to calculate periods for events that are not on the same day.
I modified your method the way I think it could help you:
```
public void setBeginTijd()
{
String dateStart = "22.08.2014 22:00";
String dateEnd = "25.08.2014 01:00";
SimpleDateFormat fullFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
Date d1 = null;
Date d2 = null;
try
{
d1 = fullFormat.parse(dateStart);
d2 = fullFormat.parse(dateEnd);
long diff = d2.getTime() - d1.getTime();
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Delta minutes: " + diffMinutes);
System.out.println("Delta hours: " + diffHours);
System.out.println("Delta days: " + diffDays);
}
catch (Exception e)
{
e.printStackTrace();
}
}
``` | Here is the correct math for time difference in hours & minutes. Stripping of the decimal fraction is happening automatically when you operate on int/long values.
```
long diff = d2.getTime() - d1.getTime();
long diffHours = diff / 1000 / 60 / 60;
long diffMinutes = diff / 1000 / 60 - diffHours * 60;
``` |
8,301,490 | ```
when i try to run my Application it gives me following error:
Compilation error
The file /app/models/setting.java could not be compiled. Error raised is : The type Setting is already defined
```
* I do have only one file "Setting.java", which is in the models directory
* the file is named "Setting.java" and not "setting.java" as the error message suggests
* i do not include any play modules
I am running play on windows. Is it possible that play has problems with windows' case insensitive? So it would first try to compile models/Setting.java and after that models/setting.java ??
What else could be the reason for this odd behavior?
/EDIT:
Since i wrote this question here i did not edit anything at my play application and i did not restart it. Now i just refreshed the page and the same error comes again - but with another model!!
```
The file /app/models/staticsite.java could not be compiled. Error raised is : The type Staticsite is already defined
```
/EDIT2:
After a few page refreshes in the browser this error appeared:
```
The file /app/models/setting.java could not be compiled. Error raised is : The public type Setting must be defined in its own file
```
The file IS named "Setting.java" and the class IS named Setting | 2011/11/28 | [
"https://Stackoverflow.com/questions/8301490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1070022/"
] | This error happens when you rename the class file that you try to compile. Simply re run the play frame work after you refract the class name. This will fix the issue. | Did you have a `settings.java` and replaced it with `Settings.java`? Anyway, try `play clean`.
If that doesn't work, check very carefully that you don't have any problematic invisible characters in your file. |
64,666,682 | so my problem is that I'm trying to write a program that uses a switch case to tell a function which case to do. I tried to include an or statement into the switch cases so that I could have a range of values for each case but it seems to be presenting me with an error. Is there a fix to this problem using the switch case or am I simply misusing the switch case and should try a different method? Thanks.
```
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int Random(int);
void Movement(void);
int main()
{
int healthratio=5;
switch(healthratio){
case healthratio>0 || healthratio<=10:
printf("%d.\n",healthratio);
break;
case healthratio>10 || healthratio<=20:
printf("%d.\n",healthratio);
break;
case healthratio>20:
printf("%d.\n",healthratio);
break;
}
}
```
When I run this code I get this error "error: case label does not reduce to an integer constant" | 2020/11/03 | [
"https://Stackoverflow.com/questions/64666682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14567401/"
] | ```
case healthratio>0 || healthratio<=10
```
This is not valid in standard C, some compilers allows the use of [case ranges](https://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html), i.e. `gcc` and `clang`:
```
case 0 ... 10:
printf("%d.\n",healthratio);
break;
```
But if you can not use them then you are forced to define all cases:
```
case 0:
case 1:
case 2:
...
case 10:
printf("%d.\n",healthratio);
break;
```
or use `if` statements: `if (x >= 0 && x <= 10) ...` | According to the C Standard (6.8.4.2 The switch statement)
>
> 3 **The expression of each case label shall be an integer constant
> expression** and no two of the case constant expressions in the same
> switch statement shall have the same value after conversion. There may
> be at most one default label in a switch statement. (Any enclosed
> switch statement may have a default label or case constant expressions
> with values that duplicate case constant expressions in the enclosing
> switch statement.)
>
>
>
However in labels like this
```
case healthratio>0 || healthratio<=10:
```
the used expression is not a constant expression. Moreover if you used a constant operands of the expression `healthratio>0 || healthratio<=10` then depending on whether the expression is true or false you had a label either
```
case 0:
```
or
```
case 1:
```
That is it is not what you are expecting.
Instead of the switch statement you should use if-else statements like
```
if ( healthratio>0 && healthratio<=10 )
{
printf("%d.\n",healthratio);
}
else if ( healthratio>10 && healthratio<=20 )
{
printf("%d.\n",healthratio);
}
else
{
printf("%d.\n",healthratio);
}
``` |
67,540,057 | My bootstrap model is not hidden by default. I want it to show up only when I click a link.
I am a novice in web development.
**tst.html**
```
<!DOCTYPE html>
<html lang="english">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Testing</title>
<!-- Bootstrap CSS CDN -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6"
crossorigin="anonymous"
>
<!-- Font Awesome JS -->
<script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="sha384-tzzSw1/Vo+0N5UhStP3bvwWPq+uvzCMfrN1fEFe+xBmv1C/AtVX5K0uZtmcHitFZ" crossorigin="anonymous"></script>
<script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="modal-fade" id="recordContent">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="recordContentLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
content
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="buttonCustom">Understood</button>
</div>
</div>
</div>
</div>
<a href="" data-toggel='modal' data-target="#recordContent"> Open modal</a>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
</body>
</html>
``` | 2021/05/14 | [
"https://Stackoverflow.com/questions/67540057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11483786/"
] | Just a couple of issues you class must be `modal fade` not `modal-fade` and your target attribute modal `data-toggle` not `data-toggel`
```html
<!DOCTYPE html>
<html lang="english">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Testing</title>
<!-- Bootstrap CSS CDN -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6"
crossorigin="anonymous"
>
<!-- Font Awesome JS -->
<script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="sha384-tzzSw1/Vo+0N5UhStP3bvwWPq+uvzCMfrN1fEFe+xBmv1C/AtVX5K0uZtmcHitFZ" crossorigin="anonymous"></script>
<script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script>
</head>
<body>
<div class="container" >
<div class="modal fade" id="recordContent" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="recordContentLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
content
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="buttonCustom">Understood</button>
</div>
</div>
</div>
</div>
<a href="" data-toggle='modal' data-target="#recordContent"> Open modal</a>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
</body>
</html>
``` | This is working now, you might be missing some right piece of code. Please check below code
```html
<!DOCTYPE html>
<html lang="english">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Testing</title>
<!-- Bootstrap CSS CDN -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<!-- Font Awesome JS -->
<script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="sha384-tzzSw1/Vo+0N5UhStP3bvwWPq+uvzCMfrN1fEFe+xBmv1C/AtVX5K0uZtmcHitFZ" crossorigin="anonymous"></script>
<script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="modal fade" id="recordContent" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
content
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<a href="" data-toggle='modal' data-target="#recordContent"> Open modal</a>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
</body>
</html>
``` |
48,816,636 | I am little bit new to the programming. I am learning Python, version 3.6.
```
print("1.+ \n2.-\n3.*\n4./")
choice = int(input())
if choice == 1:
sum = 0
print("How many numbers you want to sum?")
numb = int(input())
for i in range(numb):
a = int(input(str(i+1)+". number "))
sum+=a
print("Result : "+str(sum))
```
For improving myself i am trying to build a calculator but first i am asking how many numbers user want to calculate. You can see this in code above, but when it is comes to subtracting or dividing or multiplying i have no idea what to do.
My reason to do it like this i want to do the calculator like in real time calculators. | 2018/02/15 | [
"https://Stackoverflow.com/questions/48816636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8881970/"
] | You can also use the \*args or \*kargs in order to subtract more than two numbers. If you define \*args keyword in a function then it will help you to take as many variables you want. | There are two methods to solve this:
**Method-1**
Using the logic for subtraction a-b-c-… = ((a-b)-c)-…
```
def subt1(*numbers): # defining a function subt1 and using a non-keyword argument *numbers so that variable number of arguments can be provided by user. All these arguments will be stored as a tuple.
try: # using try-except to handle the errors. If numbers are given as arguments, then the statements in the try block will get executed.
diff = numbers[0] # assigning the first element/number to the variable diff
for i in range(1,len(numbers)): # iterating through all the given elements/ numbers of a tuple using a for loop
diff = diff - numbers[i] # performing the subtraction operation for multiple numbers from left to right, for eg, a-b-c = (a-b)-c
return diff # returning the final value of the above operation
except: # if no arguments OR more than one non-numbers are passed, then the statement in the except block will get executed
return 'please enter numbers as arguments'
```
subt1(10, 5, -7, 9, -1) ----> here subt1 performs 10-5-(-7)-9-(-1) and returns the value
>
> 4
>
>
>
subt1(25.5, 50.0, -100.25, 75) ----> here subt1 performs 25.5-50.0-(-100.25)-75 and returns the value
>
> 0.75
>
>
>
subt1(20j, 10, -50+100j, 150j) ----> here subt1 performs 20j-10-(-50+100j)-150j and returns the value
>
> (40-230j)
>
>
>
subt1() ----> here the statement in the except block is returned as no input is passed
>
> 'please enter numbers as arguments'
>
>
>
subt1('e', 1, 2.0, 3j) ---> here the statement in the except block is returned as a string 'e' is passed which is not a number
>
> 'please enter numbers as arguments'
>
>
>
**Method-2**
Using the logic for subtraction a-b-c-… = a-(b+c+…) = a-add(b,c,…)
```
def subt2(*numbers):
try:
add = 0 # initializing a variable add with 0
for i in range(1,len(numbers)):
add = add+ numbers[i] # performing the addition operation for the numbers starting from the index 1
return numbers[0]-add # returning the final value of subtraction of given numbers, logic : a-b-c = a-(b+c) = a-add(b,c)
except:
return 'please enter numbers as arguments'
```
subt2(10, 5, -7, 9, -1) ----> here subt2 performs 10-5-(-7)-9-(-1) and returns the value
>
> 4
>
>
>
subt2(25.5, 50.0, -100.25, 75) ----> here subt2 performs 25.5-50.0-(-100.25)-75 and returns the value
>
> 0.75
>
>
>
subt2(20j, 10, -50+100j, 150j) ----> here subt2 performs 20j-10-(-50+100j)-150j and returns the value
>
> (40-230j)
>
>
>
Note : All the above test cases have been tested in Jupyter notebooks. |
61,307,490 | I am considering using the Singelton Design Pattern and create a Singelton of my Main class. While I was searching, I found some comments that this is rather bad programming practice, especially since the declaration of a static method does not do justice to object-oriented programming. Do you have any suggestions for improving my code?
```
public class MainClass {
private static MainClass instance = new MainClass();
public static MainClass getMainInstance() {
return instance;
}
public static void main(String[] args) {
MainClass main = Main.instance;
}
}
``` | 2020/04/19 | [
"https://Stackoverflow.com/questions/61307490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11096084/"
] | budget is a group of limits to certain values that affect site performance
Open angular.json file and find budgets keyword and increase value
```
"budgets": [
{
"type": "initial",
"maximumWarning": "4mb", <===
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "150kb",
"maximumError": "150kb"
}
]
``` | Even though you can just bump up your limits, it's probably not what you want to do. The limits are there for a reason.
You should try to avoid exceeding them in the first place if possible.
For me, the problem was I was importing my theme file (which was quite large) into my components' SCSS files.
```
@import "src/my-theme";
```
The only reason for that was that I needed to access my SCSS color variables within those files. It's a terrible idea to import any larger file in multiple of your styles only to access a few of your variables; your application will become huge and really slow to load.
If you only need access to your variables, I suggest this solution:
1. in your theme file, make CSS variables like so: `:root { --primary-color: #11dd11; }`
2. remove the import from your other SCSS files and use this to get your color instead: `var(--primary-color)` |
43,104,209 | I am creating a google map that is populated with markers based upon information from my database. I have followed the [tutorial](https://developers.google.com/maps/documentation/javascript/mysql-to-maps#checking-that-xml-output-works) provided from Google in this first step.
The map works fine, however since some of my markers are close together, I would like to take advantage of marker clustering. I’ve followed what I can from Google's tutorial on [marker clustering](https://developers.google.com/maps/documentation/javascript/marker-clustering).
However, I cannot find a way to get it to work. My markers just show up the way they are, without any clustering. I think I have followed all of the steps, linking the JS file to my HTML, downloading and uploading the marker icons and JS file to my hosting site, etc.
How can I continue to create markers from my database, but also cluster the markers?
I have tested the exact code from the google marker clusterer tutorial, and everything works fine. (However the markers are not in the locations I need.)
A simplified version of my HTML(PHP) webpage is as follows:
```
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Website</title>
<style>
map {
height: 400px;
width: 98%;
border: 5px outset SteelBlue;
}
</style>
</head>
<body>
<!-- Google Map -->
<div id='map'>
</div>
<!-- Google MAPS API & Custom Maps JS-->
<!-- This is my personal file that houses the main Javascript code -->
<script src="findermap.js"></script>
<!-- A link to download this file is provided by the Google tutorial -->
<script src="markerclusterer.js"></script>
<!-- Basic Google Maps API key link -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY-KEY-IS-USED-HERE&callback=initMap">
</script>
</body>
</html>
```
Here is basically the JavaScript file I use, "findermap.js"
```
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(0, 0),
zoom: 1
});
var customIcons = {
type1: {
icon: 'icon_type1.png'
},
type2: {
icon: 'icon_type2.png'
},
type3: {
icon: 'icon_type3.png'
},
type4: {
icon: 'icon_type4.png'
}
};
var markers = [];
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('https://my-website.com/getinfo.php', function(data) {
var xml = data.responseXML;
var markers2 = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers2, function(markerElem) {
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
markers.push(marker);
});
});
var options = {
imagePath: '/clustericons/m'
};
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, options);
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('getinfo.php') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
``` | 2017/03/29 | [
"https://Stackoverflow.com/questions/43104209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7788248/"
] | Use optional binding to ensure the values are non-nil strings and that they can be converted to `Int`.
```
if let str1 = data[0]["total1"] as? String, let str2 = data[0]["total2"] as? String {
if let int1 = Int(str1), let int2 = Int(str2) {
let sum = int1 + int2
} else {
// One or more of the two strings doesn't represent an integer
}
} else {
// One or more of the two values is nil or not a String
}
``` | Since the underlying objects are `NSString`, you can also do:
```
if let num1 = (data[0]["total1"] as? NSString)?.intValue,
let num2 = (data[0]["total2"] as? NSString)?.intValue {
let sum = num1 + num2
}
```
As @rmaddy pointed out in the comments, if a value is not an integer (such as `"hello"`), it will convert to `0`. Depending on your knowledge of the data your app is receiving and what you want to happen in this case, that result may or may not be appropriate.
`.intValue` is more forgiving of the string data format compared to `Int(str)`. Leading and trailing spaces are ignored and a floating point value such as `13.1` will be converted to an integer. Again, it depends on what you want to happen in your app. |
16,325,271 | Using LINQ, can I write a statement that will return an IEnumerable of the indexes of items.
Very simple instance:
```
{1,2,4,5,3}
```
would just return
```
{0,1,2,3,4}
```
and
```
{1,2,4,5,3}.Where(num => num == 4)
```
would return
```
{2}
```
It isn't exact code, but it should get the idea across. | 2013/05/01 | [
"https://Stackoverflow.com/questions/16325271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1116831/"
] | ```
IEnumerable<int> seq = new[] { 1, 2, 4, 5, 3 };
// The indexes of all elements.
var indexes = Enumerable.Range(0, seq.Count());
// The index of the left-most element with value 4.
// NOTE: Will return seq.Count() if the element doesn't exist.
var index = seq.TakeWhile(x => x != 4).Count();
// The indexes of all the elements with value 4.
// NOTE: Be careful to enumerate only once.
int current_index = 0;
var all_indexes =
from e in (
from x in seq
select new { x, Index = current_index++ }
)
where e.x == 4
select e.Index;
``` | This should do it. Not sure how efficient it is though..
```
List<int> list = new List<int>()
{
1,
2,
3,
4,
5
};
var indexes = list.Select(item => list.IndexOf(item));
var index = list.Where(item => item == 4).Select(item => list.IndexOf(item));
``` |
8,901 | Has anyone else noticed the content of this post no longer shows?
<https://civicrm.org/blogs/colemanw/create-your-own-tokens-fun-and-profit>
I'm trying to write a token to use the contribution note as a smarty variable but would like to review the tutorial. .. | 2016/01/15 | [
"https://civicrm.stackexchange.com/questions/8901",
"https://civicrm.stackexchange.com",
"https://civicrm.stackexchange.com/users/73/"
] | Andrew West's comment seems to be correct. There are two different things happening here - or three, depending on how you look at it.
The most important is "Permission Denied". I just visited your site, and confirmed you're running Drupal as your website software. Go to this page: www.mcuw.org/admin/people/permissions. In the "CiviCRM" section, find "CiviContribute: make online contributions", and make sure that it's checked off for both "Anonymous User" and "Authenticated User". Note that you'll need to be a Drupal administrator to view that page; if you're not, please contact your website administrator.
Second - you're getting notices on the top of the page. Those notices shouldn't affect anything, but they're bad for the donors to see, it erodes trust. You should hide those. A good explanation of how to do that is [here](https://drupal.stackexchange.com/questions/35589/how-to-prevent-warnings-from-displaying-to-anonymous-users).
Third - I'm not sure why you'd be getting those notices at all. You may want to ask your website administrator if there are any customizations they can think of that might lead to those notices appearing. | You need to contact your hosting company to resolve. United Way has vendors (OneEach Technologies, etc.) that provide website/hosting/civicrm packages to many UW affiliates that manage the backend configuration of your website.
You do not have the permissions to make the changes needed to fix this. Your hosting company does. |
73,298,614 | I have two 2D arrays like these:
```
mix = [[1,'Blue'],[2,'Black'],[3,'Black'],[4,'Red']]
possibilities = [[1,'Black'],[1,'Red'],[1,'Blue'],[1,'Yellow'],
[2,'Green'],[2,'Black'],
[3,'Black'],[3,'Pink'],
[4,'White'],[4,'Blue'],[4,'Yellow'],
[5,'Purple'],[5,'Blue']
]
```
I want to loop through the **possibilities** list, find the exact index in which it matches the **mix** list, then append the correct mix into a new list.**IF it does not match the MIX list, append into a "bad list" and then move on to the next iteration.** For now this is the idea I had ---- note it totally DOES NOT work! :)
```
i = 0
j = 0
bad_guess = []
correct_guess = []
while i < len(mix):
while possibilities[j] != mix[i]:
j += 1
if possibilities[j] == mix[i]:
i +=1
correct_guess.append(possibilities[j])
j = 0
elif possibilities[j] != mix[i]:
bad_guess.append(mix[i])
break
```
**Output**
Basically the output I would want for this example is:
```
correct_guess = [[1,'Blue'],[2,'Black'],[3,'Black'],[5,'Purple']
bad_guess = [4,'Red']
``` | 2022/08/09 | [
"https://Stackoverflow.com/questions/73298614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19641211/"
] | There are a number of ways of solving this. The simple way is to loop through the lists, but that's not very pythonic. You can remove the inner loop using a containment check:
```
bad_guess = []
correct_guess = []
for item in mix:
if item in possibilities:
correct_guess.append(item)
else:
bad_guess.append(item)
```
The `in` operator is going to do a linear search through `possibilities` at every iteration. For a small list like this, it's probably fine, but for something larger, you will want a faster lookup.
Faster lookup is offered in sets. Unfortunately, sets can not contain non-hashable types such as lists. The good news is that they can contain tuples:
```
mix = [tuple(item) for item in mix]
possibilities = {tuple(item) for item in possibilities}
bad_guess = []
correct_guess = []
for item in mix:
if item in possibilities:
correct_guess.append(item)
else:
bad_guess.append(item)
```
Another way to get the same result is to first sort `mix` by whether an item appears in `possibilities` or not, and then use `itertools.groupby` to create the output lists. This approach is fun to parse, but is not particularly legible, and therefore not recommended:
```
key = lambda item: item in possibilities
bad_guess, correct_guess = (list(g) for k, g in itertools.groupby(sorted(mix, key=key), key=key))
```
This last method is more algorithmically complex than the set lookup because sorting is an O(N log N) operation, while lookup in a set is O(1). | ```
mix = {1:'Blue' , 2:'Black' , 3:'Black' , 4:'Red'}
possibilities = [[1,'Black'],[1,'Red'],[1,'Blue'],[1,'Yellow'],
[2,'Green'],[2,'Black'],
[3,'Black'],[3,'Pink'],
[4,'White'],[4,'Blue'],[4,'Yellow'],
[5,'Purple'],[5,'Blue']
]
for poss in possibilities:
if (mix[poss[0]] = poss[1]) & (poss not in bad_guess):
bad_guess.append(poss)
elif poss not in good_guess:
good_guess.append(poss)
```
you could try making the mix list a dictionary instead so you dont need to iterate over it |
15,601 | I have a selection of paths in illustrator (cs6).
I want to select all the paths and free transform them to something like a 3rd of the size. The problem is when I shrink them down, the stroke on the paths stays the same. So originally some had 1pt and 2pt stroke, bit when I free transform all the paths to a 3rd of the original size, the strokes are all still 1pt and 2pt big.
I don't want to have to go through each path and change the stroke, as it would take a long time. is there a tool/option in illustrator that can help with this? | 2013/02/02 | [
"https://graphicdesign.stackexchange.com/questions/15601",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/9693/"
] | Using the Scale tool, tick the check box which says "Scale strokes and effects" before scaling. That reduces your strokes proportionally. | Another way to get there is under the General Preferences settings:
 |
500,144 | Hello and how you doing today? I just came across a problem which need to use Stokes theorem.
The problems says:
Evaluate the surface integral
$$
\int\_{S}\nabla\times\vec{F}\cdot{\rm d}\vec{S}
$$
where F(x,y,z)=$(y^2)i$ + $(2xy)j$+$(xz^2)k$ and S is the surface of the paraboloid $z=
x^2+y^2$ bounded by the planes $x=0,y=0$ and $z=1$ in the first quadrant pointing upward.
I got $\nabla F$ which is $(-z^2)j$
So, I stuck at here because I dont know the boundary C in order to use Stokes theorem. So could someone please help me to start?
By the way thank you very much for taking your time and consideration to help me on this problem.
 | 2013/09/21 | [
"https://math.stackexchange.com/questions/500144",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/39213/"
] | Set $m=(a+b+c)/3$, $A=a-m$, $B=b-m$, $C=c-m$ and $x=y+m$. Then your equation becomes
$$
(y-A)^3 + (y-B)^3 + (y-C)^3 = 0
$$
and, since $A+B+C=0$, your expansion applies to give
$$
y^3+(A^2+B^2+C^2)-\frac{A^3+B^3+C^3}{3}=0
$$
which is a suppressed cubic, whose discriminant is
$$
\frac{1}{4}\biggl(-\frac{A^3+B^3+C^3}{3}\biggr)^2+\frac{1}{27}(A^2+B^2+C^2)^3>0
$$
so the equation has only one real root. | Let's substitute the variable: $x=y+\frac{(a+b+c)}{3}$
The equation will now look like
$$3y^3+(2a^2-2ab-2ac+2b^2-2bc+2c^2)y+\frac{(a+b-2c)(a-3b+c)(b-2a+c)}{9}=0$$
Now we apply Cardano's method.
$$Q=\left(\frac{2a^2-2ab-2ac+2b^2-2bc+2c^2}{3}\right)^3+\left(\frac{\frac{(a+b-2c)(a-3b+c)(b-2a+c)}{9}}{2}\right)^2=\frac{8}{27}(a^2-ab-ac+b^2-bc+c^2)^3+\frac{1}{324}(a+b-2c)^2(a-2b+c)^2(b-2a+c)^2$$
Then the answer is given depending on the sign of Q.
If $Q>0$ there is only one real root
If $Q<0$ there are three distinct real roots
If $Q=0$ there are two distinct real roots. |
12,602,759 | I have a persistent dictionary (string -> string map) that I write to a NAND filesystem as a log file. My binary format is:
```
1 byte - key size
<key size> bytes - key without the terminating nul-character
2 bytes - value size and flags
<value size> bytes - value without terminating nul-character
```
Usually, I write between 20 to 100 bytes with each change in the dictionary. But since this is been persisted on NAND this design causes a new page to be allocated each time, reducing my available NAND space by 2k on each iteration.
I can't cache the writes because I can't lose this data. It's running point of sales terminals, saving transaction data. My algorithm effectively writes and call flush, so this doesn't happen.
Now, is there a de-facto or standard algorithm to solve this problem? I've looked at power-down triggers on the target platform, but the SDK suggests using the NAND as the persistent layer. | 2012/09/26 | [
"https://Stackoverflow.com/questions/12602759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131326/"
] | Being PHP loosely typed, it can't do like `{$this -> callback}()`; you have to store it in a temp variable or to use `call_user_func()` either.
EDIT - consider something like this:
```
class Lambdas
{
protected $double;
protected $triple;
public function __construct($double, $triple)
{
$this -> double = $double;
$this -> triple = $triple;
}
public function __call($name, $arguments)
{
if( is_callable($this -> {$name}) ){
return call_user_func_array($this -> {$name}, $arguments);
}
}
}
$lambdas = new Lambdas(
function($a){ return $a * 2;},
function($a){ return $a * 3;}
);
echo $lambdas -> double(2); // prints 4
echo $lambdas -> triple(2); // prints 6
``` | Dirty and dangerous, but you might succeed using eval..
```
class foo
{
private $call_back_1 = null;
private $call_back_2 = null;
function __construct($func1, $func2)
{
$this->call_back_1 = func1;
$this->call_back_2 = func2;
}
function provokeCallBacks()
{
eval($this->call_back_1);
eval($this->call_back_2);
}
}
call1 = 'echo "inside call 1"';
call2 = 'echo "inside call 2"';
$test = foo(call1, call2);
$test->provokeCallBacks();
``` |
3,189,938 | I'm trying to write a custom SQL query that will create a list of the most recent Posts AND comments and I'm having trouble visualizing how i can do this.
I can pull the latest comments by date DESC and i can pull the latest posts by date DESC but how do I make a feed / query to show them both?
Here is my comment SQL
```
SELECT comment_id, comment_content, comment_date
FROM wp_comments
WHERE comment_author = 'admin'
ORDER BY comment_date DESC
```
Edit: more clear:
Sorry, I should have been a little more clear. I want to have a list like this based on what date they occurred:
```
Wordpress post
wordpress post
wordpress comment
wordpress post
wordpress comment
```
So if someone comments on a 4 month old post, it will still show up at the top of this 'feed' | 2010/07/06 | [
"https://Stackoverflow.com/questions/3189938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157503/"
] | To get a list based solely on the most recent timestamp from two tables, you need to use a UNION:
```
SELECT wc.comment_date AS dt
FROM WP_COMMENTS wc
UNION ALL
SELECT wp.post_date AS dt
FROM WP_POSTS wp
ORDER BY dt
```
...where `dt` is the column alias for the column that holds the date value for records in either table.
Use `UNION ALL` - because data is from two different tables, there's no change of duplicates to filter out. But that means you have to get the other columns you want from either table to line up based on data and data type... | No special mySql necessary, just use the [query\_posts](http://codex.wordpress.org/Function_Reference/query_posts) loop and the [get\_comments](http://codex.wordpress.org/Function_Reference/get_comments) function in the loop.
```
<?php query_posts('posts_per_page=10'); while (have_posts()) : the_post(); ?>
<div>
<a href="<?php the_permalink() ?>" title="Permanent Link to <?php the_title_attribute(); ?>"<?php the_title_attribute(); ?></a>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php echo the_title(); ?></a>
<?php
$comments = get_comments();
foreach($comments as $comm) :
echo($comm->comment_author);
echo($comm->comment_content);
endforeach;
?>
</div>
<?php endwhile; ?>
``` |
31,674,182 | I am trying to change the width and height of a DIV dynamically using variables in javascript. My code below is not working for me.
```
div_canvas.setAttribute('style', "width: '+w_resized+'px");
div_canvas.setAttribute('style', "height: '+h_resized+'px");
```
Where w\_resized and h\_resized are variables. | 2015/07/28 | [
"https://Stackoverflow.com/questions/31674182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4650787/"
] | Using setAttribute will override the previously provided values.... you can use the style property like
```
div_canvas.style.width = w_resized + 'px';
div_canvas.style.height = h_resized + 'px';
``` | Return the width property:
```
object.style.width
```
Set the width property:
```
object.style.width="auto|length|%|initial|inherit"
```
same for height |
63,157 | Looking at the `algorithm` tag in SO, I noticed that there are 6452 questions reported:

Yet going to the tag info page, at the same time it found 6455 of them

Earlier this morning this was true for `Delphi`: 5799 against 5800. This is not the case at the moment.
But it is true right now for `math`: 2751 against 2752. `Math` does not yet have a tag wiki, so it does not depend on this.
There just seem to be different counting algorithms that produce different results at times. | 2010/09/02 | [
"https://meta.stackexchange.com/questions/63157",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/-1/"
] | This may happen from time to time. We have lots of caching that may kick at different spots.
At the moment the counts are in-sync for the `algorithm` tag, so this was due to caching. | These numbers are cached, which explain why they're different. However, I'm surprised that they're not relying on the same cache, so it's still a bug. |
28 | I assume English.SE is not the right place to ask how to nicely translate a Chinese phrase into English, but is Chinese.SE the right place? | 2011/12/14 | [
"https://chinese.meta.stackexchange.com/questions/28",
"https://chinese.meta.stackexchange.com",
"https://chinese.meta.stackexchange.com/users/58/"
] | I would say its a valid question if its a phrase that could be quite ambiguous or difficult to translate.
Like, if it is a translation that can benefit the community beyond the equivalent of an online translator | I like translating. I get so much help from the R programming site and I would like to contribute where I can. I was quite active in the Chinese Baidu Zhidao site as an English to Chinese translator for a while, and I also translated a bit in the Yahoo Answers US site. |
10,031,455 | I sometimes see Perl code like this:
```
my ( $variable ) = blah....
```
What is the point of putting parentheses around a single variable? I thought parentheses were only used when declaring multiple variables, like:
```
my ( $var1, $var2, $var3 ) = blah...
``` | 2012/04/05 | [
"https://Stackoverflow.com/questions/10031455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/511609/"
] | The parentheses create a list context which affects how the right hand side of the assignment is evaluated.
Compare
```
my $x = grep { /s/ } qw(apples bananas cherries);
print $x;
```
with
```
my ($x) = grep { /s/ } qw(apples bananas cherries);
print $x;
```
You will often use this construction when [you just want to grab the first element of a list and discard the rest](https://stackoverflow.com/questions/3728337/). | You are confusing two different things. First off, when using `my` to declare several variables, you need to use parentheses:
```
my $foo, $bar;
```
Does not work, as it is considered to be two different statements:
```
my $foo;
$bar;
```
So you need parentheses to group together the argument into an argument list to the *function* `my`:
```
my($foo, $bar);
```
Secondly, you have explicit grouping in order to invoke list context:
```
$foo, $bar = "a", "b"; # wrong!
```
Will be considered three separate statements:
```
$foo;
$bar = "a";
"b";
```
But if you use parentheses to group `$foo` and `$bar` into a list, the assignment operator will use a list context:
```
($foo, $bar) = ("a", "b");
```
Curiously, if you remove the RHS parentheses, you will also experience a hickup:
```
($foo, $bar) = "a", "b"; # Useless use of a constant (b) in void context
```
But that is because the `=` operator has higher precedence than comma `,`, which you can see in [perlop](http://perldoc.perl.org/perlop.html). If you try:
```
my @array = ("a", "b");
($foo, $bar) = @array;
```
You will get the desired behaviour without parentheses.
Now to complete the circle, lets remove the list context in the above and see what happens:
```
my @array = ("a", "b");
$foo = @array;
print $foo;
```
This prints `2`, because the array is evaluated in scalar context, and arrays in scalar context return the number of elements they contain. In this case, it is `2`.
Hence, statements such as these use list context:
```
my ($foo) = @array; # $foo is set to $array[0], first array element
my ($bar) = ("a", "b", "c"); # $bar is set to "a", first list element
```
It is a way of overriding the scalar context which is implied in scalar assignment. For comparison, these assignments are in scalar context:
```
my $foo = @array; # $foo is set to the number of elements in the array
my $bar = ("a", "b", "c"); # $bar is set to "c", last list element
``` |
453,922 | So I want to do some logging and therefor, want to put a date in front of a bash script's output. The problem is that is has multiple lines of output. I am able to only put the date before the whole output. But then I have a line without a date in the logs. Of course I can assume the date from the line above is the same, but I was hoping there is a solution.
Thanks in advance!
This is my script that calls another script:
```
#!/bin/sh
echo $(date "+%F %T") : starting script
echo $(date "+%F %T") : $(./script.sh)
echo $(date "+%F %T") :script ended
```
This is the output:
```
2012-07-26 15:34:12 : starting script
2012-07-26 15:35:14 : First line of output
second line of output
2012-07-26 15:35:17 : script ended
```
And thats what I would like to have:
```
2012-07-26 15:34:12 : starting script
2012-07-26 15:35:14 : First line of output
2012-07-26 15:35:15 : second line of output
2012-07-26 15:35:17 : script ended
``` | 2012/07/26 | [
"https://superuser.com/questions/453922",
"https://superuser.com",
"https://superuser.com/users/148175/"
] | According to a [similar question on Stack Overflow](https://stackoverflow.com/questions/21564/is-there-a-unix-utility-to-prepend-timestamps-to-lines-of-text), there are 2 great options.
awk ([Answer](https://stackoverflow.com/questions/21564/is-there-a-unix-utility-to-prepend-timestamps-to-lines-of-text))
------------------------------------------------------------------------------------------------------------------------
```
<command> | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0; }'
```
annotate ([Answer](https://stackoverflow.com/a/21909/259953))
-------------------------------------------------------------
[annotate](http://jeroen.a-eskwadraat.nl/sw/annotate/annotate) is a small bash script, that can either be directly obtained through the link provided here, or, on Debian based systems, through the package `devscripts` (in the form of `annotate-output`). | You can use `awk`
```
./script.sh | awk '{ print d,$1}' "d=$(date "+%F %T")"
```
`awk` takes an input stream and modifies it's output. This script is saying "print d followed by the original output", then then populates `d` with the date. |
49,810,906 | Here is my code below
```
<td v-for="config in configs" v-if="config">
<input type="number" v-model="config.score" v-on:keyup="computeTestScores(allocation, $event)">
</td>
<td><span class="subtotal"></span></td>`
```
how do i compute the ***subtotal***? Secondly, if the values of any input changes, i want to be able ***update the total class***; | 2018/04/13 | [
"https://Stackoverflow.com/questions/49810906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5102083/"
] | You should not try to compute the sum with v-for. V-for is meant for presentation.
Instead add a computed value that calculates the subtotal. Inside the computed you should loop through the array, calculate the sum and return it. The computed property also calculates the new value automatically if any of the inputs change. | You may sum the values of your array with the `reduce` function. The total will update automatically if any score changes.
```
<td><span class="subtotal">{{ configs.reduce((a, c) => a + parseInt(c.score), 0) }}</span></td>
``` |
6,257,628 | I want to create web pages with dynamic content. I have an HTML page, and I want to call a lua script from it
1. How do I invoke the lua script?
`<script type="text/application" >`?
`<script type="text/lua" >`?
2. Retrieve data from it? Can I do something like:
```js
int xx = 0;
<script type=text/lua>
xx = 123;
</script>
```
and have any hope that `xx` will be `123` when the script exits?
3. Replace the current web page with the content generated by the lua script. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6257628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86184/"
] | Most of the CGI and Lua I have played with involve generating the web page and inserting the dynamic bits, rather than calling a script from a web page. So more like option C from your original question. Any HTML 4 or 5 elements you want to have could easily be added into the generated web page.
Here are some places you can check out for more detailed information:
[CGILua](http://keplerproject.github.com/cgilua/manual.html) has some good information on how to use CGI and Lua together.
[This long forum page](http://www.gammon.com.au/forum/?id=6498) has some good examples with code and output.
The **Beginning Lua Programming** book has a whole chapter walking through how to set up and use CGI and Lua. (Chapter 15 - Programming for the Web)
(While some of these places are a bit dated, they still do a good job of showing how to do this sort of thing.)
Remember: If you are using cgi or fastcgi on the server side you will need the first line of your Lua file to have a pointer to wherever the Lua interpreter is, such as:
```
#!/usr/local/bin/lua
``` | If you want to run a script from a browser, consider using javascript instead.
It is very similar to Lua, and unlike Lua it's interpreted by most browsers. |
38,539,417 | I currently have an Angular Directive that validates a password and confirm password field as matching. It works to a point, it does throw an error when the passwords do not match. However, it doesn't throw the error until you have entered data in both fields. How can I make it so the error for mismatched passwords is thrown as soon as you enter data in one field or the other?
Here is the directive (it has to be added to both fields that need to match):
```
.directive('passwordVerify', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, elem, attrs, ngModel) {
//if (!ngModel) return; // do nothing if no ng-model
// watch own value and re-validate on change
scope.$watch(attrs.ngModel, function() {
validate();
});
// observe the other value and re-validate on change
attrs.$observe('passwordVerify', function(val) {
validate();
});
var validate = function() {
// values
var val1 = ngModel.$viewValue;
var val2 = attrs.passwordVerify;
// set validity
ngModel.$setValidity('passwordVerify', !val1 || !val2 || val1 === val2);
};
}
};
});
```
And here is the directive in my form:
```
<div class="small-5 columns">
<div class="small-12 columns">
<label>
Password
<input
ng-class="{ notvalid: submitted && add_user_form.user_password.$invalid }"
class="instructor-input"
id="user_password"
type="password"
name='user_password'
placeholder="password"
value=''
required
ng-model="user.user_password"
password-verify="[[user.confirm_password]]"
>
</label>
<p class="help-text">
<span class=" ">Required</span>
</p>
<div
class="help-block"
ng-messages="add_user_form.user_password.$error"
ng-show="add_user_form.user_password.$touched || add_user_form.user_password.$dirty"
>
<span class="red">
<div ng-messages-include="/app/views/messages.html" ></div>
</span>
</div>
</div>
<div class="small-12 columns">
<label>
Confirm Password
<input
ng-class="{ notvalid: submitted && add_user_form.confirm_password.$invalid }"
class="instructor-input"
id="confirm_password"
ng-model="user.confirm_password"
name="confirm_password"
type="password"
placeholder="confirm password"
name="user_confirm_passsword"
required
password-verify="[[user.user_password]]"
>
</label>
<p class="help-text">
<span class=" ">
Enter matching password
</span>
</p>
<div
class="help-block"
ng-messages="add_user_form.confirm_password.$error"
ng-show="add_user_form.confirm_password.$dirty || add_user_form.confirm_password.$touched "
>
<span class="red">
<div
ng-messages-include="/app/views/messages.html"
></div>
</span>
</div>
</div>
``` | 2016/07/23 | [
"https://Stackoverflow.com/questions/38539417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5831695/"
] | This is what worked for me (ugly and hackish):
HTML:
```
<h1>Password Verification</h1>
<form name="pw" ng-controller="pw">
<p>
<label for="password">New Password
<input type="password" name="user_password" ng-model="user_password" ng-required="confirm_password && !user-password" password-verify="confirm_pasword">
<p ng-show="pw.user_password.$error.passwordVerify">Passwords do not match</p>
<p ng-show="pw.user_password.$error.required">This field is required</p>
</label>
</p>
<p>
<label for="password">Confirm Password
<input type="password" name="confirm_password" ng-model="confirm_password" ng-required="user_password && !confirm_password" password-verify="user_password">
<p ng-show="pw.confirm_password.$error.passwordVerify">Passwords do not match</p>
<p ng-show="pw.confirm_password.$error.required">This field is required</p>
</label>
</p>
</form>
```
Then the script:
```
angular.module('app', [])
.controller('pw', ['$scope', function($scope){
$scope.user_password = "";
$scope.confirm_password = "";
}])
.directive('passwordVerify', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elem, attrs, ngModel) {
scope.$watch(attrs.ngModel, function() {
if (scope.confirm_password === scope.user_password) {
scope.pw.confirm_password.$setValidity('passwordVerify', true);
scope.pw.user_password.$setValidity('passwordVerify', true);
} else if (scope.confirm_password !== scope.user_password) {
scope.pw.confirm_password.$setValidity('passwordVerify', false);
scope.pw.user_password.$setValidity('passwordVerify', false);
}
});
}
};
});
``` | While the above answers are correct, there is a very simple solution for this situation:
You can use a `ng-class` directive to set a class different from angularjs built-in class (`ng-invalid`) and add a simple style for it in your css. DO NOT FORGET to add `!important` to your style because angularjs overrides it ;) |
2,732,373 | In propositional logic, how should the sentence "neither A nor B" be converted into a Well Formed Formula? Is it $\sim(A \lor B)$ or should it be $\sim(A \land B)$? Can it be interrupted both ways? I need a little help understanding this. | 2018/04/11 | [
"https://math.stackexchange.com/questions/2732373",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/551328/"
] | Let $G$ be the Galois group $G=Gal(K/\Bbb{Q})$. We know that elements of $G$ permute the roots $\{\pm\alpha,\pm\beta\}$. Furthermore, 1) because $K=\Bbb{Q}(\alpha,\beta)$ knowing the images of $\alpha$ and $\beta$ determines an automorphism uniquely, 2) because $f(x)$ is known to be irreducible the permutation action is transitive.
* Transitivity implies that there exists an automorphism $\sigma\in G$ such that $\sigma(\alpha)=\beta$. Obviously then $\sigma(-\alpha)=-\beta$, so $\sigma(\beta)=\pm\alpha$.
* If $\sigma(\beta)=\alpha$, then, denoting $z=\alpha/\beta-\beta/\alpha$,
$$\sigma(z)=\frac{\sigma(\alpha)}{\sigma(\beta)}-\frac{\sigma(\beta)}{\sigma(\alpha)}=\frac\beta\alpha-\frac\alpha\beta=-z.$$ Because $z\in\Bbb{Q}$ it must be fixed under $\sigma$. So $z=\sigma(z)=-z$ implying that $z=0$. But if $z=0$, then $\alpha^2=\beta^2$ and hence $\alpha=\pm\beta$ which is absurd.
* Therefore $\sigma(\beta)$ must be $-\alpha$ and consequently also $\sigma(-\beta)=\alpha$. Thus $\sigma$ permutes the roots of $f$ in a 4-cycle:
$$\alpha\mapsto\beta\mapsto-\alpha\mapsto-\beta\mapsto\alpha.$$ Furthermore, we easily verify that this 4-cycle fixes $z$, so this fits the bill. We also conclude that $\sigma$ is of order four in $G$.
* If $\tau\in G$ is an automorphism that maps $\alpha$ to itself, we see that the composition $\sigma\tau$ also maps $\alpha$ to $\beta$. Repeating the earlier argument we see that $\sigma\tau$ must also act on the four zeros as the same 4-cycle. But, an automorphism in $G$ is uniquely determined by how it permutes the roots, so we can conclude that $\sigma\tau=\sigma$. Hence $\tau$ must be the identity.
* If $\tau\in G$ is arbitrary, then $\tau(\alpha)=\sigma^k(\alpha)$ for some choice of $k\in\{0,1,2,3\}$. This implies that $\sigma^{-k}\tau$ maps $\alpha$ to itself. By the previous bullet we can conclude that $\sigma^{-k}\tau=1\_G$. Hence $\tau=\sigma^k$.
* We have shown that $G$ is generated by $\sigma$. Therefore $G\simeq C\_4$. This, of course, also implies that $[K:\Bbb{Q}]=4$ and $K=\Bbb{Q}(\alpha)$. | Note, $G = Z\_4$ iff $b(a^2-4b)$ is a square, but $b(a^2 -4b) = (b \delta)^2$ for $\delta = \alpha/\beta - \beta/\alpha$. |
132,981 | In my story, one of the main characters (Joe) has been born with a somewhat superpower: Any person near him will have elevated neurotransmitter levels. If their brain is releasing happy neurotransmitters, then they will feel even more happy when in Joe's vicinity. If they are sad, they will verge on depression when the he approaches. This is the handwave, the upshot to all this is that any person nearby will experience stronger emotions.
My question is what effects the company of Joe will have over time. If they are friends of Joe, will they be addicted to his presence? If they are captives, will they die of a heart attack if they receive a sudden shock? Or are neurotransmitters not this magical? | 2018/12/15 | [
"https://worldbuilding.stackexchange.com/questions/132981",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/53812/"
] | A rather short-time effect would be that people would not be able to function anymore.
Neurotransmitters don't just dissappear the second we stop feeling happy or sad. They're chemicals that still course through the body, especially if a great amount of them was set free. More importantly, our bodies are designed to react to very small amounts of them. The systems of people around Joe would be so flooded with a mix of of differend transmitters that they would effectively be stoned all the time. Depending on which emotions they felt, it would be like a drug high or a bad trip or a mix of both.
Addiction or desensization to those transmitters would occur long-term, but even short-term these people wouldn't be able to think and act rationally. To an outsider they would seem druged or manic, stupid with love or hysteric. Their behavior would be immediately categorized as extreme. | >
> If they are friends of Joe, will they be addicted to his presence?
>
>
>
This is complicated.
The first thing you have to take into account is that the happy people around Joe will have an unbalanced amount of some neurotransmitters related to the feeling of content, joy or whatever. I am not a doctor, but to me this seems similar to having taken some kind of antidepressant drug without having any medical need for it.
[Science itself does not have a definitive answer about whether antidepressants are addictive:](https://www.addictioncenter.com/stimulants/antidepressants/)
>
> Antidepressant dependence can form in people who never needed the drugs in the first place. Some people are incorrectly diagnosed with depression and prescribed antidepressants. According to one study, doctors misdiagnosed almost two-thirds of patients with depression and prescribed unnecessary antidepressants.
>
>
> Doctors still debate the addictive nature of antidepressants. Most consider these drugs non-addictive. Others point to the withdrawal symptoms of antidepressants as evidence that a dependence can form. People who suddenly stop taking antidepressants often have withdrawal symptoms such as nausea, hand tremors and depression.
>
>
>
To complicate things, your character is not giving people around him a dose of antidepressants - he is giving them pure neurotransmitters, so it's even more difficult for us layspeople (and I think even for doctors too) to predict what would happen.
Now, while we don't know whether feelings of joy would make people addicted, I think feelings of sadness would. If you ever knew someone who was a goth or emo as a teenager you know what I am talking about. I lived close to a place which was a magnet for emos. I could hardly ever feel sad myself because just looking at them made me feel [expletive] happy by comparison, and that emo thing lasted like a decade.
>
> If they are captives, will they die of a heart attack if they receive a sudden shock? Or are neurotransmitters not this magical?
>
>
>
Whenever you hear something about someone dying from a heart attack due to some sad news, usually it's an elderly person who had some heart condition, and there are.other stresses involved; the sudden sadness is just the last drop that does them in, but there is always more to that. If sadness could kill through heart attack, every mother who had their child killed violently or unexpectedly would die too. |
347,615 | I have an application which takes an integer as input and based on the input calls static methods of different classes. Every time a new number is added, we need to add another case and call a different static method of a different class. There are now 50 cases in the switch and every time I need to add another case, I shudder. Is there a better way to do this.
I did some thinking and came up with this idea. I use the strategy pattern. Instead of having a switch case, I have a map of strategy objects with the key being the input integer. Once the method is invoked, it will look up the object and call the generic method for the object. This way I can avoid using the switch case construct.
What do you think? | 2017/04/23 | [
"https://softwareengineering.stackexchange.com/questions/347615",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/188637/"
] | A map of strategy objects alone, which is initialized in some function of your code, where you have several lines of code looking like
```
myMap.Add(1,new Strategy1());
myMap.Add(2,new Strategy2());
myMap.Add(3,new Strategy3());
```
requires you and your colleagues to implement the functions/strategies to be called in separate classes, in a more uniform manner (since your strategy objects will all have to implement the same interface). Such code is often a little bit more comprehensive than
```
case 1:
MyClass1.Doit1(someParameters);
break;
case 2:
MyClass2.Doit2(someParameters);
break;
case 3:
MyClass3.Doit3(someParameters);
break;
```
However, it still will not release you from the burden of editing this code file whenever a new number needs to be added. The real benefits of this approach is a different one:
* the initialization of the map now becomes separated from the dispatch code which actually *calls* the function associated to a specific number, and the latter does *not* contain those 50 repetitions any more, it will just look like `myMap[number].DoIt(someParameters)`. So this dispatch code does not need to be touched whenever a new number arrives and can be implemented according to the Open-Closed principle. Moreover, when you get requirements where you need to extend the dispatch code itself, you will not have to change 50 places any more, but only one.
* the content of the map is determined at run-time (whilst the content of the switch construct is determined before compile-time), so this gives you the opportunity to make the initialization logic more flexible or extendable.
So yes, there are some benefits, and this is surely a step towards more SOLID code. If it pays off to refactor, however, is something you or your team will have to decide by itself. If you do not expect the dispatch code to be changed, the initialization logic to be changed, and the readability of the `switch` is not a real problem, then your refactoring might not be so important now. | I am strongly in favor of the strategy outlined in [the answer by @DocBrown](https://softwareengineering.stackexchange.com/a/347616/116460).
I am going to suggest an improvement to the answer.
The calls
```
myMap.Add(1,new Strategy1());
myMap.Add(2,new Strategy2());
myMap.Add(3,new Strategy3());
```
can be distributed. You don't have to go back to the same file to add another strategy, which adheres to the Open-Closed principle even better.
Say you implement `Strategy1` in file Strategy1.cpp. You can have the following block of code in it.
```
namespace Strategy1_Impl
{
struct Initializer
{
Initializer()
{
getMap().Add(1, new Strategy1());
}
};
}
using namespace Strategy1_Impl;
static Initializer initializer;
```
You can repeat the same code in every StategyN.cpp file. As you can see, that will be a lot of repeated code. To reduce the code duplication, you can use a template which can be put in a file that is accessible to all the `Strategy` classes.
```
namespace StrategyHelper
{
template <int N, typename StrategyType> struct Initializer
{
Initializer()
{
getMap().Add(N, new StrategyType());
}
};
}
```
After that, the only thing you have to use in Strategy1.cpp is:
```
static StrategyHelper::Initializer<1, Strategy1> initializer;
```
The corresponding line in StrategyN.cpp is:
```
static StrategyHelper::Initializer<N, StrategyN> initializer;
```
---
You can take the use of templates to another level by using a class template for the concrete Strategy classes.
```
class Strategy { ... };
template <int N> class ConcreteStrategy;
```
And then, instead of `Strategy1`, use `ConcreteStrategy<1>`.
```
template <> class ConcreteStrategy<1> : public Strategy { ... };
```
Change the helper class to register `Strategy`s to:
```
namespace StrategyHelper
{
template <int N> struct Initializer
{
Initializer()
{
getMap().Add(N, new ConcreteStrategy<N>());
}
};
}
```
Change the code in Strateg1.cpp to:
```
static StrategyHelper::Initializer<1> initializer;
```
Change the code in StrategN.cpp to:
```
static StrategyHelper::Initializer<N> initializer;
``` |
3,553,779 | How do I dismiss the keyboard when a button is pressed? | 2010/08/24 | [
"https://Stackoverflow.com/questions/3553779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/454665/"
] | you can also use this code on button click event
```
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
``` | Kotlin:
=======
To dismiss the keyboard, call `clearFocus()` on the respective element when the button is clicked.
Example:
```
mSearchView.clearFocus()
``` |
67,290,697 | After upgrading Xcode to 12.5 and iOS to 14.5, I can't run the iOS app on a real device nor in the simulator.
After running `npm run ios`, I get this message:
```
The following build commands failed:
CompileC .../Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Flipper-Folly.build/Objects-normal/x86_64/DistributedMutex.o /Users/guilherme/Documents/Dood/ios/Pods/Flipper-Folly/folly/synchronization/DistributedMutex.cpp normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler
```
If I try to run the app on a real device using Xcode, this is the error I get (related to Flipper-Folly):
```
.../ios/Pods/Headers/Private/Flipper-Folly/folly/synchronization/DistributedMutex-inl.h:1051:5: 'atomic_notify_one<unsigned long>' is unavailable
```
Ideas? Thanks!
**UPDATE:**
React native has been updated to 0.64.1. You can now just change your react-native dependency to this version within your package.json file, then run `npm install` | 2021/04/27 | [
"https://Stackoverflow.com/questions/67290697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4064710/"
] | There is an open RN issue here: <https://github.com/facebook/react-native/issues/31179>
For me commenting out `Flipper` in the `Podfile`, `pod install`, and rebuild worked as a temp solution.
```rb
# Enables Flipper.
#
# Note that if you have use_frameworks! enabled, Flipper will not work and
# you should disable these next few lines.
# use_flipper!
# post_install do |installer|
# flipper_post_install(installer)
# end
``` | just comment out the flipper line in a pod and in Xcode also if you are not using it, hope this will fix in future updates.
```
# Note that if you have use_frameworks! enabled, Flipper will not work and
# you should disable the next line.
# use_flipper!({ 'Flipper' => '0.79.1'})
# post_install do |installer|
# react_native_post_install(installer)
# end
```
IN Xcode comment all import and flipper variable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.